From 8b56a75f19dea921c147774a7ea1244a3de88254 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:31 +0000 Subject: [PATCH 01/70] refactor(engine): move cmd/mod.rs to cmd.rs --- crates/engine/src/{cmd/mod.rs => cmd.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/engine/src/{cmd/mod.rs => cmd.rs} (100%) diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd.rs similarity index 100% rename from crates/engine/src/cmd/mod.rs rename to crates/engine/src/cmd.rs From 7445b8eee7b7d19207e0e574af215ae998340bd6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:31 +0000 Subject: [PATCH 02/70] refactor(engine): move cmd/datamerge/mod.rs to cmd/datamerge.rs --- crates/engine/src/cmd/{datamerge/mod.rs => datamerge.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/engine/src/cmd/{datamerge/mod.rs => datamerge.rs} (100%) diff --git a/crates/engine/src/cmd/datamerge/mod.rs b/crates/engine/src/cmd/datamerge.rs similarity index 100% rename from crates/engine/src/cmd/datamerge/mod.rs rename to crates/engine/src/cmd/datamerge.rs From 648ec777e42cdd9b3fa5f50934f79f9e4a78deac Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:32 +0000 Subject: [PATCH 03/70] refactor(ui-egui): move panels/mod.rs to panels.rs --- crates/ui-egui/src/{panels/mod.rs => panels.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/ui-egui/src/{panels/mod.rs => panels.rs} (100%) diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels.rs similarity index 100% rename from crates/ui-egui/src/panels/mod.rs rename to crates/ui-egui/src/panels.rs From 802388109a03e9228ce962cee062e8f0c3fb5f8f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:32 +0000 Subject: [PATCH 04/70] refactor(color): move cms/mod.rs to cms.rs --- crates/color/src/{cms/mod.rs => cms.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/color/src/{cms/mod.rs => cms.rs} (100%) diff --git a/crates/color/src/cms/mod.rs b/crates/color/src/cms.rs similarity index 100% rename from crates/color/src/cms/mod.rs rename to crates/color/src/cms.rs From 29d10be4352188291acc0acf6d038d8517367005 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:39 +0000 Subject: [PATCH 05/70] refactor(compose): move hyphen/mod.rs to hyphen.rs --- crates/compose/src/{hyphen/mod.rs => hyphen.rs} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename crates/compose/src/{hyphen/mod.rs => hyphen.rs} (99%) diff --git a/crates/compose/src/hyphen/mod.rs b/crates/compose/src/hyphen.rs similarity index 99% rename from crates/compose/src/hyphen/mod.rs rename to crates/compose/src/hyphen.rs index 57b75d63b..3f07f4b40 100644 --- a/crates/compose/src/hyphen/mod.rs +++ b/crates/compose/src/hyphen.rs @@ -26,8 +26,8 @@ use std::sync::OnceLock; pub use dict::Dictionary; pub use patterns::Patterns; -static EN_US_DIC: &[u8] = include_bytes!("../../../../assets/hyphenation/en-us.dic"); -static EN_US_PAT: &str = include_str!("../../../../assets/hyphenation/en-us.pat"); +static EN_US_DIC: &[u8] = include_bytes!("../../../assets/hyphenation/en-us.dic"); +static EN_US_PAT: &str = include_str!("../../../assets/hyphenation/en-us.pat"); impl Dictionary { /// The bundled US English dictionary (decoded on first use). From 9e7147da938057fb3628989d7d49f5699149f6ee Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:11 +0000 Subject: [PATCH 06/70] refactor(ui-egui): move the tests module of dialogs.rs to dialogs/tests.rs --- crates/ui-egui/src/dialogs.rs | 3524 +-------------------------- crates/ui-egui/src/dialogs/tests.rs | 3494 ++++++++++++++++++++++++++ 2 files changed, 3495 insertions(+), 3523 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 01f252c5a..e91d0696c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7400,3526 +7400,4 @@ fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn paragraph_style_settings_show_captured_color_and_pending_spacing_without_changing_the_document() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Heading"})).unwrap(); - app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":7})).unwrap(); - app.run("type.char", json!({"fontFamily":"Source Sans 3","fontStyle":"Bold","size":16,"fill":"[Paper]"})).unwrap(); - app.run("style.paragraph.create", json!({"name":"Header","fromSelection":true})).unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - let style = doc.styles.para("Header").unwrap(); - let mut d = Dialog::new("paragraphStyleOptions", json!({"name":"Header"})); - let summary = paragraph_style_summary("", &d, style, &doc.styles); - for value in ["Source Sans 3", "Bold", "16 pt", "[Paper]"] { - assert!(summary.contains(value), "{summary}"); - } - assert!(summary.len() < 250, "default attributes do not swamp the captured settings: {summary}"); - d.fields.insert("c.fill".into(), json!("[Registration]")); - d.fields.insert("p.spaceAfter".into(), json!(4.5)); - let summary = paragraph_style_summary("", &d, style, &doc.styles); - assert!(summary.contains("[Registration]") && !summary.contains("[Paper]"), "{summary}"); - assert!(summary.contains("4.5 pt"), "{summary}"); - assert_eq!(app.session.doc().unwrap().doc, doc); - } - - /// A dialog opened without the menu's fields has no `useDefaults` field at all. Confirming it - /// with no layer unticked must keep the file's defaults, not choose every layer explicitly: - /// an implicit all-on choice is rejected for a PDF without layers, so the command's error - /// tells the two apart. - #[test] - fn layer_options_confirm_without_the_menu_fields_keeps_file_defaults() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 100, "height": 100, "pages": 1})).unwrap(); - let pdf = app.run("file.exportPdf", json!({})).unwrap()["base64"].clone(); - let placed = app.run("file.place", json!({"base64": pdf, "name": "plain.pdf", "x": 0, "y": 0, "width": 100})).unwrap(); - let id = designcraft_doc::ItemId(placed["id"].as_u64().unwrap()); - app.run("selection.set", json!({"ids": [placed["id"]]})).unwrap(); - app.ui.dialog = Some(Dialog::new("layerOptions", json!({}))); - confirm(&mut app).unwrap(); - assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "an untouched dialog keeps the file defaults"); - // The menu's own dialog still asks for an explicit all-on choice when that is the state - // it was opened in; a layerless PDF refuses it rather than accepting an empty override. - app.ui.dialog = Some(Dialog::new("layerOptions", json!({"useDefaults": false, "layers": []}))); - let err = confirm(&mut app).unwrap_err(); - assert!(err.contains("could not be changed"), "{err}"); - assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "a layerless PDF never takes an explicit choice"); - } - - #[test] - fn paragraph_style_settings_compare_with_the_chosen_parent() { - let mut styles = designcraft_doc::Styles::default(); - styles.paragraph.push(designcraft_doc::ParagraphStyle { - name: "Parent".into(), - chars: designcraft_doc::CharAttrs { size: Some(20.0), ..Default::default() }, - based_on: None, - next_style: None, - para: Default::default(), - shortcut: String::new(), - }); - let style = designcraft_doc::ParagraphStyle { - name: "Child".into(), - based_on: Some("Parent".into()), - next_style: None, - para: Default::default(), - chars: Default::default(), - shortcut: String::new(), - }; - let d = Dialog::new("paragraphStyleOptions", json!({"name":"Child"})); - assert_eq!(paragraph_style_summary("", &d, &style, &styles), "Parent"); - } - - #[test] - fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - let open = |app: &mut DesignApp| { - crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT)); - }; - let set = |app: &mut DesignApp, k: &str, v: Value| { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); - }; - let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len(); - let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len(); - let (n0, u0) = (items(&app), undo(&app)); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); - open(&mut app); - dialog_frame(&mut app, &ctx, screen, vec![]); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] { - visible_label(&labels, screen, expected); - } - // Preview: the copies show, and change with the fields, without an undo step. - set(&mut app, "count", json!("5")); - set(&mut app, "vertical", json!("-0.75 in")); - set(&mut app, "horizontal", json!("0")); - set(&mut app, "preview", json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!((items(&app), undo(&app)), (n0 + 5, u0)); - set(&mut app, "count", json!("3")); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(items(&app), n0 + 3); - set(&mut app, "preview", json!(false)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(items(&app), n0, "Preview off takes them away"); - set(&mut app, "preview", json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(items(&app), n0 + 3); - // Cancel puts the document back. - cancel(&mut app); - assert!(app.ui.dialog.is_none()); - assert_eq!((items(&app), undo(&app)), (n0, u0)); - // OK after a preview makes the copies once, as one undo step, 0.75 in apart. - app.run("selection.set", json!({"ids": [id]})).unwrap(); - open(&mut app); - set(&mut app, "count", json!("2")); - set(&mut app, "vertical", json!("-0.75 in")); - set(&mut app, "horizontal", json!("0")); - set(&mut app, "preview", json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let r = confirm(&mut app).unwrap(); - assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1)); - let last = r["ids"][1].as_u64().unwrap(); - let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y(); - assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}"); - // Create as a grid: Rows × Columns cells, the original being one. - app.run("selection.set", json!({"ids": [id]})).unwrap(); - open(&mut app); - set(&mut app, "grid", json!(true)); - set(&mut app, "rows", json!("2")); - set(&mut app, "columns", json!("3")); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "Rows:"); - visible_label(&labels, screen, "Columns:"); - assert_eq!(confirm(&mut app).unwrap()["created"], 5); - // A value that isn't a measure keeps the dialog open and says so. - open(&mut app); - set(&mut app, "vertical", json!("up")); - assert!(confirm(&mut app).is_err()); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.s("status"), "Invalid value: up"); - } - - /// A three-page document in `units` with Document Setup open. - fn document_setup_app(units: &str) -> DesignApp { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 3})).unwrap(); - app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap(); - crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); - app - } - - fn setup_fields(app: &mut DesignApp, fields: Value) { - let d = app.ui.dialog.as_mut().unwrap(); - for (k, v) in fields.as_object().unwrap() { - d.fields.insert(k.clone(), v.clone()); - } - } - - /// File › File Info opens filled from the document and OK stores what was typed; Export PDF - /// then names the file after the document and takes the PDF's title from File Info. - #[test] - fn file_info_dialog_stores_the_fields_and_titles_the_pdf() { - use std::sync::{Arc, Mutex}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"title": "flyer-v3"})).unwrap(); - app.run("file.info", json!({"author": "Ana Ruiz", "keywords": ["spring", "shoes"]})).unwrap(); - crate::menus::activate(&mut app, "file.info", &Value::Null); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.id, "fileInfo"); - assert_eq!((d.s("documentTitle"), d.s("author"), d.s("keywords")), (String::new(), "Ana Ruiz".into(), "spring; shoes".into())); - setup_fields(&mut app, json!({"documentTitle": "Spring Catalog", "author": "", "keywords": "spring, catalog", "description": "Shoes"})); - confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - let info = app.session.active().unwrap().doc.file_info.clone(); - assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "", "Shoes")); - assert_eq!(info.keywords, ["spring", "catalog"]); - // Keywords left as shown stay as they are, even one with a comma in it. - app.run("file.info", json!({"keywords": ["Washington, DC", "map"]})).unwrap(); - crate::menus::activate(&mut app, "file.info", &Value::Null); - setup_fields(&mut app, json!({"author": "Studio"})); - confirm(&mut app).unwrap(); - let info = app.session.active().unwrap().doc.file_info.clone(); - assert_eq!((info.author.as_str(), info.keywords.clone()), ("Studio", vec!["Washington, DC".to_string(), "map".to_string()])); - // Another keyword edited: the one with a comma in it still stays one keyword. - crate::menus::activate(&mut app, "file.info", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("keywords"), "Washington, DC; map"); - setup_fields(&mut app, json!({"keywords": "Washington, DC; atlas"})); - confirm(&mut app).unwrap(); - assert_eq!(app.session.active().unwrap().doc.file_info.keywords, ["Washington, DC", "atlas"]); - - let writes: Arc>>> = Arc::new(Mutex::new(Vec::new())); - let sink = writes.clone(); - app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| { - sink.lock().unwrap().push(bytes.to_vec()); - Ok(()) - })); - let names: Arc>> = Arc::new(Mutex::new(Vec::new())); - let asked = names.clone(); - app.services.pick_save = Some(Box::new(move |name: &str| { - asked.lock().unwrap().push(name.to_string()); - Some("/tmp/designcraft-file-info.pdf".to_string()) - })); - open_pdf_export(&mut app); - confirm(&mut app).unwrap(); - assert_eq!(names.lock().unwrap().as_slice(), ["flyer-v3.pdf"]); - let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[0]).into_owned(); - assert!(pdf.contains("/Title(Spring Catalog)") && !pdf.contains("/Title(flyer-v3)"), "the PDF's title is File Info's"); - // A title given to the export is the PDF's title, even when it is the document's name. - open_pdf_export(&mut app); - setup_fields(&mut app, json!({"title": "flyer-v3"})); - confirm(&mut app).unwrap(); - let asked = names.lock().unwrap().last().cloned().unwrap_or_default(); - assert_eq!(std::path::Path::new(&asked).file_name().and_then(|n| n.to_str()), Some("flyer-v3.pdf"), "{asked}"); - let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[1]).into_owned(); - assert!(pdf.contains("/Title(flyer-v3)") && !pdf.contains("/Title(Spring Catalog)"), "the given title wins"); - } - - /// File Info's OK stores the fields in the document the dialog was opened for, even when - /// another document became active meanwhile; once that document has closed, OK stores nothing. - #[test] - fn file_info_dialog_stores_into_the_document_it_was_opened_for() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"title": "first"})).unwrap(); - crate::menus::activate(&mut app, "file.info", &Value::Null); - app.run("file.new", json!({"title": "second"})).unwrap(); - setup_fields(&mut app, json!({"author": "Ana Ruiz"})); - confirm(&mut app).unwrap(); - let docs = app.session.documents(); - let author = |title: &str| docs.iter().find(|d| d.doc.title == title).map(|d| d.doc.file_info.author.clone()); - assert_eq!((author("first").as_deref(), author("second").as_deref()), (Some("Ana Ruiz"), Some(""))); - assert_eq!(app.session.active().map(|d| d.doc.title.as_str()), Some("second"), "the active document stays active"); - - crate::menus::activate(&mut app, "file.info", &Value::Null); - app.run("file.close", json!({})).unwrap(); - setup_fields(&mut app, json!({"author": "Studio"})); - confirm(&mut app).unwrap(); - assert!(app.session.documents().iter().all(|d| d.doc.file_info.author != "Studio"), "the dialog's document closed"); - } - - /// File Info opened through `ui.dialog.open` with only some fields stores only those fields; - /// the others keep what the document holds. - #[test] - fn file_info_opened_with_some_fields_keeps_the_others() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("file.info", json!({"documentTitle": "Spring Catalog", "keywords": ["spring", "shoes"]})).unwrap(); - assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": {"author": "Ana Ruiz", "description": ""}}))["ok"], true); - confirm(&mut app).unwrap(); - let info = app.session.active().unwrap().doc.file_info.clone(); - assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "Ana Ruiz", "")); - assert_eq!(info.keywords, ["spring", "shoes"]); - } - - /// Fields given to `ui.dialog.open` as JSON other than text reach `file.info` as they are: a - /// keyword list stays a list, and `null` clears a field. - #[test] - fn file_info_opened_with_a_keyword_list_stores_the_list() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("file.info", json!({"author": "Ana Ruiz"})).unwrap(); - let fields = json!({"keywords": ["Washington, DC", "map"], "author": null}); - assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": fields}))["ok"], true); - confirm(&mut app).unwrap(); - let info = app.session.active().unwrap().doc.file_info.clone(); - assert_eq!(info.keywords, ["Washington, DC", "map"]); - assert_eq!(info.author, ""); - } - - /// File Info's OK for a document that is not the active one leaves the active document's - /// Data Merge preview showing the record it showed. - #[test] - fn file_info_for_another_document_keeps_the_active_preview() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"title": "first"})).unwrap(); - crate::menus::activate(&mut app, "file.info", &Value::Null); - app.run("file.new", json!({"title": "second"})).unwrap(); - let csv = designcraft_engine::cmd::base64_encode(b"Name\nAda\nGrace\n"); - app.run("data.source.select", json!({"bytes": csv, "name": "people.csv"})).unwrap(); - app.run("data.preview", json!({"record": 2})).unwrap(); - setup_fields(&mut app, json!({"author": "Ana Ruiz"})); - confirm(&mut app).unwrap(); - let active = app.session.active().unwrap(); - assert_eq!((active.doc.title.as_str(), active.preview_record), ("second", Some(2)), "the preview still shows record 2"); - let first = app.session.documents().iter().find(|d| d.doc.title == "first").map(|d| d.doc.file_info.author.clone()); - assert_eq!(first.as_deref(), Some("Ana Ruiz")); - } - - #[test] - fn document_setup_ok_applies_margins_bleed_and_size_in_one_step() { - let mut app = document_setup_app("millimeters"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.id, "documentSetup"); - assert_eq!((d.s("marginTop"), d.b("marginLinked")), ("12.7 mm".to_string(), true), "the document's margins, in its units"); - setup_fields( - &mut app, - json!({"marginTop": "20 mm", "marginBottom": "20 mm", "marginInside": "20 mm", "marginOutside": "20 mm", "bleedTop": "3 mm", - "bleedBottom": "3 mm", "bleedInside": "3 mm", "bleedOutside": "3 mm", "width": "210 mm", "height": "297 mm"}), - ); - confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - let mm = designcraft_geom::units::PT_PER_MM; - let doc = &app.session.active().unwrap().doc; - assert!((doc.settings.page_width - 210.0 * mm).abs() < 1e-6 && (doc.settings.bleed[2] - 3.0 * mm).abs() < 1e-6); - assert!(doc.spreads.iter().flat_map(|s| &s.pages).all(|p| (p.margins.top - 20.0 * mm).abs() < 1e-6), "every page"); - app.run("edit.undo", json!({})).unwrap(); - let doc = &app.session.active().unwrap().doc; - assert!((doc.settings.page_width - 612.0).abs() < 1e-6 && doc.settings.bleed[0] == 0.0, "one undo step"); - } - - #[test] - fn document_setup_reads_a_bare_number_in_the_documents_units() { - let mut app = document_setup_app("millimeters"); - setup_fields(&mut app, json!({"bleedTop": "5", "bleedBottom": "5", "bleedInside": "5", "bleedOutside": "5", "width": "210"})); - confirm(&mut app).unwrap(); - let mm = designcraft_geom::units::PT_PER_MM; - let settings = &app.session.active().unwrap().doc.settings; - assert!(settings.bleed.iter().all(|b| (b - 5.0 * mm).abs() < 1e-6), "5 mm, not 5 picas: {:?}", settings.bleed); - assert!((settings.page_width - 210.0 * mm).abs() < 1e-6, "{}", settings.page_width); - } - - #[test] - fn document_setup_keeps_each_pages_margins_unless_they_are_edited() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 3, "margins": 36})).unwrap(); - app.run("layout.marginsAndColumns", json!({"pages": [1], "margins": 90})).unwrap(); - let margins = - |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| p.margins.top).collect::>(); - // Only the page count changes: every page keeps its own margins. - crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); - setup_fields(&mut app, json!({"pages": "4"})); - confirm(&mut app).unwrap(); - assert_eq!(margins(&app), [36.0, 90.0, 36.0, 36.0]); - // Edited margins go to every page. - crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); - setup_fields(&mut app, json!({"marginTop": "1p0"})); - confirm(&mut app).unwrap(); - assert_eq!(margins(&app), [12.0; 4]); - } - - #[test] - fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() { - for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] { - let mut app = document_setup_app("points"); - setup_fields(&mut app, json!({key: value, "bleedInside": "9"})); - assert!(confirm(&mut app).is_err(), "{key}"); - assert!(app.ui.dialog.is_some(), "{key}: the dialog stays open"); - assert_eq!(app.session.active().unwrap().doc.settings.bleed, [0.0; 4], "{key}: nothing changed"); - } - } - - #[test] - fn document_setup_links_edges_and_adjust_layout_applies() { - let mut app = document_setup_app("points"); - let f = app.run("frame.create", json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap(); - crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 900.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - // Typing in a linked margin sets all four. - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let top = labels.iter().filter(|(t, _, _)| t == "36 pt").map(|(_, r, _)| *r).next().expect("the top margin"); - click_dialog(&mut app, &ctx, screen, top.center()); - let select_all = - egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; - dialog_frame(&mut app, &ctx, screen, vec![select_all, egui::Event::Text("72 pt".into())]); - dialog_frame(&mut app, &ctx, screen, vec![]); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(["Top", "Bottom", "Inside", "Outside"].iter().all(|e| d.s(&format!("margin{e}")) == "72 pt"), "linked: {:?}", d.fields); - // Adjust Layout applies at once, and the frame follows the margins. - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Adjust Layout").center()); - assert!(app.ui.dialog.is_none(), "applied"); - let doc = &app.session.active().unwrap().doc; - let b = doc.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds(); - assert!((b.y0 - 72.0).abs() < 1e-6 && doc.page(0).unwrap().margins.outside == 72.0, "{b:?}"); - } - - #[test] - fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap(); - let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); - app.run("table.select", json!({"what": "table"})).unwrap(); - app.run("app.cellOptionsDialog", json!({})).unwrap(); - let ctx = dialog_context(""); - dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!(d.id, "cellOptions"); - assert_eq!(d.fields["weight"], json!(1.0)); - d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"])); - d.fields.insert("gapColor".into(), json!("[Paper]")); - d.fields.insert("fill".into(), json!("[Black]")); - d.fields.insert("fillTint".into(), json!(0.2)); - confirm(&mut app).unwrap(); - let st = app.session.active().unwrap(); - let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap(); - let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone(); - assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges"); - assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs"); - assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6)); - assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied"); - } - - #[test] - fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap(); - let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); - app.run("table.select", json!({"what": "table"})).unwrap(); - app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap(); - app.run("app.cellOptionsDialog", json!({})).unwrap(); - let mut d = app.ui.dialog.take().unwrap(); - d.fields.insert("seed".into(), json!(5)); - let outer = [true, true, true, true, false, false]; - cell_options_edges_changed(&mut app, &mut d, &outer); - assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0))); - // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen - // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it. - d.fields.insert("weight".into(), json!(5.0)); - cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]); - assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0))); - d.fields.insert("weight".into(), json!(1.0)); - app.ui.dialog = Some(d); - confirm(&mut app).unwrap(); - let st = app.session.active().unwrap(); - let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap(); - assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]); - } - - #[test] - fn preferences_ok_saves_a_story_editor_size_that_loads_back() { - // `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`. - let sizes = [(json!("nan"), 20.0), (json!("inf"), 20.0), (json!(null), 20.0), (json!(1e39), 36.0), (json!(3), 8.0), (json!(11), 11.0)]; - for (size, want) in sizes { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.ui.story_editor_size = 20.0; - app.run("app.preferences", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("storyEditorSize".into(), size); - confirm(&mut app).unwrap(); - let saved = serde_json::to_vec(&app.ui).unwrap(); - assert_eq!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_size, want); - } - } - - #[test] - fn preferences_ok_sets_only_the_ruler_units_it_is_given() { - // `ui.dialog.open` takes any fields, so the vertical units can be missing. - for (vertical, want) in [(None, "inches"), (Some("points"), "points")] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("document.preferences", json!({"verticalUnits": "inches"})).unwrap(); - let mut fields = json!({"horizontalUnits": "millimeters", "bg.relativeTo": "topOfPage"}); - if let Some(vertical) = vertical { - fields["verticalUnits"] = json!(vertical); - } - app.ui.dialog = Some(Dialog::new("preferences", fields)); - confirm(&mut app).unwrap(); - let units = app.run("document.preferences", json!({})).unwrap(); - assert_eq!((units["horizontalUnits"].as_str(), units["verticalUnits"].as_str()), (Some("millimeters"), Some(want))); - } - } - - #[test] - fn enter_and_escape_close_the_style_menu_not_numbering_and_section_options() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 2})).unwrap(); - crate::menus::activate(&mut app, "layout.section", &Value::Null); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - for pressed in [egui::Key::Enter, egui::Key::Escape] { - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - // The section's Style menu (the first of the two). - let style = labels.iter().filter(|(t, r, c)| t.trim() == "1, 2, 3, 4…" && c.contains_rect(*r)).map(|(_, r, _)| *r).next().unwrap(); - click_dialog(&mut app, &ctx, screen, style.center()); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(egui::Popup::is_any_open(&ctx), "the Style menu opened"); - dialog_frame(&mut app, &ctx, screen, vec![key(pressed)]); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(app.ui.dialog.is_some(), "{pressed:?} with the menu open leaves the dialog open"); - assert!(app.session.active().unwrap().doc.sections.iter().all(|s| s.start_number != Some(0))); - if egui::Popup::is_any_open(&ctx) { - egui::Popup::close_all(&ctx); - dialog_frame(&mut app, &ctx, screen, vec![]); - } - } - // With no menu open, Escape closes the dialog. - dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Escape)]); - assert!(app.ui.dialog.is_none()); - } - - #[test] - fn numbering_and_section_options_keep_their_actions_in_view() { - for language in ["en", "ar"] { - for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.language = language.into(); - app.run("file.new", json!({"pages": 2})).unwrap(); - crate::menus::activate(&mut app, "layout.section", &Value::Null); - let ctx = dialog_context(language); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let tr = |s| crate::i18n::tr(language, s); - for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] { - visible_label(&labels, screen, expected); - } - if size.x > 1000.0 { - // Every option fits without scrolling, and choosing one then OK applies it. - visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A"))); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center()); - assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog"); - let doc = &app.session.active().unwrap().doc; - assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically"); - } - } - } - } - - fn select_all_key() -> egui::Event { - egui::Event::Key { - key: egui::Key::A, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() }, - } - } - - /// The Color Picker over a new document's selected frame, a few frames in. - fn picker(fields: Value) -> (DesignApp, egui::Context, egui::Rect, u64) { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - app.ui.dialog = Some(Dialog::new("colorPicker", fields)); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 500.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - (app, ctx, screen, id) - } - - /// The rightmost painted `text`: the picker's own field, right of egui's colour editor (which - /// has R/G/B fields of its own). - fn rightmost(labels: &[(String, egui::Rect, egui::Rect)], text: &str) -> egui::Pos2 { - labels - .iter() - .filter(|(t, _, _)| t.trim() == text) - .map(|(_, r, _)| r.center()) - .max_by(|a, b| a.x.total_cmp(&b.x)) - .unwrap_or_else(|| panic!("{text} is painted")) - } - - /// Types `text` one character per frame, with an idle frame after each. - fn type_slowly(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, text: &str) { - for ch in text.chars() { - dialog_frame(app, ctx, screen, vec![egui::Event::Text(ch.into())]); - dialog_frame(app, ctx, screen, vec![]); - } - } - - fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color { - let d = &app.session.active().unwrap().doc; - d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap() - } - - #[test] - fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() { - let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ffffff"})); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "ffffff").center()); - dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); - type_slowly(&mut app, &ctx, screen, "#f5"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f5", "#ffffff"), "half-typed text stays; the colour waits"); - type_slowly(&mut app, &ctx, screen, "9019"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f59019", "#f59019"), "a 7-character #rrggbb commits"); - // Invalid text is replaced by the colour when focus leaves. - dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); - type_slowly(&mut app, &ctx, screen, "zz"); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#").center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "f59019"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019"); - } - - #[test] - fn typed_channel_values_are_kept_while_typing() { - let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]})); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, rightmost(&labels, "1")); - dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); - type_slowly(&mut app, &ctx, screen, "12.5"); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(rightmost(&labels, "12.5").x > rightmost(&labels, "2").x - 1.0, "the typed text stays in the R field"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203"); - confirm(&mut app).unwrap(); - let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") }; - assert!((r - 12.5 / 255.0).abs() < 1e-6, "{r}"); - } - - #[test] - fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() { - let cmyk = json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]}); - // Picked by hex: converted to CMYK. - let (mut app, ctx, screen, id) = picker(cmyk.clone()); - let hex = app.ui.dialog.as_ref().unwrap().s("hex"); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, hex.trim_start_matches('#')).center()); - dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); - type_slowly(&mut app, &ctx, screen, "3366cc"); - confirm(&mut app).unwrap(); - assert!(matches!(fill(&app, id), designcraft_color::Color::Cmyk { .. }), "{:?}", fill(&app, id)); - // A typed C/M/Y/K percent is a percent: M 1 is 1 %. - let (mut app, ctx, screen, id) = picker(cmyk.clone()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, rightmost(&labels, "50")); - dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); - type_slowly(&mut app, &ctx, screen, "1"); - confirm(&mut app).unwrap(); - let designcraft_color::Color::Cmyk { c, m, y, k } = fill(&app, id) else { panic!("not CMYK") }; - assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}"); - // Typed R/G/B values: RGB. - let (mut app, ctx, screen, id) = picker(cmyk); - let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap(); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, rightmost(&labels, &r.to_string())); - dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); - type_slowly(&mut app, &ctx, screen, "10"); - confirm(&mut app).unwrap(); - assert!(matches!(fill(&app, id), designcraft_color::Color::Rgb { .. }), "{:?}", fill(&app, id)); - } - - #[test] - fn ok_without_edits_leaves_the_fill_alone() { - let (mut app, _, _, id) = picker(json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]})); - let before = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.clone(); - confirm(&mut app).unwrap(); - assert_eq!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill, before); - } - - #[test] - fn dialogs_do_not_dim_the_page() { - let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ff8000"})); - let time = ctx.input(|i| i.time) + 1.0 / 60.0; - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(&mut app, ui.ctx())); - fn covers(shape: &egui::Shape, screen: egui::Rect) -> bool { - match shape { - egui::Shape::Rect(r) => r.rect.contains_rect(screen) && r.fill.a() > 0, - egui::Shape::Vec(v) => v.iter().any(|s| covers(s, screen)), - _ => false, - } - } - assert!(app.ui.dialog.is_some()); - assert!(!output.shapes.iter().any(|s| covers(&s.shape, screen)), "nothing paints over the whole window"); - } - - fn draw(app: &mut DesignApp, ctx: &egui::Context) { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - } - - /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled". - fn ruled_paragraph() -> (DesignApp, Value) { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0}); - app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap(); - let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap(); - app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); - app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap(); - (app, rule) - } - - fn undo_steps(app: &DesignApp) -> usize { - app.session.doc().map_or(0, |st| st.history.undo.len()) - } - - #[test] - fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() { - let (mut app, rule) = ruled_paragraph(); - let ctx = egui::Context::default(); - app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap(); - draw(&mut app, &ctx); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!(d.id, "paragraphRules"); - let current = d.fields["current"].clone(); - assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule"); - assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false); - // Pick a colour, as the Color menu does. - app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]")); - draw(&mut app, &ctx); - let before = undo_steps(&app); - confirm(&mut app).unwrap(); - assert_eq!(undo_steps(&app), before + 1, "one undo step"); - let mut want = rule.clone(); - want["color"] = json!("[Registration]"); - assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule); - } - - #[test] - fn paragraph_style_options_edit_one_rule_field() { - let (mut app, rule) = ruled_paragraph(); - let ctx = egui::Context::default(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); - draw(&mut app, &ctx); - let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style"); - app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5)); - draw(&mut app, &ctx); - let before = undo_steps(&app); - confirm(&mut app).unwrap(); - assert_eq!(undo_steps(&app), before + 1, "one undo step"); - let mut want = rule.clone(); - want["weight"] = json!(1.5); - assert_eq!(resolved(&app)["ruleBelow"], want); - assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(resolved(&app)["ruleBelow"], rule); - } - - /// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and - /// clicks OK; returns the resolved attributes of the paragraph styled with it. - fn style_section_edit(sections: &[&str], fields: Value) -> Value { - let (mut app, _) = ruled_paragraph(); - let ctx = egui::Context::default(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"}))); - for section in sections { - app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section)); - draw(&mut app, &ctx); - } - for (k, v) in fields.as_object().unwrap() { - app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone()); - } - draw(&mut app, &ctx); - let before = undo_steps(&app); - confirm(&mut app).unwrap(); - assert_eq!(undo_steps(&app), before + 1, "one undo step"); - let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); - let own = serde_json::to_value(&style.para).unwrap(); - for (k, v) in fields.as_object().unwrap() { - assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}"); - } - app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone() - } - - #[test] - fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() { - let para = style_section_edit( - &["keep", "border"], - json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3, - "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}), - ); - assert_eq!(para["keepWithNext"], 2); - assert_eq!(para["keepLinesTogether"], true); - assert_eq!(para["keepAllLines"], false); - assert_eq!(para["keepFirst"], 3); - assert_eq!(para["startParagraph"], "nextPage"); - assert_eq!(para["borderOn"], true); - assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0])); - // Fields not edited keep the resolved value. - assert_eq!(para["keepLast"], 2); - assert_eq!(para["ruleBelow"]["weight"], 3.0); - } - - #[test] - fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() { - let para = style_section_edit( - &["bullets", "span"], - json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3, - "p.spanColumns": {"kind": "split", "columns": 3}}), - ); - assert_eq!(para["listType"], "numbers"); - assert_eq!(para["numberStyle"], "upperRoman"); - assert_eq!(para["numberExpression"], "^#)^t"); - assert_eq!(para["startAt"], 3); - assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3})); - let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap(); - assert_eq!(props.number_label(3), "III)\t"); - } - - #[test] - fn paragraph_style_options_ignore_optical_margin_is_set_on_ok() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Flush"})).unwrap(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Flush", "section": "indents"}))); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::unique("ignore_optical_margin_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(3); - h.get_by_label("Ignore Optical Margin").click(); - h.run_steps(3); - h.get_by_label(" OK ").click(); - h.run_steps(3); - let app = h.state(); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.doc().unwrap().doc.styles.para("Flush").unwrap().para.ignore_optical_margin, Some(true)); - } - - #[test] - fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() { - let (mut app, _) = ruled_paragraph(); - let ctx = egui::Context::default(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"}))); - draw(&mut app, &ctx); - app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}])); - let e = confirm(&mut app).unwrap_err(); - assert!(e.contains("bad GREP"), "{e}"); - let d = app.ui.dialog.clone().expect("the dialog stays open"); - assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true)); - assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved"); - draw(&mut app, &ctx); - } - - #[test] - fn paragraph_style_options_show_a_refused_rename_on_general_and_trim_a_new_name() { - let (mut app, _) = ruled_paragraph(); - let ctx = egui::Context::default(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "rules"}))); - draw(&mut app, &ctx); - app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!("Ruled Child")); - let e = confirm(&mut app).unwrap_err(); - let d = app.ui.dialog.clone().expect("the dialog stays open"); - assert_eq!(d.s("section"), "general", "the name field is on General"); - assert!(d.s("status").contains("already exists"), "{e}"); - - app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!(" Fresh ")); - app.ui.dialog.as_mut().unwrap().fields.insert("x.tag".into(), json!("h3")); - confirm(&mut app).unwrap(); - let st = &app.session.doc().unwrap().doc.styles; - assert!(st.para("Fresh").is_some()); - assert_eq!(st.export_tag("Fresh", false).map(|t| t.tag.as_str()), Some("h3")); - } - - /// A frame with two paragraphs of [Basic Paragraph]; the first has a local Word Spacing minimum. - fn two_paragraphs() -> (DesignApp, Value) { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One\nTwo"})).unwrap(); - app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); - app.run("type.para", json!({"attrs": {"wordSpaceMin": 0.7}})).unwrap(); - (app, r["story"].clone()) - } - - /// The resolved paragraph attribute `key` of the paragraph at byte `at`. - fn para_attr(app: &mut DesignApp, story: &Value, at: usize, key: &str) -> Value { - app.run("text.select", json!({"story": story, "anchor": at, "focus": at})).unwrap(); - app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone() - } - - /// The hyphenation video (Graphd Tutorials, 0:39–1:13): the Paragraph panel menu's - /// Hyphenation… opens InDesign's Hyphenation Settings for the selected paragraphs. Preview - /// shows the slider moved to Fewer Hyphens on the page without an undo step, OK makes it one - /// step on the selected paragraph only, and Cancel puts it back. - #[test] - fn hyphenation_settings_preview_apply_and_cancel_on_the_selected_paragraph() { - let (mut app, story) = two_paragraphs(); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); - let sid = designcraft_doc::StoryId(story.as_u64().unwrap()); - let weight = |app: &DesignApp, para: usize| { - let d = &app.session.doc().unwrap().doc; - d.styles.resolve_para(&d.story(sid).unwrap().paras[para]).0.hyph_weight - }; - assert!(crate::menus::menu_enabled(&app, "app.hyphenationDialog")); - app.run("app.hyphenationDialog", json!({})).unwrap(); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!( - (d.id.as_str(), d.fields["current"]["hyphWeight"].as_f64(), d.fields["current"]["hyphenate"].as_bool()), - ("hyphenation", Some(0.5), Some(true)) - ); - for label in [ - "Hyphenation Settings", - "Hyphenate", - "Words with at Least:", - "letters", - "Hyphen Limit:", - "hyphens", - "Hyphenation Zone:", - "Better Spacing", - "Fewer Hyphens", - "Hyphenate Capitalized Words", - "Hyphenate Last Word", - "Hyphenate Across Column", - "Preview", - ] { - assert!(labels.iter().any(|(t, _, _)| t == label), "{label}: {labels:?}"); - } - // Fewer Hyphens (9 of 10) with Preview: on the page, no undo step. - let before = undo_steps(&app); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("hyphWeight".into(), json!(0.9)); - d.fields.insert("preview".into(), json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(weight(&app, 0), 0.9, "previewed"); - assert_eq!(undo_steps(&app), before, "a preview is no step"); - // Cancel: back as it was. - cancel(&mut app); - assert_eq!(weight(&app, 0), 0.5); - // Again, and OK: one step, the selected paragraph only. - app.run("app.hyphenationDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("hyphWeight".into(), json!(0.9)); - d.fields.insert("preview".into(), json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - confirm(&mut app).unwrap(); - assert_eq!((weight(&app, 0), weight(&app, 1)), (0.9, 0.5)); - assert_eq!(undo_steps(&app), before + 1, "one undo step"); - // Paragraph Style Options › Hyphenation has the same form. - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": "hyph"}))); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for label in ["Hyphenation Zone:", "Better Spacing", "Fewer Hyphens", "Hyphenate Last Word", "Hyphenate Across Column"] { - assert!(labels.iter().any(|(t, _, _)| t == label), "style options: {label}"); - } - app.ui.dialog = None; - app.run("edit.deselectAll", json!({})).unwrap(); - assert!(!crate::menus::menu_enabled(&app, "app.hyphenationDialog"), "no paragraph"); - } - - /// Hyphenate differs across the selection: it shows mixed, and the first click turns it on for - /// all. Settings the command refuses show why: a preview goes back and isn't retried until they - /// change, and OK keeps the dialog open. - /// A mixed Better Spacing ↔ Fewer Hyphens slider: a click on its middle step sets every - /// selected paragraph to it, though the knob already sat there. - #[test] - fn hyphenation_settings_mixed_slider_click_sets_the_step() { - let (mut app, story) = two_paragraphs(); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); - app.run("type.para", json!({"attrs": {"hyphWeight": 0.2}})).unwrap(); - app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); - app.run("app.hyphenationDialog", json!({})).unwrap(); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let rect = |l: &str| labels.iter().find(|(t, _, _)| t == l).map(|(_, r, _)| *r).unwrap(); - let (better, fewer) = (rect("Better Spacing"), rect("Fewer Hyphens")); - click_dialog(&mut app, &ctx, screen, egui::pos2((better.right() + fewer.left()) / 2.0, better.center().y)); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphWeight"), Some(&json!(0.5))); - } - - #[test] - fn hyphenation_settings_mixed_checkbox_and_refused_settings() { - let (mut app, story) = two_paragraphs(); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); - app.run("type.para", json!({"attrs": {"hyphenate": false}})).unwrap(); - app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); - app.run("app.hyphenationDialog", json!({})).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().fields["current"]["hyphenate"].is_null(), "mixed"); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let at = labels.iter().find(|(t, _, _)| t == "Hyphenate").map(|(_, r, _)| r.left_center() - egui::vec2(10.0, 0.0)).unwrap(); - click_dialog(&mut app, &ctx, screen, at); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphenate"), Some(&json!(true)), "the first click turns it on"); - // A refused setting (as a control-channel caller could send it): no preview, the reason. - let before = undo_steps(&app); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("hyphWeight".into(), json!("heavy")); - d.fields.insert("preview".into(), json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(!d.fields.contains_key(PREVIEWED) && d.fields.contains_key("status"), "{:?}", d.fields); - assert!(app.session.doc().unwrap().interaction.is_none(), "the preview went back"); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(app.session.doc().unwrap().interaction.is_none(), "not tried again"); - // OK with it: an error, and the dialog stays open with the reason. - assert!(confirm(&mut app).is_err()); - let d = app.ui.dialog.as_ref().expect("the dialog stays open"); - assert!(d.fields.contains_key("status")); - assert_eq!(undo_steps(&app), before); - // Corrected, it previews and applies. - app.ui.dialog.as_mut().unwrap().fields.insert("hyphWeight".into(), json!(0.9)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("status")); - confirm(&mut app).unwrap(); - assert_eq!(para_attr(&mut app, &story, 0, "hyphenate"), true); - assert_eq!(para_attr(&mut app, &story, 4, "hyphWeight"), 0.9); - } - - #[test] - fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() { - let (mut app, story) = two_paragraphs(); - let ctx = egui::Context::default(); - assert!(crate::menus::menu_enabled(&app, "app.justificationDialog")); - app.run("app.justificationDialog", json!({})).unwrap(); - draw(&mut app, &ctx); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!(d.id, "justification"); - assert_eq!(d.fields["current"]["wordSpaceMin"], 0.7); - assert_eq!(d.fields["current"]["wordSpaceDesired"], 1.0); - app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.1)); - draw(&mut app, &ctx); - let before = undo_steps(&app); - confirm(&mut app).unwrap(); - assert_eq!(undo_steps(&app), before + 1, "one undo step"); - assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1); - assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceMin"), 0.7, "unedited fields stay"); - assert_eq!(para_attr(&mut app, &story, 4, "wordSpaceDesired"), 1.0, "only the selected paragraph"); - let style = app.session.doc().unwrap().doc.styles.resolve_para_style(designcraft_doc::story::BASIC_PARAGRAPH).0.word_space_desired; - assert_eq!(style, 1.0, "the paragraph style keeps its value"); - - // Cancel (Escape) leaves the paragraph alone. - app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); - app.run("app.justificationDialog", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.2)); - let before = undo_steps(&app); - let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events: vec![escape], - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - assert!(app.ui.dialog.is_none(), "cancelled"); - assert_eq!(undo_steps(&app), before); - assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1); - - app.run("edit.deselectAll", json!({})).unwrap(); - assert!(!crate::menus::menu_enabled(&app, "app.justificationDialog"), "nothing to justify"); - assert!(app.run("app.justificationDialog", json!({})).is_err()); - } - - #[test] - fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() { - let (mut app, story) = two_paragraphs(); - let ctx = egui::Context::default(); - app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); - app.run("app.justificationDialog", json!({})).unwrap(); - draw(&mut app, &ctx); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!(d.fields["current"]["wordSpaceMin"], Value::Null, "mixed shows empty"); - assert_eq!(d.fields["current"]["wordSpaceMax"], 1.33); - - // Out of range, and minimum above desired: an error, the dialog stays open, nothing changes. - let before = undo_steps(&app); - for (key, v) in [("wordSpaceMax", 20.0), ("glyphScaleMin", 0.2), ("letterSpaceDesired", f64::NAN)] { - app.ui.dialog = Some(d.clone()); - app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(v)); - assert!(confirm(&mut app).is_err(), "{key} = {v}"); - assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why"); - } - app.ui.dialog = Some(d.clone()); - app.ui.dialog.as_mut().unwrap().fields.insert("letterSpaceMin".into(), json!(0.1)); - assert!(confirm(&mut app).is_err(), "letter spacing minimum above desired"); - draw(&mut app, &ctx); - assert_eq!(undo_steps(&app), before); - - app.ui.dialog = Some(d); - app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceMax".into(), json!(1.5)); - confirm(&mut app).unwrap(); - assert_eq!(undo_steps(&app), before + 1); - for (at, min) in [(0, 0.7), (4, 0.8)] { - assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMax"), 1.5); - assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMin"), min, "each paragraph keeps its own minimum"); - } - } - - fn command_app(id: &str, fields: Value) -> DesignApp { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields)); - app - } - - #[test] - fn generic_new_document_preserves_typed_values_and_text_entry() { - for pages in [json!(2), json!(" 2 ")] { - let mut app = command_app( - "file.new", - json!({ - "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0, - "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40}, - "title": " ", "status": "internal", "primaryTextFrame": true - }), - ); - confirm(&mut app).unwrap(); - let doc = &app.session.active().unwrap().doc; - assert_eq!(doc.page_count(), 2); - assert!(!doc.settings.facing_pages); - assert!(doc.title.starts_with("Untitled-")); - for page in doc.spreads.iter().flat_map(|s| &s.pages) { - assert!((page.width - 595.2755905511812).abs() < 0.01); - assert!((page.height - 841.8897637795277).abs() < 0.01); - assert_eq!(page.columns.gutter, 0.0); - assert_eq!(page.margins.top, 10.0); - assert_eq!(page.margins.outside, 40.0); - } - // `primaryTextFrame` is documented since #776, so the dialog passes it on (`status` isn't). - assert!(doc.spreads.iter().any(|s| !s.items.is_empty()), "documented fields reach the command"); - assert!(app.ui.dialog.is_none()); - } - } - - #[test] - fn numbering_commands_document_their_fields() { - let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::>(); - assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]); - assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]); - } - - #[test] - fn generic_command_preserves_array_geometry() { - let mut app = command_app("file.new", json!({})); - confirm(&mut app).unwrap(); - app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]}))); - confirm(&mut app).unwrap(); - let doc = &app.session.active().unwrap().doc; - let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap(); - assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0)); - } - - #[test] - fn generic_explicit_null_uses_the_commands_existing_semantics() { - // file.new accepts null width by using the selected preset's width. - for width in [Value::Null, json!("null")] { - let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "})); - confirm(&mut app).unwrap(); - let doc = &app.session.active().unwrap().doc; - assert_eq!(doc.title, "Sample layout"); - assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01); - } - } - - #[test] - fn generic_invalid_number_retains_dialog_without_creating_document() { - let mut app = command_app("file.new", json!({"width": 0})); - assert!(confirm(&mut app).is_err()); - assert!(app.session.active().is_none()); - let dialog = app.ui.dialog.as_ref().unwrap(); - assert_eq!(dialog.fields["width"], 0); - assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range")); - } - - #[test] - fn style_options_preview_choice_is_remembered_on_reopen() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.paragraph.create", json!({"name":"Tutorial","chars":{"size":10}})).unwrap(); - open_style_options(&mut app, true, "Tutorial"); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::unique("style_preview_remember_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(3); - h.get_by_label("Preview").click(); - h.run_steps(3); - cancel(h.state_mut()); - open_style_options(h.state_mut(), true, "Tutorial"); - assert!(h.state().ui.dialog.as_ref().unwrap().b("preview"), "Preview stays checked on reopen"); - } - - #[test] - fn style_options_preview_updates_all_uses_cancels_and_commits_once() { - use egui_kittest::{Harness, kittest::Queryable}; - for paragraph in [true, false] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect":[36,36,300,300],"content":"text","text":"First\nSecond"})).unwrap(); - app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":12})).unwrap(); - let kind = if paragraph { "paragraph" } else { "character" }; - app.run(&format!("style.{kind}.create"), json!({"name":"Tutorial","chars":{"size":10}})).unwrap(); - app.run(&format!("style.{kind}.apply"), json!({"name":"Tutorial"})).unwrap(); - let before = app.session.doc().unwrap().doc.clone(); - let undo = app.session.doc().unwrap().history.undo.len(); - let journal = app.session.journal.len(); - open_style_options(&mut app, paragraph, "Tutorial"); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::unique("style_preview_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(3); - h.get_by_label("Preview").click(); - h.run_steps(3); - h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(18)); - h.run_steps(3); - let app = h.state_mut(); - assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 18.0); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); - assert_eq!(app.session.journal.len(), journal); - // Repeated previews replace each other, never accumulate undo entries. - app.ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(20)); - h.run_steps(3); - assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 20.0); - h.get_by_label("Preview").click(); - h.run_steps(3); - assert_eq!(h.state().session.doc().unwrap().doc, before); - h.get_by_label("Preview").click(); - h.run_steps(3); - cancel(h.state_mut()); - assert_eq!(h.state().session.doc().unwrap().doc, before); - assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); - open_style_options(h.state_mut(), paragraph, "Tutorial"); - let d = h.state_mut().ui.dialog.as_mut().unwrap(); - d.fields.insert("preview".into(), json!(true)); - d.fields.insert("c.size".into(), json!(24)); - h.run_steps(3); - confirm(h.state_mut()).unwrap(); - assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); - // Both paragraphs/character runs still use the globally edited definition. - for pos in [0, 6] { - h.state_mut().run("text.select", json!({"story":f["story"],"anchor":pos,"focus":pos+1})).unwrap(); - assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 24.0); - } - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(h.state().session.doc().unwrap().doc, before); - } - } - - #[test] - fn style_preview_refuses_justification_spacing_ok_would_refuse() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let before = app.session.doc().unwrap().doc.clone(); - let mut d = - Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, "p.wordSpaceDesired": 1.1})); - style_options_preview(&mut app, &mut d); - assert_ne!(app.session.doc().unwrap().doc, before, "a valid value previews"); - // Minimum above Desired: the page goes back and the dialog says why. - d.fields.insert("p.wordSpaceMin".into(), json!(1.5)); - style_options_preview(&mut app, &mut d); - assert_eq!(app.session.doc().unwrap().doc, before); - assert!(d.s("status").contains("Word Spacing"), "{:?}", d.fields.get("status")); - assert!(app.session.doc().unwrap().interaction.is_none()); - } - - #[test] - fn invalid_style_preview_leaves_the_starting_document_and_can_be_cancelled() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.character.create", json!({"name":"Emphasis"})).unwrap(); - let before = app.session.doc().unwrap().doc.clone(); - let mut d = Dialog::new("characterStyleOptions", json!({"name":"Emphasis","preview":true,"basedOn":"Emphasis"})); - style_options_preview(&mut app, &mut d); - assert!(d.fields.contains_key("status")); - assert_eq!(app.session.doc().unwrap().doc, before); - app.ui.dialog = Some(d); - cancel(&mut app); - assert_eq!(app.session.doc().unwrap().doc, before); - assert!(app.session.doc().unwrap().interaction.is_none()); - } - - #[test] - fn style_preview_rejects_conflicting_scalar_and_nested_rule_fields_without_panicking() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let before = app.session.doc().unwrap().doc.clone(); - let mut dialog = Dialog::new( - "paragraphStyleOptions", - json!({ - "name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, - "p.ruleAbove": false, "p.ruleAbove.weight": 2 - }), - ); - style_options_preview(&mut app, &mut dialog); - assert!(dialog.fields.contains_key("status")); - assert_eq!(app.session.doc().unwrap().doc, before); - app.ui.dialog = Some(dialog); - cancel(&mut app); - assert!(app.session.doc().unwrap().interaction.is_none()); - } - - #[test] - fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - // A 300 pt frame, 2 columns, 12 pt gutter (picas in the dialog). - let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); - let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); - app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "gutter": 12})).unwrap(); - let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); - let mut d = Dialog::new("textFrameOptions", json!({})); - seed_text_frame_options(&app, &mut d); - // Fixed Number shows each column's width: (300 - 12) / 2 = 144 pt. - assert_eq!((d.s("columnsKind"), d.s("columnWidth"), d.s("firstBaseline")), ("fixedNumber".into(), "12p0".into(), "ascent".into())); - for (k, v) in [ - ("columnsKind", json!("fixedWidth")), - ("columnWidth", json!("10p0")), - ("firstBaseline", json!("capHeight")), - ("firstBaselineMin", json!("0p6")), - ("balanceColumns", json!(true)), - ("ignoreWrap", json!(true)), - ] { - d.fields.insert(k.into(), v); - } - app.ui.dialog = Some(d); - confirm(&mut app).unwrap(); - let o = opts(&app); - assert_eq!(o.columns_kind, designcraft_doc::ColumnsKind::FixedWidth); - assert_eq!((o.column_width, o.first_baseline_min, o.columns), (120.0, 6.0, 2)); - assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight); - assert!(o.balance_columns && o.ignore_wrap); - // Fixed Number again: the width isn't sent. - let mut d = Dialog::new("textFrameOptions", json!({})); - seed_text_frame_options(&app, &mut d); - assert_eq!(d.s("columnWidth"), "10p0", "Fixed Width shows its own width"); - d.fields.insert("columnsKind".into(), json!("fixedNumber")); - app.ui.dialog = Some(d); - confirm(&mut app).unwrap(); - assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0)); - } - - #[test] - fn baseline_grid_increment_error_explains_the_positive_measure_rule() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); - let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); - for increment in ["0", "-1 pt", "not a measure"] { - let mut d = Dialog::new("textFrameOptions", json!({})); - seed_text_frame_options(&app, &mut d); - d.fields.insert("customGrid".into(), json!(true)); - d.fields.insert("gridIncrement".into(), json!(increment)); - app.ui.dialog = Some(d); - let error = confirm(&mut app).unwrap_err().to_string(); - assert!(error.contains("the baseline grid increment must be a measure greater than zero"), "{increment}: {error}"); - assert!(app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid.is_none()); - } - } - - #[test] - fn text_frame_options_set_a_custom_baseline_grid_relative_to() { - use designcraft_doc::{FrameBaselineGrid, FrameGridRelative}; - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); - let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); - let grid = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid; - let open = |app: &mut DesignApp, fields: &[(&str, Value)]| { - let mut d = Dialog::new("textFrameOptions", json!({})); - seed_text_frame_options(app, &mut d); - for (k, v) in fields { - d.fields.insert((*k).into(), v.clone()); - } - app.ui.dialog = Some(d); - confirm(app) - }; - app.run("selection.set", json!({"ids": [id.0]})).unwrap(); - // Turned on, the grid takes the shown start and increment (the document grid's: 3p0 and 1p0). - open(&mut app, &[("customGrid", json!(true)), ("gridRelativeTo", json!("frame"))]).unwrap(); - assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 36.0, increment: 12.0, relative_to: FrameGridRelative::TopOfFrame })); - // The dialog shows the frame's grid; changing Relative To keeps its start and increment. - open(&mut app, &[("gridStart", json!("0p10"))]).unwrap(); - open(&mut app, &[("gridRelativeTo", json!("inset"))]).unwrap(); - assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 10.0, increment: 12.0, relative_to: FrameGridRelative::TopInset })); - open(&mut app, &[("customGrid", json!(false))]).unwrap(); - assert_eq!(grid(&app), None); - } - - #[test] - fn text_frame_options_change_only_what_was_edited() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); - let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); - app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap(); - let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); - let before = opts(&app); - let open = |app: &mut DesignApp, fields: &[(&str, Value)]| { - app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({}))); - let mut d = app.ui.dialog.take().unwrap(); - seed_text_frame_options(app, &mut d); - for (k, v) in fields { - d.fields.insert((*k).into(), v.clone()); - } - app.ui.dialog = Some(d); - confirm(app) - }; - // OK without edits changes nothing (no undo step either). - assert_eq!(open(&mut app, &[]).unwrap(), Value::Null); - assert_eq!(opts(&app), before); - // The rule's weight is in points; unequal insets the user didn't touch stay. - open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap(); - let o = opts(&app); - assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}"); - assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter)); - // One of the rule's insets edited: the other rule settings stay. - open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap(); - let o = opts(&app); - assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0)); - assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule); - // One inset side edited: the others keep their values. - open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap(); - assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]); - open(&mut app, &[("balanceColumns", json!(true))]).unwrap(); - let o = opts(&app); - assert!(o.balance_columns && o.column_rule && o.columns == 2, "{o:?}"); - // An unknown swatch is an error and the dialog stays open. - let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err(); - assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}"); - assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK); - // Each OK is one undo step. - for _ in 0..4 { - app.run("edit.undo", json!({})).unwrap(); - } - assert_eq!(opts(&app), before); - } - - #[test] - fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.newSample", json!({})).unwrap(); - crate::menus::activate(&mut app, "toc.generate", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(TOC)); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in - ["Table of Contents", "Title:", "Include Paragraph Styles:", "Other Styles:", "« Add", "Remove »", "Replace Existing Table of Contents"] - { - visible_label(&labels, screen, expected); - } - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Headline").center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "« Add").center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in ["Entry Style:", "TOC Level 1", "After Entry", "Between Entry and Number:", "Level:"] { - visible_label(&labels, screen, expected); - } - let undo = app.session.doc().unwrap().history.undo.len(); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center()); - assert!(app.ui.dialog.is_none()); - let d = &app.session.doc().unwrap().doc; - let toc = d.toc.clone().unwrap(); - assert_eq!(toc.entries, vec![designcraft_doc::TocEntry::new("Headline", 1)]); - let text = &d.story(toc.story).unwrap().text; - assert!(text.starts_with("Contents\n") && text.contains("\nNotes on the Grid\t"), "{text}"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); - // Reopened, the dialog shows the table of contents and replaces it. - crate::menus::activate(&mut app, "toc.generate", &Value::Null); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.b("replace")); - assert_eq!(toc_rows(d).iter().map(|r| r.style.as_str()).collect::>(), ["Headline"]); - } - - #[test] - fn margins_and_columns_link_arithmetic_preview_and_one_undo_step() { - // Adobe's "Set up a modern magazine layout" (1:41–3:04): linked margins to 0.4375 in, then - // 5 columns with a 0.1875 in gutter, unlinked, and "*2" typed after the outside margin. - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"preset": "A4", "pages": 3, "facingPages": true, "margins": 36})).unwrap(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); - open_margins_and_columns(&mut app); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - let mut labels = vec![]; - for _ in 0..3 { - labels = dialog_frame(&mut app, &ctx, screen, vec![]); - } - for expected in - ["Margins and Columns", "Margins", "Top:", "Bottom:", "Inside:", "Outside:", "Columns", "Number:", "Gutter:", "Adjust Layout", "Preview"] - { - visible_label(&labels, screen, expected); - } - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.b("link"), "four equal margins open linked"); - // Linked: one margin typed is all four. - app.ui.dialog.as_mut().unwrap().fields.insert("marginTop".into(), json!("0.4375 in")); - dialog_frame(&mut app, &ctx, screen, vec![]); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(MARGIN_FIELDS.iter().all(|(k, _, _)| d.s(k) == "0.4375 in"), "{:?}", d.fields); - // Preview: the page changes, with no undo step. - let undo = app.session.doc().unwrap().history.undo.len(); - app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let top = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].margins.top; - assert!((top(&app) - 31.5).abs() < 1e-6, "previewed: {}", top(&app)); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); - // Unlinked (the link button), the outside margin alone: "*2" typed after it is worked out - // when the field is left. - app.ui.dialog.as_mut().unwrap().fields.insert("link".into(), json!(false)); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let field = labels - .iter() - .filter(|(t, _, _)| t.trim() == "0.4375 in") - .map(|(_, r, _)| *r) - .max_by(|a, b| (a.max.x + a.max.y).total_cmp(&(b.max.x + b.max.y))) - .unwrap(); - click_dialog(&mut app, &ctx, screen, field.center()); - dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::End), egui::Event::Text("*2".into())]); - dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Tab)]); - dialog_frame(&mut app, &ctx, screen, vec![]); - let d = app.ui.dialog.as_ref().unwrap(); - assert!( - !d.s("marginOutside").contains('*') && (d.m("marginOutside").unwrap() - 63.0).abs() < 1e-6, - "worked out on leaving the field: {}", - d.s("marginOutside") - ); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("link".into(), json!(false)); - for (k, v) in [("marginOutside", "0.4375 in*2"), ("columns", "5"), ("gutter", "0.1875 in"), ("target", "all")] { - d.fields.insert(k.into(), json!(v)); - } - dialog_frame(&mut app, &ctx, screen, vec![]); - confirm(&mut app).unwrap(); - let pg = app.session.doc().unwrap().doc.spreads[1].pages[0].clone(); - assert_eq!((pg.margins.top, pg.margins.outside, pg.columns.count), (31.5, 63.0, 5)); - assert!((pg.columns.gutter - 13.5).abs() < 1e-6); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); - // Cancel after a preview puts the page back. - open_margins_and_columns(&mut app); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("preview".into(), json!(true)); - d.fields.insert("columns".into(), json!("2")); - dialog_frame(&mut app, &ctx, screen, vec![]); - cancel(&mut app); - assert_eq!(app.session.doc().unwrap().doc.spreads[1].pages[0].columns.count, 5); - } - - #[test] - fn create_guides_reads_like_indesigns_and_previews() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 1, "facingPages": false})).unwrap(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); - open_create_guides(&mut app); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - let mut labels = vec![]; - for _ in 0..3 { - labels = dialog_frame(&mut app, &ctx, screen, vec![]); - } - for expected in - ["Create Guides", "Rows", "Columns", "Options", "Fit Guides to:", "Margins", "Page", "Remove Existing Ruler Guides", "Preview"] - { - visible_label(&labels, screen, expected); - } - // Rows and Columns side by side. - let (r, c) = (visible_label(&labels, screen, "Rows"), visible_label(&labels, screen, "Columns")); - assert!((r.center().y - c.center().y).abs() < 2.0 && r.center().x < c.center().x); - // Thirds, single guides, fitted to the page: clicking the Page radio. - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Page").center()); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!(d.s("fitTo"), "page"); - d.fields.insert("rows".into(), json!("3")); - d.fields.insert("rowGutter".into(), json!("0")); - d.fields.insert("preview".into(), json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let guides = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].guides.len(); - assert_eq!(guides(&app), 2, "previewed"); - confirm(&mut app).unwrap(); - assert_eq!(guides(&app), 2, "made once"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(guides(&app), 0, "one undo step"); - } - - fn dialog_context(language: &str) -> egui::Context { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx, language); - crate::theme::apply(&ctx, &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default())); - ctx - } - - fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, events: Vec) -> Vec<(String, egui::Rect, egui::Rect)> { - let time = ctx.input(|i| i.time) + 1.0 / 60.0; - let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| { - show(app, ui.ctx()); - }); - output.textures_delta.clear(); - fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) { - match shape { - egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)), - egui::Shape::Vec(shapes) => { - for s in shapes { - collect(s, clip, labels); - } - } - _ => {} - } - } - let mut labels = Vec::new(); - for shape in output.shapes { - collect(&shape.shape, shape.clip_rect, &mut labels); - } - labels - } - - fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect { - let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted")); - assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}"); - assert!(clip.contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}"); - *rect - } - - fn click_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2) { - for pressed in [true, false] { - dialog_frame( - app, - ctx, - screen, - vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - } - - fn scroll_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2, delta: egui::Vec2) { - dialog_frame( - app, - ctx, - screen, - vec![ - egui::Event::PointerMoved(pos), - egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta, - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }, - ], - ); - // Let smooth wheel scrolling and scrollbar visibility settle before clicking. - for _ in 0..30 { - dialog_frame(app, ctx, screen, vec![]); - } - } - - fn scope_control(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value { - let (request, _reply) = crate::control::ControlRequest::new(method, params); - let crate::control::Outcome::Done(value) = crate::control::handle(app, ctx, &request) else { panic!("ordinary control response") }; - assert_eq!(value["ok"], true, "{value}"); - value["result"].clone() - } - - fn scope_click(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, label: &str) { - let labels = dialog_frame(app, ctx, screen, vec![]); - let pos = visible_label(&labels, screen, label).center(); - click_dialog(app, ctx, screen, pos); - } - - fn scope_dialog() -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) { - scope_dialog_with_selection("red red | red", 7) - } - - fn scope_dialog_with_selection(text: &str, end: usize) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) { - scope_dialog_with_tool(text, end, None) - } - - fn scope_dialog_with_tool( - text: &str, - end: usize, - tool: Option<&str>, - ) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.language = "en".into(); - app.run("file.new", json!({})).unwrap(); - let frame = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap(); - let sid = designcraft_engine::doc::StoryId(frame["story"].as_u64().unwrap()); - let ctx = dialog_context("en"); - if let Some(tool) = tool { - scope_control(&mut app, &ctx, "ui.tool.select", json!({"tool": tool})); - } - app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": end})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - for (field, value) in [("find", "red"), ("change", "unused")] { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); - } - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - scope_click(&mut app, &ctx, screen, "document"); - scope_click(&mut app, &ctx, screen, "selection"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection"); - (app, ctx, screen, sid) - } - - fn scope_selected(app: &DesignApp, sid: designcraft_engine::doc::StoryId, a: usize, b: usize) { - let t = app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((t.story, t.range(), t.cell), (sid, a..b, None)); - } - - fn scope_state_unchanged(app: &DesignApp, before: &designcraft_engine::DocState) { - let after = app.session.doc().unwrap(); - assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc)); - assert_eq!(after.uid, before.uid); - assert_eq!(after.revision, before.revision); - assert_eq!(after.selection, before.selection); - assert_eq!(after.history.limit, before.history.limit); - for (actual, expected) in [(&after.history.undo, &before.history.undo), (&after.history.redo, &before.history.redo)] { - assert_eq!(actual.len(), expected.len()); - for (a, b) in actual.iter().zip(expected) { - assert_eq!(a.label, b.label); - assert_eq!(a.selection, b.selection); - assert!(std::sync::Arc::ptr_eq(&a.doc, &b.doc)); - } - } - } - - #[test] - fn find_scope_dialog_control_effective_noops_retain_bounds() { - for (field, value) in [("objectMode", json!(false)), ("story", Value::Null)] { - let (mut app, ctx, screen, sid) = scope_dialog(); - assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(field)); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().clone(); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], value); - scope_state_unchanged(&app, &before); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 4, 7); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); - } - } - - #[test] - fn find_scope_dialog_explicit_story_ignored_scope_preserves_grep_cursor() { - for physical in [false, true] { - for (text, pattern, hits, changed) in [ - ("é", "é|(?:)", vec![(0, 2)], "X"), - ("é🙂", "é|(?:)", vec![(0, 2), (6, 6)], "X🙂X"), - ("é🙂", "(?:)", vec![(0, 0), (2, 2), (6, 6)], "XéX🙂X"), - ] { - let (mut app, ctx, screen, sid) = scope_dialog_with_selection(text, 0); - for (field, value) in [("find", json!(pattern)), ("change", json!("X")), ("story", json!(sid.0))] { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); - } - scope_click(&mut app, &ctx, screen, "GREP"); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len())); - for &(a, b) in &hits { - scope_click(&mut app, &ctx, screen, "Find Next"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "Found"); - scope_selected(&app, sid, a, b); - let before = app.session.doc().unwrap().clone(); - let cur = app.ui.dialog.as_ref().unwrap().s("scope"); - let next = if cur == "selection" { "document" } else { "selection" }; - if physical { - scope_click(&mut app, &ctx, screen, &cur); - scope_click(&mut app, &ctx, screen, next); - } else { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next})); - } - assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), next); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["story"], json!(sid.0)); - scope_state_unchanged(&app, &before); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len())); - } - scope_click(&mut app, &ctx, screen, "Find Next"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches"); - // An ignored scope change must not revive an exhausted endpoint either. - let before = app.session.doc().unwrap().clone(); - let cur = app.ui.dialog.as_ref().unwrap().s("scope"); - let next = if cur == "selection" { "document" } else { "selection" }; - if physical { - scope_click(&mut app, &ctx, screen, &cur); - scope_click(&mut app, &ctx, screen, next); - } else { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next})); - } - scope_click(&mut app, &ctx, screen, "Find Next"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches"); - scope_state_unchanged(&app, &before); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} replacement(s) made", hits.len())); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, changed); - } - } - } - - #[test] - fn find_scope_dialog_explicit_story_transitions_reset_cursor() { - for remove_override in [false, true] { - let (mut app, ctx, screen, sid) = scope_dialog_with_selection("é🙂", 0); - let other = app.run("frame.create", json!({"rect": [180, 36, 100, 100], "content": "text", "text": "other"})).unwrap(); - app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); - for (field, value) in [("find", json!("(?:)")), ("story", json!(sid.0))] { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); - } - scope_click(&mut app, &ctx, screen, "GREP"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 0); - let before = app.session.doc().unwrap().clone(); - let value = if remove_override { Value::Null } else { other["story"].clone() }; - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": value})); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0})); - scope_state_unchanged(&app, &before); - // Away and back still releases continuation even if no Find command intervenes. - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 0); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 2, 2); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "é🙂"); - let other_sid = designcraft_engine::doc::StoryId(other["story"].as_u64().unwrap()); - assert_eq!(app.session.doc().unwrap().doc.story(other_sid).unwrap().text, "other"); - } - } - - #[test] - fn find_scope_dialog_control_mode_changes_release_bounds() { - for object_mode in [false, true] { - let (mut app, ctx, _, sid) = scope_dialog(); - if object_mode { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": true})); - } - // Direct Session consumers share the retained domain even while Object is shown. - let p = json!({"find": "red", "change": "blue", "scope": "selection"}); - let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); - assert_eq!(count.as_array().unwrap().len(), 2); - scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.next", "params": p})); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().clone(); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": !object_mode})); - assert_eq!(app.ui.dialog.as_ref().unwrap().b("objectMode"), !object_mode); - scope_state_unchanged(&app, &before); - let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); - assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); - let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p})); - assert_eq!(changed, json!({"count": 1})); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); - } - } - - #[test] - fn find_scope_dialog_tool_replacement_releases_bounds() { - for (tool, replacement) in [("page", "cmd:layout.pageSize"), ("rectangleFrame", "frameSize")] { - let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool)); - assert_eq!(app.session.tool_id(), tool); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().clone(); - let active = (app.session.active_index(), app.session.documents().len()); - let off = app.session.layout().xf(designcraft_engine::doc::SpreadRef::Doc(0)).translation(); - let x = off.x + before.doc.spreads[0].pages[0].x + 200.0; - let y = off.y + 200.0; - // The Page tool opens Page Size on a double-click (a click selects the page). - let events = if tool == "page" { - json!([{"kind": "doubleclick", "x": x, "y": y}]) - } else { - json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]) - }; - // Real tool -> Action::Dialog -> after_engine; no injected UI request. - scope_control(&mut app, &ctx, "ui.pointer", json!({"events": events})); - assert_eq!(app.ui.dialog.as_ref().unwrap().id, replacement); - assert!(app.session.ui_requests.is_empty()); - assert_eq!((app.session.active_index(), app.session.documents().len()), active); - scope_state_unchanged(&app, &before); - scope_click(&mut app, &ctx, screen, "Cancel"); - assert!(app.ui.dialog.is_none()); - assert_eq!((app.session.active_index(), app.session.documents().len()), active); - scope_state_unchanged(&app, &before); - let p = json!({"find": "red", "change": "blue", "scope": "selection"}); - let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); - assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); - scope_state_unchanged(&app, &before); - let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p})); - assert_eq!(changed, json!({"count": 1})); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); - } - } - - #[test] - fn find_scope_dialog_tool_without_replacement_retains_bounds() { - for tool in ["page", "rectangleFrame"] { - let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool)); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().clone(); - let fields = app.ui.dialog.as_ref().unwrap().fields.clone(); - scope_control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "move", "x": 200, "y": 200}]})); - assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields); - scope_state_unchanged(&app, &before); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 4, 7); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn find_scope_dialog_native_pdf_replacement_releases_bounds() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("three.pdf"); - std::fs::write(&path, crate::browser_import_tests::pdf()).unwrap(); - for dismissal in ["Cancel", "Escape", "control"] { - let (mut app, ctx, screen, sid) = scope_dialog(); - let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let seen_pick = picked.clone(); - let seen_read = read.clone(); - let pick_path = path.to_string_lossy().to_string(); - let read_path = pick_path.clone(); - app.services.pick_open = Some(Box::new(move |purpose| { - assert_eq!(purpose, "place"); - seen_pick.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Some(pick_path.clone()) - })); - app.services.read = Some(Box::new(move |path| { - assert_eq!(path, read_path); - seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - std::fs::read(path).map_err(|e| e.to_string()) - })); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().clone(); - let active = (app.session.active_index(), app.session.documents().len()); - // Exercise engine.execute -> UiRequest::Pick -> native host PDF replacement. - scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}})); - assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1); - let dialog = app.ui.dialog.as_ref().unwrap(); - assert_eq!(dialog.id, "pdfImport"); - assert_eq!(dialog.s("path"), path.to_string_lossy()); - assert_eq!(dialog.fields["pages"], 3); - assert_eq!(dialog.s("page"), "1"); - assert!(!dialog.b("async")); - assert_eq!(dialog.fields["target"], json!(before.uid)); - assert!(app.session.ui_requests.is_empty()); - assert!(app.pending_pdf.is_none()); - assert_eq!((app.session.active_index(), app.session.documents().len()), active); - scope_state_unchanged(&app, &before); - match dismissal { - "Cancel" => scope_click(&mut app, &ctx, screen, "Cancel"), - "Escape" => { - dialog_frame( - &mut app, - &ctx, - screen, - vec![egui::Event::Key { - key: egui::Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }], - ); - } - "control" => { - scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({})); - } - _ => panic!("known dismissal"), - } - assert!(app.ui.dialog.is_none()); - assert!(app.pending_pdf.is_none()); - assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!((app.session.active_index(), app.session.documents().len()), active); - scope_state_unchanged(&app, &before); - let p = json!({"find": "red", "change": "blue", "scope": "selection"}); - let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); - assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); - scope_state_unchanged(&app, &before); - let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p})); - assert_eq!(changed, json!({"count": 1})); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn find_scope_dialog_native_picker_cancel_retains_bounds() { - let (mut app, ctx, screen, sid) = scope_dialog(); - let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let seen = picked.clone(); - app.services.pick_open = Some(Box::new(move |purpose| { - assert_eq!(purpose, "place"); - seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - None - })); - let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let seen_read = read.clone(); - app.services.read = Some(Box::new(move |_| { - seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Err("canceled picker must not read".into()) - })); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().clone(); - let active = (app.session.active_index(), app.session.documents().len()); - let fields = app.ui.dialog.as_ref().unwrap().fields.clone(); - scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}})); - assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 0); - assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields); - assert_eq!((app.session.active_index(), app.session.documents().len()), active); - scope_state_unchanged(&app, &before); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 4, 7); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); - } - - #[test] - fn find_scope_dialog_exact_baseline_buttons() { - let (mut app, ctx, screen, sid) = scope_dialog_with_selection("red red", 3); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red"); - } - - #[test] - fn find_scope_dialog_grep_tab_alone_restarts_original_selection() { - let (mut app, ctx, screen, sid) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_click(&mut app, &ctx, screen, "GREP"); - assert!(app.ui.dialog.as_ref().unwrap().b("grep")); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("find"), "red"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 4, 7); - scope_click(&mut app, &ctx, screen, "Text"); - assert!(!app.ui.dialog.as_ref().unwrap().b("grep")); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - } - - #[test] - fn find_scope_dialog_buttons_retain_nonempty_hits_and_change_all() { - let (mut app, ctx, screen, sid) = scope_dialog(); - let history = app.session.doc().unwrap().history.undo.len(); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 4, 7); - scope_click(&mut app, &ctx, screen, "Find Next"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches"); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), history); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1); - scope_click(&mut app, &ctx, screen, "Cancel"); - assert!(app.ui.dialog.is_none()); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); - app.run("edit.redo", json!({})).unwrap(); - let native = app.run("file.serialize", json!({})).unwrap(); - app.run("file.openBytes", json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap(); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); - } - - fn scope_confirm_case(action: &str) { - let (mut app, ctx, screen, sid) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Count"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - match action { - "OK" => scope_click(&mut app, &ctx, screen, "OK"), - "Enter" => { - dialog_frame( - &mut app, - &ctx, - screen, - vec![egui::Event::Key { - key: egui::Key::Enter, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }], - ); - } - "control" => { - assert_eq!(scope_control(&mut app, &ctx, "ui.dialog.confirm", json!({}))["count"], 2); - } - _ => panic!("known confirmation route"), - } - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); - // The closed dialog cannot leave its old seven-byte range for a later direct query. - let matches = app.run("find.find", json!({"find": "blue", "scope": "selection"})).unwrap(); - assert_eq!(matches.as_array().unwrap().len(), 0); - } - - #[test] - fn find_scope_dialog_ok_consumes_retained_bounds() { - scope_confirm_case("OK"); - } - - #[test] - fn find_scope_dialog_enter_consumes_retained_bounds() { - scope_confirm_case("Enter"); - } - - #[test] - fn find_scope_dialog_control_confirm_consumes_retained_bounds() { - scope_confirm_case("control"); - } - - #[test] - fn find_scope_dialog_query_reselection_cancel_and_reopen() { - let (mut app, ctx, screen, sid) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true})); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "r.d"})); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({})); - assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1); - app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 7})).unwrap(); - app.run("find.next", json!({"find": "red", "scope": "selection"})).unwrap(); - scope_control(&mut app, &ctx, "ui.dialog.open", json!({"id": "findChange", "fields": {"find": "red", "scope": "selection"}})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); - app.run("text.select", json!({"story": sid.0, "anchor": 4, "focus": 7})).unwrap(); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 4, 7); - app.run("app.findChange", json!({})).unwrap(); - for (field, value) in [("find", "red"), ("scope", "selection")] { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); - } - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); - } - - #[test] - fn find_scope_dialog_word_reselection_limits_count_and_change_buttons() { - let (mut app, ctx, screen, sid) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let selected = app.session.doc().unwrap().selection.clone(); - let frame = selected.text.unwrap().frame.unwrap(); - let point = { - let st = app.session.doc().unwrap(); - let cs = app.session.cache.get(&st.doc, sid, None); - let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap(); - let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5); - assert_eq!(cs.frames[fi].frame, frame); - assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1)); - let loc = st.doc.find(frame).unwrap(); - st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner - }; - let before = app.session.doc().unwrap().doc.clone(); - let revision = app.session.doc().unwrap().revision; - app.run("text.selectWord", json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap(); - assert_eq!(app.session.doc().unwrap().selection, selected); - assert!(app.session.doc().unwrap().revision > revision, "a new revision"); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn find_scope_dialog_failed_native_drop_alert_releases_bounds() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("broken.designcraft"); - std::fs::write(&path, b"not a native document").unwrap(); - for dismissal in ["OK", "Escape", "control"] { - let (mut app, ctx, screen, sid) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - let before = app.session.doc().unwrap().doc.clone(); - let selected = app.session.doc().unwrap().selection.clone(); - let revision = app.session.doc().unwrap().revision; - let history = app.session.doc().unwrap().history.undo.len(); - let uid = app.session.doc().unwrap().uid; - let error = app.open_dropped(&path.to_string_lossy()).unwrap_err(); - let alert = app.ui.dialog.as_ref().unwrap(); - assert_eq!(alert.id, "alert"); - assert_eq!(alert.s("title"), "Can't Open the File"); - assert_eq!(alert.s("message"), error); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); - assert_eq!(app.session.doc().unwrap().selection, selected); - assert_eq!(app.session.doc().unwrap().revision, revision); - assert_eq!(app.session.doc().unwrap().uid, uid); - assert_eq!(app.session.doc().unwrap().history.undo.len(), history); - match dismissal { - "OK" => scope_click(&mut app, &ctx, screen, "OK"), - "Escape" => { - dialog_frame( - &mut app, - &ctx, - screen, - vec![egui::Event::Key { - key: egui::Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }], - ); - } - "control" => { - scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({})); - } - _ => panic!("known dismissal"), - } - assert!(app.ui.dialog.is_none()); - let p = json!({"find": "red", "change": "blue", "scope": "selection"}); - assert_eq!(app.run("find.find", p.clone()).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); - assert_eq!(app.run("find.change", p).unwrap(), json!({"count": 1})); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1); - } - } - - #[test] - fn find_scope_dialog_child_errors_and_explicit_parent() { - let (mut app, ctx, screen, sid) = scope_dialog(); - app.run("text.select", json!({"story": sid.0, "anchor": 13, "focus": 13})).unwrap(); - app.run("table.insert", json!({"rows": 1, "cols": 1})).unwrap(); - app.run("text.insert", json!({"text": "red child", "raw": true})).unwrap(); - let child = app.session.doc().unwrap().selection.text.unwrap(); - let before = app.session.doc().unwrap().doc.clone(); - let selection = app.session.doc().unwrap().selection.clone(); - let history = app.session.doc().unwrap().history.undo.len(); - for label in ["Count", "Find Next", "Change All"] { - scope_click(&mut app, &ctx, screen, label); - assert!(app.ui.dialog.as_ref().unwrap().s("status").contains("not supported")); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); - assert_eq!(app.session.doc().unwrap().selection, selection); - assert_eq!(app.session.doc().unwrap().history.undo.len(), history); - } - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0})); - scope_click(&mut app, &ctx, screen, "Count"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 match(es)"); - scope_click(&mut app, &ctx, screen, "Change All"); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 replacement(s) made"); - assert_eq!(app.session.doc().unwrap().doc.text_story(sid, child.cell).unwrap().text, "red child"); - assert!(app.session.doc().unwrap().doc.story(sid).unwrap().text.starts_with("blue blue | blue")); - } - - #[test] - fn find_scope_dialog_error_confirmation_and_escape_release_context() { - for escape in [false, true] { - let (mut app, ctx, screen, sid) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Find Next"); - scope_selected(&app, sid, 0, 3); - if escape { - dialog_frame( - &mut app, - &ctx, - screen, - vec![egui::Event::Key { - key: egui::Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }], - ); - } else { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "["})); - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true})); - scope_click(&mut app, &ctx, screen, "OK"); - } - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); - assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1); - } - } - - #[test] - fn find_scope_dialog_domain_and_object_changes_release_original_range() { - for route in ["scope", "object", "menu", "command"] { - let (mut app, ctx, screen, _) = scope_dialog(); - scope_click(&mut app, &ctx, screen, "Find Next"); - match route { - "scope" => { - for scope in ["story", "selection"] { - scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": scope})); - } - } - "object" => { - scope_click(&mut app, &ctx, screen, "Object"); - scope_click(&mut app, &ctx, screen, "Text"); - } - "menu" => crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null), - "command" => { - app.run("app.newDocumentDialog", json!({})).unwrap(); - } - _ => panic!("known reset route"), - } - assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1); - } - } - - #[test] - fn dialog_title_and_actions_fit_scaled_viewports() { - for language in ["en", "ar"] { - for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0)] { - for (command, title, ok, cancel) in - [("app.preferences", "Preferences", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "Create", "Close")] - { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.language = language.into(); - app.run("file.new", json!({})).unwrap(); - app.run(command, json!({})).unwrap(); - let ctx = dialog_context(language); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in [title, ok, cancel] { - visible_label(&labels, screen, crate::i18n::tr(language, expected)); - } - } - } - } - } - - #[test] - fn preferences_first_setting_switches_interface_language() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("app.preferences", json!({})).unwrap(); - let ctx = dialog_context(""); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let heading = visible_label(&labels, screen, "Interface Language"); - let combo = visible_label(&labels, screen, "English"); - let scaling = visible_label(&labels, screen, "When Scaling"); - assert!(heading.bottom() <= combo.top() && combo.bottom() <= scaling.top(), "the language comes first: {heading:?} {combo:?} {scaling:?}"); - let pane = labels.iter().filter(|(_, rect, _)| rect.left() >= heading.left() - 1.0 && rect.top() < heading.top()); - assert!(pane.clone().all(|(text, _, _)| text == "Preferences"), "nothing above it: {:?}", pane.collect::>()); - - // Choosing a language applies it at once; the dialog stays open. - click_dialog(&mut app, &ctx, screen, combo.center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for (_, name) in crate::i18n::LANGUAGES { - assert!(labels.iter().any(|(text, _, _)| text == name), "{name} is listed by its own name"); - } - let deutsch = visible_label(&labels, screen, "Deutsch").center(); - click_dialog(&mut app, &ctx, screen, deutsch); - assert_eq!(app.ui.language, "de"); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let heading = visible_label(&labels, screen, crate::i18n::tr("de", "Interface Language")); - let combo = visible_label(&labels, screen, "Deutsch"); - - // The names stay endonyms in the German interface. - click_dialog(&mut app, &ctx, screen, combo.center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for name in ["English", "Français", "日本語", "Українська"] { - assert!(labels.iter().any(|(text, _, _)| text == name), "{name}"); - } - click_dialog(&mut app, &ctx, screen, heading.center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(!labels.iter().any(|(text, _, _)| text == "Français"), "the list closes"); - - // The control channel's command and the combo show the same setting. - app.run("app.language", json!({"lang": "ja"})).unwrap(); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(labels.iter().any(|(text, _, _)| text == "日本語")); - assert!(labels.iter().any(|(text, _, _)| text == crate::i18n::tr("ja", "Interface Language"))); - - // Cancel puts back the language the dialog opened with; OK keeps the choice. - let cancel_button = visible_label(&labels, screen, crate::i18n::tr("ja", "Cancel")).center(); - click_dialog(&mut app, &ctx, screen, cancel_button); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.ui.language, ""); - app.run("app.preferences", json!({})).unwrap(); - app.run("app.language", json!({"lang": "it"})).unwrap(); - confirm(&mut app).unwrap(); - assert_eq!(app.ui.language, "it"); - app.run("app.preferences", json!({})).unwrap(); - app.run("app.language", json!({"lang": "uk"})).unwrap(); - cancel(&mut app); - assert_eq!(app.ui.language, "it"); - } - - #[test] - fn preferences_sidebar_scroll_keeps_selected_options_visible() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("app.preferences", json!({})).unwrap(); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let sidebar = visible_label(&labels, screen, "General").center(); - assert!( - !labels.iter().any(|(text, rect, clip)| text == "File Handling" && clip.contains_rect(*rect)), - "last section starts below the sidebar" - ); - scroll_dialog(&mut app, &ctx, screen, sidebar, egui::vec2(0.0, -600.0)); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let files = visible_label(&labels, screen, "File Handling").center(); - click_dialog(&mut app, &ctx, screen, files); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("section"), "files"); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in ["Document Recovery Data", "Save recovery data every:", "OK", "Cancel"] { - visible_label(&labels, screen, expected); - } - } - - #[test] - fn preferences_horizontal_scroll_reaches_clipped_options() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("app.preferences", json!({})).unwrap(); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(450.0, 280.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let body = visible_label(&labels, screen, "When Scaling").center(); - // The last General option sits below this short viewport. - scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(0.0, -600.0)); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let option = "Absolute Numbering (instead of Section Numbering)"; - let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == option).unwrap(); - assert!(rect.right() > clip.right(), "rightmost option starts horizontally clipped: {rect:?}, {clip:?}"); - scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(-600.0, 0.0)); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in [option, "Preferences", "OK", "Cancel"] { - visible_label(&labels, screen, expected); - } - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, option).center()); - assert!(app.ui.dialog.as_ref().unwrap().b("absolutePageNumbers")); - } - - /// Scroll the dialog body down at `at` until `text` is painted unclipped on screen. - fn scroll_to_label(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, at: egui::Pos2, text: &str) -> egui::Rect { - for _ in 0..40 { - let labels = dialog_frame(app, ctx, screen, vec![]); - if let Some((_, rect, _)) = labels.iter().find(|(t, r, clip)| t.trim() == text && screen.contains_rect(*r) && clip.contains_rect(*r)) { - return *rect; - } - scroll_dialog(app, ctx, screen, at, egui::vec2(0.0, -60.0)); - } - panic!("{text} never scrolled into view"); - } - - #[test] - fn new_document_vertical_scroll_reaches_every_field_and_preset() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("app.newDocumentDialog", json!({})).unwrap(); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(392.0, 271.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let body = visible_label(&labels, screen, "Width").center(); - let shown = - |labels: &[(String, egui::Rect, egui::Rect)]| labels.iter().any(|(t, r, clip)| t == "Primary Text Frame" && clip.contains_rect(*r)); - assert!(!shown(&labels), "the details start vertically clipped"); - let ptf = scroll_to_label(&mut app, &ctx, screen, body, "Primary Text Frame"); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in ["New Document", "Create", "Close"] { - visible_label(&labels, screen, expected); - } - click_dialog(&mut app, &ctx, screen, ptf.center()); - assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "the caption toggles its checkbox"); - // Below the details: the preset tabs and cards. - scroll_to_label(&mut app, &ctx, screen, body, "[Default]"); - } - - #[test] - fn arabic_new_document_fields_remain_reachable_and_editable() { - for size in [egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0), egui::vec2(1178.0, 814.0)] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.language = "ar".into(); - app.run("app.newDocumentDialog", json!({})).unwrap(); - let fields = [("height", "66p1"), ("gutter", "1p2"), ("marginBottom", "3p3"), ("marginOutside", "3p4")]; - for (field, value) in fields { - app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(value)); - } - let ctx = dialog_context("ar"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - // With craft-fonts' Noto Sans Arabic the rows above are taller, so at the smallest size the - // Height field starts partly below the body's clip: scroll to it like the other fields. - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let (_, _, body) = labels.iter().find(|(text, _, _)| text.trim() == "66p1").expect("66p1 is painted"); - let height = scroll_to_label(&mut app, &ctx, screen, body.center(), "66p1"); - click_dialog(&mut app, &ctx, screen, height.center()); - dialog_frame( - &mut app, - &ctx, - screen, - vec![ - egui::Event::Key { - key: egui::Key::A, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() }, - }, - egui::Event::Text("88p8".into()), - ], - ); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("height"), "88p8", "numeric fields accept edits"); - let caption = scroll_to_label(&mut app, &ctx, screen, height.center(), crate::i18n::tr("ar", "Primary Text Frame")); - click_dialog(&mut app, &ctx, screen, caption.center()); - assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "checkboxes remain clickable"); - for (_, value) in &fields[1..] { - scroll_to_label(&mut app, &ctx, screen, height.center(), value); - } - } - } - - #[test] - fn resized_dialogs_cancel_and_reopen_without_applying_edits() { - for (command, title, field, ok, cancel) in [ - ("app.preferences", "Preferences", "recoveryMinutes", "OK", "Cancel"), - ("app.newDocumentDialog", "New Document", "pages", "Create", "Close"), - ] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run(command, json!({})).unwrap(); - let original = app.ui.dialog.as_ref().unwrap().fields[field].clone(); - app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(42)); - let ctx = dialog_context("en"); - for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0), egui::vec2(589.0, 407.0)] { - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in [title, ok, cancel] { - visible_label(&labels, screen, expected); - } - } - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0)); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, cancel).center()); - assert!(app.ui.dialog.is_none()); - assert!(app.session.active().is_none(), "cancelling must not create a document"); - app.run(command, json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], original, "cancelled edits must not survive reopening"); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, title); - dialog_frame( - &mut app, - &ctx, - screen, - vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], - ); - assert!(app.ui.dialog.is_none(), "Escape must also close the reopened dialog"); - } - } - - #[test] - fn paragraph_style_options_tabs_section_adds_a_stop_on_its_ruler() { - use egui_kittest::kittest::Queryable; - let (app, _) = ruled_paragraph(); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "tabs"}))); - h.run_steps(4); - h.get_by_label("Clear All"); - // The ruler sits below the row of alignment buttons; its strip takes the click. - let b = h.get_by_label("Right-aligned tab").rect(); - h.get_by_label("Right-aligned tab").click(); - h.run_steps(2); - let left = h.get_by_label("Left-aligned tab").rect(); - let at = egui::pos2(left.min.x + crate::panels::tabs::PAD + 100.0, b.max.y + 14.0); - crate::test_window::click_at(&mut h, at); - let d = h.state().app.ui.dialog.clone().unwrap(); - let tabs = d.fields.get("p.tabs").cloned().unwrap_or_default(); - assert_eq!(tabs.as_array().map(Vec::len), Some(1), "{tabs}"); - assert_eq!(tabs[0]["align"], "right"); - confirm(&mut h.state_mut().app).unwrap(); - let app = &mut h.state_mut().app; - let style = app.session.execute("type.tabs.get", &json!({"style": "Ruled Child"})).unwrap(); - assert_eq!(style["tabs"], tabs); - assert_eq!(app.session.execute("type.tabs.get", &json!({})).unwrap()["tabs"], tabs, "the paragraph follows its style"); - } - - #[test] - fn parses_command_params() { - let f = command_fields("{name, type: custom|lastPageNumber|chapterNumber, text?, rule?: {on, weight}, flag?: bool} — creates"); - let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect(); - assert_eq!(keys, ["name", "type", "text", "rule", "flag"]); - assert_eq!(f[1].choices, ["custom", "lastPageNumber", "chapterNumber"]); - assert!(!f[0].optional && f[2].optional); - assert!(f[4].boolean); - assert!(command_fields("{}").is_empty()); - assert!(command_fields("no params").is_empty()); - // A parenthetical after the key describes the value. - let f = command_fields("{angle (degrees, CCW), ids?}"); - let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect(); - assert_eq!(keys, ["angle", "ids"]); - assert!(!f[0].optional && f[1].optional); - assert_eq!(f[0].hint, "degrees, CCW"); - let f = command_fields("{scaleX? (%), ref?: 0..8, ids?: parent items (default: all)}"); - let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect(); - assert_eq!(keys, ["scaleX", "ref", "ids"]); - assert!(f.iter().all(|f| f.optional)); - assert_eq!(f[0].hint, "%"); - assert_eq!(f[2].hint, "parent items (default: all)"); - // Every command with a "…" label parses without panicking. - for c in designcraft_engine::command_specs() { - let _ = command_fields(c.params); - } - } - - fn test_app() -> crate::DesignApp { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 1})).unwrap(); - app - } - - #[test] - fn toc_dialog_keeps_the_character_styles_and_sorting_of_its_entries() { - let mut app = test_app(); - app.session.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap(); - app.session.execute("style.character.create", &json!({"name": "Number"})).unwrap(); - app.session.execute("style.character.create", &json!({"name": "Dots"})).unwrap(); - let sid = - app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Pears\nApples"})).unwrap()["story"] - .clone(); - app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 8})).unwrap(); - app.session.execute("style.paragraph.apply", &json!({"name": "Head"})).unwrap(); - app.session.execute("layout.pages.insert", &json!({"count": 1})).unwrap(); - let entries = json!([{"style": "Head", "pageNumberStyle": "Number", "separatorStyle": "Dots", "sort": true}]); - app.session.execute("toc.generate", &json!({"page": 2, "entries": entries})).unwrap(); - let before = app.session.active().unwrap().doc.toc.clone().unwrap(); - // The dialog shows the options, and OK (Replace Existing) writes them back unchanged. - open_toc(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - let row = &toc_rows(d)[0]; - assert_eq!((row.page_number_style.as_str(), row.separator_style.as_str(), row.sort), ("Number", "Dots", true)); - let chars: Vec = serde_json::from_value(d.fields["charStyles"].clone()).unwrap(); - assert_eq!(chars, ["Number", "Dots"], "[None] is the menu's first choice, not a style"); - let p = toc_params(&app, d); - assert_eq!( - (&p["entries"][0]["pageNumberStyle"], &p["entries"][0]["separatorStyle"], &p["entries"][0]["sort"]), - (&json!("Number"), &json!("Dots"), &json!(true)) - ); - confirm(&mut app).expect("OK regenerates the table of contents"); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.toc.as_ref().unwrap().entries, before.entries); - // [None] and unsorted are left out of the params. - let mut d = Dialog::new(TOC, json!({"included": [{"style": "Head", "level": 1, "separator": "^t"}]})); - d.fields.insert("replace".into(), json!(true)); - let p = toc_params(&app, &d); - assert!(p["entries"][0].get("pageNumberStyle").is_none() && p["entries"][0].get("sort").is_none(), "{p}"); - } - - #[test] - fn paragraph_style_options_dialog_saves_edits() { - let mut app = test_app(); - let name = app.session.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap()["name"].as_str().unwrap().to_string(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": name, "p.align": "center"}))); - confirm(&mut app).expect("OK saves the style edit"); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.styles.para(&name).unwrap().para.align, Some(designcraft_doc::Align::Center)); - } - - #[test] - fn paragraph_style_options_align_to_grid_shows_and_sets_the_style_grid_alignment() { - use designcraft_doc::GridAlign; - use egui_kittest::kittest::Queryable; - let mut app = test_app(); - app.session.execute("style.paragraph.create", &json!({"name": "Grid Body", "para": {"gridAlign": "firstLineOnly"}})).unwrap(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"}))); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - let grid = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| { - h.state().app.session.active().unwrap().doc.styles.para("Grid Body").unwrap().para.grid_align - }; - h.run_steps(4); - h.get_by_value("First Line Only"); - confirm(&mut h.state_mut().app).unwrap(); - assert_eq!(grid(&h), Some(GridAlign::FirstLineOnly), "OK without edits keeps the style's alignment"); - h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"}))); - h.run_steps(4); - h.get_by_value("First Line Only").click(); - h.run_steps(3); - h.get_by_label("All Lines").click(); - h.run_steps(3); - confirm(&mut h.state_mut().app).unwrap(); - assert_eq!(grid(&h), Some(GridAlign::AllLines)); - } - - #[test] - fn delete_paragraph_style_dialog_removes_the_style_and_reassigns_text() { - let mut app = test_app(); - let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string(); - let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap(); - app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap(); - app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); - app.session.execute("style.paragraph.apply", &json!({"name": name})).unwrap(); - app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH}))); - confirm(&mut app).expect("OK deletes the style"); - let st = app.session.active().unwrap(); - assert!(st.doc.styles.para(&name).is_none(), "style removed"); - let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap(); - assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "text reassigned to the replacement style"); - } - - #[test] - fn delete_paragraph_style_dialog_defaults_replacement_to_basic_paragraph() { - let mut app = test_app(); - let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string(); - // No `replaceWith` set — the dialog's default field. - app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name}))); - confirm(&mut app).expect("OK deletes the style with the default replacement"); - let st = app.session.active().unwrap(); - assert!(st.doc.styles.para(&name).is_none()); - } - - #[test] - fn character_style_options_dialog_saves_edits() { - let mut app = test_app(); - let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); - app.ui.dialog = Some(Dialog::new("characterStyleOptions", json!({"name": name, "c.tracking": 20.0}))); - confirm(&mut app).expect("OK saves the style edit"); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.styles.char_style(&name).unwrap().chars.tracking, Some(20.0)); - } - - #[test] - fn delete_character_style_dialog_removes_the_style_and_reassigns_text() { - let mut app = test_app(); - let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); - let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap(); - app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap(); - app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap(); - app.session.execute("style.character.apply", &json!({"name": name})).unwrap(); - app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE}))); - confirm(&mut app).expect("OK deletes the style"); - let st = app.session.active().unwrap(); - assert!(st.doc.styles.char_style(&name).is_none(), "style removed"); - let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap(); - assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "text reassigned to the replacement style"); - } - - #[test] - fn delete_character_style_dialog_defaults_replacement_to_none() { - let mut app = test_app(); - let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); - // No `replaceWith` set — the dialog's default field. - app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name}))); - confirm(&mut app).expect("OK deletes the style with the default replacement"); - let st = app.session.active().unwrap(); - assert!(st.doc.styles.char_style(&name).is_none()); - } - - /// File › Export EPUB… opens EPUB Export Options from the document's setting; OK stores a - /// changed Split Document as one undo step, and an unchanged one adds none. - #[test] - fn epub_export_passes_its_options_to_the_engine() { - use std::io::Read; - use std::sync::{Arc, Mutex}; - let mut app = test_app(); - app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap(); - let r = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "One\nTwo"})).unwrap(); - let sid = r["story"].as_u64().unwrap(); - for anchor in [0, 4] { - app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": anchor})).unwrap(); - app.session.execute("style.paragraph.apply", &json!({"name": "Chapter"})).unwrap(); - } - let written: Arc>> = Arc::new(Mutex::new(Vec::new())); - let sink = written.clone(); - app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| { - *sink.lock().unwrap() = bytes.to_vec(); - Ok(()) - })); - crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "split": {"style": "Chapter"}})).unwrap(); - let bytes = written.lock().unwrap().clone(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut opf = String::new(); - z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); - assert!(opf.contains("properties=\"cover-image\""), "the first page is the cover: {opf}"); - assert!(z.by_name("OEBPS/content2.xhtml").is_ok(), "the split override reaches the export"); - assert_eq!(app.session.active().unwrap().doc.settings.epub_split, designcraft_doc::EpubSplit::Off, "an override is not stored"); - crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "cover": false})).unwrap(); - let bytes = written.lock().unwrap().clone(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut opf = String::new(); - z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); - assert!(!opf.contains("cover-image"), "a caller's cover: false stays: {opf}"); - } - - #[test] - fn epub_export_options_store_split_document() { - use designcraft_doc::EpubSplit; - let mut app = test_app(); - app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap(); - let undo_steps = |app: &crate::DesignApp| app.session.active().map(|st| st.history.undo.len()); - app.run("app.exportEpub", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!((d.id.as_str(), d.b("split"), d.s("style").as_str()), ("epubExport", false, designcraft_doc::BASIC_PARAGRAPH)); - d.fields.insert("split".into(), json!(true)); - d.fields.insert("style".into(), json!("Chapter")); - let before = undo_steps(&app); - confirm(&mut app).unwrap(); - assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::Style("Chapter".into())); - assert_eq!(undo_steps(&app), before.map(|n| n + 1)); - open_epub_export(&mut app); - assert_eq!(app.ui.dialog.as_ref().map(|d| (d.b("split"), d.s("mode"), d.s("style"))), Some((true, "style".into(), "Chapter".into()))); - confirm(&mut app).unwrap(); - assert_eq!(undo_steps(&app), before.map(|n| n + 1), "unchanged: no undo step"); - open_epub_export(&mut app); - app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("exportTags")); - confirm(&mut app).unwrap(); - assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags); - open_epub_export(&mut app); - cancel(&mut app); - assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags, "Cancel stores nothing"); - } - - #[test] - fn pdf_export_defaults() { - let d = Dialog::new("pdfExport", json!({})); - let keys: Vec<&str> = d.fields.iter().map(|(k, _)| k.as_str()).collect(); - // serde_json::Map keeps keys sorted. - let expected = [ - "bleed", - "compressImages", - "flatten", - "marksBleed", - "marksCrop", - "marksOffset", - "marksPageInfo", - "marksWeight", - "preset", - "spreads", - "standard", - "tagged", - ]; - assert_eq!(keys, expected); - assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing")); - assert_eq!(d.fields["standard"].as_str(), Some("none")); - assert_eq!(d.fields["compressImages"].as_bool(), Some(false)); - assert_eq!(d.fields["flatten"].as_str(), Some("")); - assert_eq!(d.fields["spreads"].as_bool(), Some(false)); - assert_eq!(d.fields["bleed"].as_bool(), Some(true)); - assert_eq!(d.fields["marksCrop"].as_bool(), Some(false)); - assert_eq!(d.fields["marksBleed"].as_bool(), Some(false)); - assert_eq!(d.fields["marksPageInfo"].as_bool(), Some(false)); - assert_eq!(d.fields["marksWeight"].as_str(), Some("0.25")); - assert_eq!(d.fields["marksOffset"].as_str(), Some("6")); - assert_eq!(d.fields["tagged"].as_bool(), Some(true)); - } - - #[test] - fn pdf_export_override_keeps_override() { - let d = Dialog::new("pdfExport", json!({"bleed": false})); - assert_eq!(d.fields["bleed"].as_bool(), Some(false)); - assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing")); - assert_eq!(d.fields["tagged"].as_bool(), Some(true)); - } - - #[test] - fn pdf_export_preset_high_quality_print_keeps_flatten() { - let mut d = Dialog::new("pdfExport", json!({})); - d.fields.insert("flatten".into(), json!("medium")); - apply_pdf_preset(&mut d, "Desktop Printing"); - assert_eq!(d.s("standard"), "none"); - assert!(!d.b("compressImages")); - assert!(!d.b("marksCrop")); - assert!(!d.b("marksBleed")); - assert!(!d.b("marksPageInfo")); - assert_eq!(d.s("flatten"), "medium", "a leave-unchanged preset must not touch flatten"); - } - - #[test] - fn pdf_export_preset_press_quality_keeps_flatten() { - let mut d = Dialog::new("pdfExport", json!({})); - d.fields.insert("flatten".into(), json!("high")); - apply_pdf_preset(&mut d, "Commercial Printing"); - assert_eq!(d.s("standard"), "none"); - assert!(d.b("compressImages")); - assert!(d.b("marksCrop")); - assert!(d.b("marksBleed")); - assert!(!d.b("marksPageInfo")); - assert_eq!(d.s("flatten"), "high"); - } - - #[test] - fn pdf_export_preset_smallest_file_size_sets_flatten_low() { - let mut d = Dialog::new("pdfExport", json!({})); - apply_pdf_preset(&mut d, "Screen and Email"); - assert_eq!(d.s("standard"), "none"); - assert!(d.b("compressImages")); - assert!(!d.b("marksCrop")); - assert!(!d.b("marksBleed")); - assert!(!d.b("marksPageInfo")); - assert_eq!(d.s("flatten"), "low"); - } - - /// The PDF/X-1a preset exports X-1a with the High Resolution flattener and printer's marks. - #[test] - fn pdf_export_preset_pdf_x1a_flattens_at_high_resolution() { - let mut d = Dialog::new("pdfExport", json!({})); - apply_pdf_preset(&mut d, "PDF/X-1a:2003"); - assert_eq!(d.s("standard"), "x1a"); - assert_eq!(d.s("flatten"), "high"); - assert!(d.b("marksCrop") && d.b("marksBleed")); - assert!(PDF_EXPORT_PRESETS.contains(&"PDF/X-1a:2003")); - } - - #[test] - fn pdf_export_preset_pdf_x4_keeps_flatten() { - let mut d = Dialog::new("pdfExport", json!({})); - d.fields.insert("flatten".into(), json!("medium")); - apply_pdf_preset(&mut d, "PDF/X-4"); - assert_eq!(d.s("standard"), "x4"); - assert!(!d.b("compressImages")); - assert!(d.b("marksCrop")); - assert!(d.b("marksBleed")); - assert!(!d.b("marksPageInfo")); - assert_eq!(d.s("flatten"), "medium"); - } - - #[test] - fn pdf_export_preset_pdf_a2b_keeps_flatten() { - let mut d = Dialog::new("pdfExport", json!({})); - d.fields.insert("flatten".into(), json!("low")); - apply_pdf_preset(&mut d, "PDF/A-2b"); - assert_eq!(d.s("standard"), "a2b"); - assert!(!d.b("compressImages")); - assert!(!d.b("marksCrop")); - assert!(!d.b("marksBleed")); - assert!(!d.b("marksPageInfo")); - assert_eq!(d.s("flatten"), "low"); - } - - #[test] - fn open_pdf_export_seeds_fields_from_settings() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.pdf_export.standard = "x4".into(); - app.ui.pdf_export.tagged = false; - app.ui.pdf_export.marks_crop = true; - app.ui.pdf_export.flatten = String::new(); - app.ui.flattener = "medium".into(); - open_pdf_export(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.id, "pdfExport"); - assert_eq!(d.s("standard"), "x4"); - assert!(!d.b("tagged")); - assert!(d.b("marksCrop")); - assert_eq!(d.s("pages"), "all"); - assert_eq!(d.s("flatten"), "medium", "empty flatten falls back to the global flattener"); - assert_eq!(d.s("title"), "", "no document → empty title"); - - // A non-empty persisted flatten is used verbatim, not the global fallback. - app.ui.pdf_export.flatten = "low".into(); - app.ui.flattener = "medium".into(); - open_pdf_export(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.s("flatten"), "low"); - } - - #[test] - fn pdf_export_preset_custom_changes_nothing() { - let mut d = Dialog::new("pdfExport", json!({})); - d.fields.insert("standard".into(), json!("x4")); - d.fields.insert("compressImages".into(), json!(true)); - d.fields.insert("marksCrop".into(), json!(true)); - d.fields.insert("marksBleed".into(), json!(true)); - d.fields.insert("marksPageInfo".into(), json!(true)); - d.fields.insert("flatten".into(), json!("high")); - let before = d.fields.clone(); - apply_pdf_preset(&mut d, "Custom"); - assert_eq!(d.fields, before); - } - - #[test] - fn confirm_pdf_export_writes_file_and_persists_settings() { - use std::sync::{Arc, Mutex}; - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let writes: Arc)>>> = Arc::new(Mutex::new(Vec::new())); - let sink = writes.clone(); - app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { - sink.lock().unwrap().push((path.to_string(), bytes.to_vec())); - Ok(()) - })); - app.services.pick_save = Some(Box::new(|_name: &str| Some("/tmp/designcraft-test.pdf".to_string()))); - - app.ui.dialog = Some(Dialog::new("pdfExport", json!({}))); - { - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("standard".into(), json!("x4")); - d.fields.insert("bleed".into(), json!(false)); - d.fields.insert("marksCrop".into(), json!(true)); - d.fields.insert("tagged".into(), json!(false)); - d.fields.insert("title".into(), json!("Report")); - } - confirm(&mut app).unwrap(); - - let got = writes.lock().unwrap(); - assert_eq!(got.len(), 1, "confirming the dialog writes exactly one file"); - assert_eq!(got[0].0, "/tmp/designcraft-test.pdf"); - assert!(got[0].1.starts_with(b"%PDF"), "the written bytes are a PDF"); - drop(got); - - assert_eq!(app.ui.pdf_export.standard, "x4"); - assert!(!app.ui.pdf_export.bleed); - assert!(app.ui.pdf_export.marks_crop); - assert!(!app.ui.pdf_export.tagged); - } - - #[test] - fn update_link_asks_before_replacing_edits_made_in_the_layout() { - let dir = std::env::temp_dir().join(format!("dc-update-link-dialog-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("note.txt"); - std::fs::write(&path, "One").unwrap(); - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let r = app.session.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true, "rect": [72, 72, 300, 200]})).unwrap(); - let sid = r["story"].as_u64().unwrap(); - let text = |app: &crate::DesignApp| app.session.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone(); - - // Not edited in the layout: updates without asking. - std::fs::write(&path, "Two").unwrap(); - crate::panels::properties::update_links(&mut app, json!({"story": sid})); - assert!(app.ui.dialog.is_none()); - assert_eq!(text(&app), "Two"); - - // Edited in the layout: asks first; Cancel changes nothing. - app.session.execute("story.setText", &json!({"story": sid, "text": "Mine"})).unwrap(); - std::fs::write(&path, "Three").unwrap(); - crate::panels::properties::update_links(&mut app, json!({"story": sid})); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.id.as_str(), d.s("files").as_str()), ("updateLink", "note.txt")); - app.ui.dialog = None; - assert_eq!(text(&app), "Mine"); - - // Window › Links › Update Link (all links) asks too; confirming updates. - crate::menus::activate(&mut app, "links.update", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("updateLink")); - confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - assert_eq!(text(&app), "Three"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn confirm_pdf_export_cancelled_save_writes_nothing() { - use std::sync::{Arc, Mutex}; - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let writes: Arc)>>> = Arc::new(Mutex::new(Vec::new())); - let sink = writes.clone(); - app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { - sink.lock().unwrap().push((path.to_string(), bytes.to_vec())); - Ok(()) - })); - app.services.pick_save = Some(Box::new(|_name: &str| None)); - - app.ui.dialog = Some(Dialog::new("pdfExport", json!({}))); - let r = confirm(&mut app).unwrap(); - assert_eq!(r, Value::Null); - assert!(writes.lock().unwrap().is_empty(), "cancelling the save picker must not write"); - } - - use designcraft_doc::{CharAttrs, CharacterStyle}; - - /// A document with character styles Base (bold) and Emphasis (italic) on the first two letters. - fn styled_app() -> DesignApp { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.character.create", json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap(); - app.run("style.character.create", json!({"name": "Emphasis", "chars": {"fontStyle": "Italic"}})).unwrap(); - let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap(); - app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 2})).unwrap(); - app.run("style.character.apply", json!({"name": "Emphasis"})).unwrap(); - app - } - - /// One control-channel request, as the control port or MCP would send it. - fn ctl(app: &mut DesignApp, method: &str, params: Value) -> Value { - let (req, _reply) = crate::control::ControlRequest::new(method, params); - match crate::control::handle(app, &egui::Context::default(), &req) { - crate::control::Outcome::Done(v) => v, - crate::control::Outcome::Screenshot { .. } => Value::Null, - } - } - - fn char_style(app: &DesignApp, name: &str) -> Option { - app.session.active().and_then(|st| st.doc.styles.char_style(name).cloned()) - } - - #[test] - fn character_style_options_set_exactly_the_edited_attributes() { - let mut app = styled_app(); - assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}))["ok"], true); - ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 14})); - ctl(&mut app, "ui.dialog.set", json!({"field": "c.fill", "value": "[Paper]"})); - ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": "Base"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert!(app.ui.dialog.is_none()); - let st = char_style(&app, "Emphasis").unwrap(); - assert_eq!(st.based_on.as_deref(), Some("Base")); - assert_eq!(st.chars, CharAttrs { font_style: Some("Italic".into()), size: Some(14.0), fill: Some("[Paper]".into()), ..Default::default() }); - } - - #[test] - fn character_style_options_unset_cleared_fields_and_rename_every_use() { - let mut app = styled_app(); - ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}})); - ctl(&mut app, "ui.dialog.set", json!({"field": "c.fontStyle", "value": null})); - ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Strong"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert!(char_style(&app, "Emphasis").is_none()); - assert!(char_style(&app, "Strong").unwrap().chars.is_empty()); - let st = app.session.active().unwrap(); - let story = st.doc.stories.values().next().unwrap(); - assert!(story.chars.iter().any(|r| r.format.style == "Strong")); - // A taken name keeps the dialog open with the reason. - ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Strong"}})); - ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Base"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.s("status").is_empty())); - assert!(char_style(&app, "Strong").is_some()); - } - - #[test] - fn new_character_style_opens_its_options_and_creates_the_style() { - let mut app = styled_app(); - crate::menus::activate(&mut app, "style.character.create", &Value::Null); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("characterStyleOptions", true, "Character Style 1")); - ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 9})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let st = char_style(&app, "Character Style 1").unwrap(); - assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), ..Default::default() })); - crate::menus::activate(&mut app, "style.character.create", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("rename"), "Character Style 2"); - } - - #[test] - fn new_paragraph_style_opens_its_options_and_creates_the_style() { - let mut app = styled_app(); - crate::menus::activate(&mut app, "style.paragraph.create", &Value::Null); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("paragraphStyleOptions", true, "Paragraph Style 1")); - ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 20})); - ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": designcraft_doc::BASIC_PARAGRAPH})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap(); - assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - assert_eq!(st.chars, CharAttrs { size: Some(20.0), ..Default::default() }); - } - - #[test] - fn style_rows_open_their_options_except_none() { - let mut app = styled_app(); - open_style_options(&mut app, false, "Emphasis"); - let d = app.ui.dialog.take().unwrap(); - assert_eq!((d.id.as_str(), d.s("name").as_str()), ("characterStyleOptions", "Emphasis")); - open_style_options(&mut app, false, designcraft_doc::NO_CHAR_STYLE); - assert!(app.ui.dialog.is_none()); - open_style_options(&mut app, true, designcraft_doc::BASIC_PARAGRAPH); - assert_eq!(app.ui.dialog.take().unwrap().id, "paragraphStyleOptions"); - } - - #[test] - fn style_options_sections_draw() { - let mut app = styled_app(); - let ctx = egui::Context::default(); - let frame = |app: &mut DesignApp| { - for _ in 0..2 { - let raw = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))), - max_texture_side: Some(8192), - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - } - }; - for lang in ["", "ar"] { - app.run("app.language", json!({"lang": lang})).unwrap(); - for fields in [json!({"name": "Emphasis"}), json!({"new": true}), json!({"name": "Emphasis", "c.size": null, "c.underline": false})] { - for section in ["general", "chars", "advanced", "color", "openType", "underline", "strikethrough"] { - let mut f = fields.clone(); - f["section"] = json!(section); - app.ui.dialog = Some(Dialog::new("characterStyleOptions", f)); - frame(&mut app); - assert!(app.ui.dialog.is_some(), "{section} stays open"); - } - } - for section in - ["general", "chars", "advanced", "border", "shading", "keep", "span", "bullets", "color", "openType", "underline", "strikethrough"] - { - for fields in [ - json!({"new": true}), - json!({"new": true, "p.listType": "bullets", "p.spanColumns": {"kind": "span", "columns": 0}, "p.borderOn": true}), - json!({"new": true, "p.listType": "numbers", "p.startAt": 1, "p.spanColumns": {"kind": "split", "columns": 2}, "p.keepLinesTogether": true}), - ] { - let mut f = fields; - f["section"] = json!(section); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", f)); - frame(&mut app); - assert!(app.ui.dialog.is_some(), "{section} stays open"); - } - } - } - } - - #[test] - fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { - use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; - use egui_kittest::{Harness, kittest::Queryable}; - fn drag(h: &mut Harness<'static, DesignApp>, from: Pos2, to: Pos2) { - h.event(Event::PointerMoved(from)); - h.run_steps(1); - h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - for step in 1..=8 { - h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0))); - h.run_steps(1); - } - h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); - } - let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap(); - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.ui.dialog = Some(Dialog::new("insertTable", Value::Null)); - let mut ready = false; - let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( - move |ui, app: &mut DesignApp| { - if !ready { - crate::theme::install_fonts(ui.ctx(), &app.ui.language); - crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default())); - ready = true; - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - let centred = rect(&h); - assert!((centred.center() - egui::pos2(600.0, 400.0)).length() < 1.0, "{centred:?}"); - assert!(centred.width() < 1000.0 && centred.height() < 700.0, "the area is the dialog, not the backdrop: {centred:?}"); - - let title = h.get_by_label("Create Table").rect().center(); - drag(&mut h, title, title + vec2(100.0, 60.0)); - let moved = rect(&h); - assert!((moved.min - centred.min - vec2(100.0, 60.0)).length() < 2.0, "{centred:?} -> {moved:?}"); - - let body = egui::pos2(moved.right() - 40.0, moved.center().y); - drag(&mut h, body, body + vec2(-150.0, 80.0)); - assert_eq!(rect(&h), moved, "a drag in the body leaves the dialog in place"); - - // The title row stays inside the top edge. - let title = h.get_by_label("Create Table").rect().center(); - drag(&mut h, title, title - vec2(0.0, 1000.0)); - assert!(rect(&h).top().abs() < 1.0, "{:?}", rect(&h)); - - // Opened again, the dialog starts centred. - h.state_mut().ui.dialog = None; - h.run_steps(2); - h.state_mut().ui.dialog = Some(Dialog::new("insertTable", Value::Null)); - h.run_steps(4); - assert!((rect(&h).center() - centred.center()).length() < 1.0, "{:?}", rect(&h)); - - // Past the left edge, about 100 px of the title row stays inside. - let title = h.get_by_label("Create Table").rect().center(); - drag(&mut h, title, title - vec2(900.0, 0.0)); - assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h)); - } - - #[test] - fn the_new_document_window_drags_mostly_aside_and_keeps_its_preview() { - use egui::{Event, Modifiers, PointerButton, vec2}; - use egui_kittest::{Harness, kittest::Queryable}; - let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap(); - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"title": "A"})).unwrap(); - app.ui.new_document_preview = true; - app.run("app.newDocumentDialog", json!({})).unwrap(); - let mut ready = false; - let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( - move |ui, app: &mut DesignApp| { - if !ready { - crate::theme::install_fonts(ui.ctx(), &app.ui.language); - crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default())); - ready = true; - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(6); - let preview = h.state().session.new_document_preview(); - assert!(preview.is_some(), "Preview is on"); - let centred = rect(&h); - assert!(centred.width() > 900.0, "{centred:?}"); - let from = h.get_all_by_label("New Document").map(|n| n.rect().center()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap(); - let to = from + vec2(1300.0, 0.0); - h.event(Event::PointerMoved(from)); - h.run_steps(1); - h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - for step in 1..=8 { - h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0))); - h.run_steps(1); - } - h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); - // All but 100 px of the window's width is past the right edge, over the preview. - assert!((rect(&h).left() - 1300.0).abs() < 2.0, "{:?}", rect(&h)); - let app = h.state(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("newDocument")); - assert_eq!(app.session.new_document_preview(), preview, "moving the window keeps the preview"); - assert_eq!(app.session.documents().len(), 2); - } - - #[test] - fn margins_dialog_reads_bare_numbers_in_the_ruler_unit() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap(); - crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null); - for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] { - ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "15"})); - } - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let top = app.session.active().unwrap().doc.page(0).unwrap().margins.top; - assert!((top - 15.0 * 72.0 / 25.4).abs() < 0.01, "top margin was {top} pt"); - } - fn facing_app(pages: u64) -> DesignApp { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": pages, "facingPages": true})).unwrap(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); - app - } - - fn guide_counts(app: &DesignApp) -> Vec { - let doc = &app.session.active().unwrap().doc; - (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect() - } - - #[test] - fn create_guides_dialog_targets_the_page_in_view() { - let mut app = facing_app(6); - crate::canvas::go_to_page(&mut app, 4); - crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); - ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert_eq!(guide_counts(&app), vec![0, 0, 0, 0, 4, 0]); - // "Both pages of the spread" covers the facing pair. - crate::canvas::go_to_page(&mut app, 1); - crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); - ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"})); - ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "spread"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]); - } - - #[test] - fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() { - let mut app = facing_app(4); - app.run("layout.parents.edit", json!({"on": true})).unwrap(); - crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread"); - for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] { - ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "20 pt"})); - } - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); - ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let doc = &app.session.active().unwrap().doc; - for pg in &doc.parents[0].pages { - assert_eq!((pg.margins.top, pg.margins.outside, pg.guides.len()), (20.0, 20.0, 2)); - } - // Every document page shows the parent's guides. - assert!((0..doc.page_count()).all(|abs| doc.inherited_guides(abs).len() == 2)); - } - - #[test] - fn other_dialogs_keep_reading_bare_numbers_as_picas() { - let mut app = facing_app(2); - app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap(); - app.ui.dialog = Some(Dialog::new("newDocument", json!({"width": "15"}))); - assert_eq!(app.ui.dialog.as_ref().unwrap().m("width"), Some(180.0)); - } - #[test] - fn character_style_options_set_the_digits() { - let mut app = styled_app(); - ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}})); - ctl(&mut app, "ui.dialog.set", json!({"field": "c.digits", "value": "farsi"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); - } -} +mod tests; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs new file mode 100644 index 000000000..80971b57f --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -0,0 +1,3494 @@ +use super::*; + +#[test] +fn paragraph_style_settings_show_captured_color_and_pending_spacing_without_changing_the_document() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Heading"})).unwrap(); + app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":7})).unwrap(); + app.run("type.char", json!({"fontFamily":"Source Sans 3","fontStyle":"Bold","size":16,"fill":"[Paper]"})).unwrap(); + app.run("style.paragraph.create", json!({"name":"Header","fromSelection":true})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let style = doc.styles.para("Header").unwrap(); + let mut d = Dialog::new("paragraphStyleOptions", json!({"name":"Header"})); + let summary = paragraph_style_summary("", &d, style, &doc.styles); + for value in ["Source Sans 3", "Bold", "16 pt", "[Paper]"] { + assert!(summary.contains(value), "{summary}"); + } + assert!(summary.len() < 250, "default attributes do not swamp the captured settings: {summary}"); + d.fields.insert("c.fill".into(), json!("[Registration]")); + d.fields.insert("p.spaceAfter".into(), json!(4.5)); + let summary = paragraph_style_summary("", &d, style, &doc.styles); + assert!(summary.contains("[Registration]") && !summary.contains("[Paper]"), "{summary}"); + assert!(summary.contains("4.5 pt"), "{summary}"); + assert_eq!(app.session.doc().unwrap().doc, doc); +} + +/// A dialog opened without the menu's fields has no `useDefaults` field at all. Confirming it +/// with no layer unticked must keep the file's defaults, not choose every layer explicitly: +/// an implicit all-on choice is rejected for a PDF without layers, so the command's error +/// tells the two apart. +#[test] +fn layer_options_confirm_without_the_menu_fields_keeps_file_defaults() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100, "pages": 1})).unwrap(); + let pdf = app.run("file.exportPdf", json!({})).unwrap()["base64"].clone(); + let placed = app.run("file.place", json!({"base64": pdf, "name": "plain.pdf", "x": 0, "y": 0, "width": 100})).unwrap(); + let id = designcraft_doc::ItemId(placed["id"].as_u64().unwrap()); + app.run("selection.set", json!({"ids": [placed["id"]]})).unwrap(); + app.ui.dialog = Some(Dialog::new("layerOptions", json!({}))); + confirm(&mut app).unwrap(); + assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "an untouched dialog keeps the file defaults"); + // The menu's own dialog still asks for an explicit all-on choice when that is the state + // it was opened in; a layerless PDF refuses it rather than accepting an empty override. + app.ui.dialog = Some(Dialog::new("layerOptions", json!({"useDefaults": false, "layers": []}))); + let err = confirm(&mut app).unwrap_err(); + assert!(err.contains("could not be changed"), "{err}"); + assert!(!app.session.doc().unwrap().doc.item(id).unwrap().has_pdf_layer_override(), "a layerless PDF never takes an explicit choice"); +} + +#[test] +fn paragraph_style_settings_compare_with_the_chosen_parent() { + let mut styles = designcraft_doc::Styles::default(); + styles.paragraph.push(designcraft_doc::ParagraphStyle { + name: "Parent".into(), + chars: designcraft_doc::CharAttrs { size: Some(20.0), ..Default::default() }, + based_on: None, + next_style: None, + para: Default::default(), + shortcut: String::new(), + }); + let style = designcraft_doc::ParagraphStyle { + name: "Child".into(), + based_on: Some("Parent".into()), + next_style: None, + para: Default::default(), + chars: Default::default(), + shortcut: String::new(), + }; + let d = Dialog::new("paragraphStyleOptions", json!({"name":"Child"})); + assert_eq!(paragraph_style_summary("", &d, &style, &styles), "Parent"); +} + +#[test] +fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let open = |app: &mut DesignApp| { + crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT)); + }; + let set = |app: &mut DesignApp, k: &str, v: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + }; + let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len(); + let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len(); + let (n0, u0) = (items(&app), undo(&app)); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + open(&mut app); + dialog_frame(&mut app, &ctx, screen, vec![]); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] { + visible_label(&labels, screen, expected); + } + // Preview: the copies show, and change with the fields, without an undo step. + set(&mut app, "count", json!("5")); + set(&mut app, "vertical", json!("-0.75 in")); + set(&mut app, "horizontal", json!("0")); + set(&mut app, "preview", json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!((items(&app), undo(&app)), (n0 + 5, u0)); + set(&mut app, "count", json!("3")); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(items(&app), n0 + 3); + set(&mut app, "preview", json!(false)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(items(&app), n0, "Preview off takes them away"); + set(&mut app, "preview", json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(items(&app), n0 + 3); + // Cancel puts the document back. + cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!((items(&app), undo(&app)), (n0, u0)); + // OK after a preview makes the copies once, as one undo step, 0.75 in apart. + app.run("selection.set", json!({"ids": [id]})).unwrap(); + open(&mut app); + set(&mut app, "count", json!("2")); + set(&mut app, "vertical", json!("-0.75 in")); + set(&mut app, "horizontal", json!("0")); + set(&mut app, "preview", json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let r = confirm(&mut app).unwrap(); + assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1)); + let last = r["ids"][1].as_u64().unwrap(); + let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y(); + assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}"); + // Create as a grid: Rows × Columns cells, the original being one. + app.run("selection.set", json!({"ids": [id]})).unwrap(); + open(&mut app); + set(&mut app, "grid", json!(true)); + set(&mut app, "rows", json!("2")); + set(&mut app, "columns", json!("3")); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "Rows:"); + visible_label(&labels, screen, "Columns:"); + assert_eq!(confirm(&mut app).unwrap()["created"], 5); + // A value that isn't a measure keeps the dialog open and says so. + open(&mut app); + set(&mut app, "vertical", json!("up")); + assert!(confirm(&mut app).is_err()); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.s("status"), "Invalid value: up"); +} + +/// A three-page document in `units` with Document Setup open. +fn document_setup_app(units: &str) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap(); + crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); + app +} + +fn setup_fields(app: &mut DesignApp, fields: Value) { + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in fields.as_object().unwrap() { + d.fields.insert(k.clone(), v.clone()); + } +} + +/// File › File Info opens filled from the document and OK stores what was typed; Export PDF +/// then names the file after the document and takes the PDF's title from File Info. +#[test] +fn file_info_dialog_stores_the_fields_and_titles_the_pdf() { + use std::sync::{Arc, Mutex}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "flyer-v3"})).unwrap(); + app.run("file.info", json!({"author": "Ana Ruiz", "keywords": ["spring", "shoes"]})).unwrap(); + crate::menus::activate(&mut app, "file.info", &Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.id, "fileInfo"); + assert_eq!((d.s("documentTitle"), d.s("author"), d.s("keywords")), (String::new(), "Ana Ruiz".into(), "spring; shoes".into())); + setup_fields(&mut app, json!({"documentTitle": "Spring Catalog", "author": "", "keywords": "spring, catalog", "description": "Shoes"})); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let info = app.session.active().unwrap().doc.file_info.clone(); + assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "", "Shoes")); + assert_eq!(info.keywords, ["spring", "catalog"]); + // Keywords left as shown stay as they are, even one with a comma in it. + app.run("file.info", json!({"keywords": ["Washington, DC", "map"]})).unwrap(); + crate::menus::activate(&mut app, "file.info", &Value::Null); + setup_fields(&mut app, json!({"author": "Studio"})); + confirm(&mut app).unwrap(); + let info = app.session.active().unwrap().doc.file_info.clone(); + assert_eq!((info.author.as_str(), info.keywords.clone()), ("Studio", vec!["Washington, DC".to_string(), "map".to_string()])); + // Another keyword edited: the one with a comma in it still stays one keyword. + crate::menus::activate(&mut app, "file.info", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("keywords"), "Washington, DC; map"); + setup_fields(&mut app, json!({"keywords": "Washington, DC; atlas"})); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.file_info.keywords, ["Washington, DC", "atlas"]); + + let writes: Arc>>> = Arc::new(Mutex::new(Vec::new())); + let sink = writes.clone(); + app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| { + sink.lock().unwrap().push(bytes.to_vec()); + Ok(()) + })); + let names: Arc>> = Arc::new(Mutex::new(Vec::new())); + let asked = names.clone(); + app.services.pick_save = Some(Box::new(move |name: &str| { + asked.lock().unwrap().push(name.to_string()); + Some("/tmp/designcraft-file-info.pdf".to_string()) + })); + open_pdf_export(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(names.lock().unwrap().as_slice(), ["flyer-v3.pdf"]); + let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[0]).into_owned(); + assert!(pdf.contains("/Title(Spring Catalog)") && !pdf.contains("/Title(flyer-v3)"), "the PDF's title is File Info's"); + // A title given to the export is the PDF's title, even when it is the document's name. + open_pdf_export(&mut app); + setup_fields(&mut app, json!({"title": "flyer-v3"})); + confirm(&mut app).unwrap(); + let asked = names.lock().unwrap().last().cloned().unwrap_or_default(); + assert_eq!(std::path::Path::new(&asked).file_name().and_then(|n| n.to_str()), Some("flyer-v3.pdf"), "{asked}"); + let pdf = String::from_utf8_lossy(&writes.lock().unwrap()[1]).into_owned(); + assert!(pdf.contains("/Title(flyer-v3)") && !pdf.contains("/Title(Spring Catalog)"), "the given title wins"); +} + +/// File Info's OK stores the fields in the document the dialog was opened for, even when +/// another document became active meanwhile; once that document has closed, OK stores nothing. +#[test] +fn file_info_dialog_stores_into_the_document_it_was_opened_for() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "first"})).unwrap(); + crate::menus::activate(&mut app, "file.info", &Value::Null); + app.run("file.new", json!({"title": "second"})).unwrap(); + setup_fields(&mut app, json!({"author": "Ana Ruiz"})); + confirm(&mut app).unwrap(); + let docs = app.session.documents(); + let author = |title: &str| docs.iter().find(|d| d.doc.title == title).map(|d| d.doc.file_info.author.clone()); + assert_eq!((author("first").as_deref(), author("second").as_deref()), (Some("Ana Ruiz"), Some(""))); + assert_eq!(app.session.active().map(|d| d.doc.title.as_str()), Some("second"), "the active document stays active"); + + crate::menus::activate(&mut app, "file.info", &Value::Null); + app.run("file.close", json!({})).unwrap(); + setup_fields(&mut app, json!({"author": "Studio"})); + confirm(&mut app).unwrap(); + assert!(app.session.documents().iter().all(|d| d.doc.file_info.author != "Studio"), "the dialog's document closed"); +} + +/// File Info opened through `ui.dialog.open` with only some fields stores only those fields; +/// the others keep what the document holds. +#[test] +fn file_info_opened_with_some_fields_keeps_the_others() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("file.info", json!({"documentTitle": "Spring Catalog", "keywords": ["spring", "shoes"]})).unwrap(); + assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": {"author": "Ana Ruiz", "description": ""}}))["ok"], true); + confirm(&mut app).unwrap(); + let info = app.session.active().unwrap().doc.file_info.clone(); + assert_eq!((info.document_title.as_str(), info.author.as_str(), info.description.as_str()), ("Spring Catalog", "Ana Ruiz", "")); + assert_eq!(info.keywords, ["spring", "shoes"]); +} + +/// Fields given to `ui.dialog.open` as JSON other than text reach `file.info` as they are: a +/// keyword list stays a list, and `null` clears a field. +#[test] +fn file_info_opened_with_a_keyword_list_stores_the_list() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("file.info", json!({"author": "Ana Ruiz"})).unwrap(); + let fields = json!({"keywords": ["Washington, DC", "map"], "author": null}); + assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "fileInfo", "fields": fields}))["ok"], true); + confirm(&mut app).unwrap(); + let info = app.session.active().unwrap().doc.file_info.clone(); + assert_eq!(info.keywords, ["Washington, DC", "map"]); + assert_eq!(info.author, ""); +} + +/// File Info's OK for a document that is not the active one leaves the active document's +/// Data Merge preview showing the record it showed. +#[test] +fn file_info_for_another_document_keeps_the_active_preview() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "first"})).unwrap(); + crate::menus::activate(&mut app, "file.info", &Value::Null); + app.run("file.new", json!({"title": "second"})).unwrap(); + let csv = designcraft_engine::cmd::base64_encode(b"Name\nAda\nGrace\n"); + app.run("data.source.select", json!({"bytes": csv, "name": "people.csv"})).unwrap(); + app.run("data.preview", json!({"record": 2})).unwrap(); + setup_fields(&mut app, json!({"author": "Ana Ruiz"})); + confirm(&mut app).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.doc.title.as_str(), active.preview_record), ("second", Some(2)), "the preview still shows record 2"); + let first = app.session.documents().iter().find(|d| d.doc.title == "first").map(|d| d.doc.file_info.author.clone()); + assert_eq!(first.as_deref(), Some("Ana Ruiz")); +} + +#[test] +fn document_setup_ok_applies_margins_bleed_and_size_in_one_step() { + let mut app = document_setup_app("millimeters"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.id, "documentSetup"); + assert_eq!((d.s("marginTop"), d.b("marginLinked")), ("12.7 mm".to_string(), true), "the document's margins, in its units"); + setup_fields( + &mut app, + json!({"marginTop": "20 mm", "marginBottom": "20 mm", "marginInside": "20 mm", "marginOutside": "20 mm", "bleedTop": "3 mm", + "bleedBottom": "3 mm", "bleedInside": "3 mm", "bleedOutside": "3 mm", "width": "210 mm", "height": "297 mm"}), + ); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let mm = designcraft_geom::units::PT_PER_MM; + let doc = &app.session.active().unwrap().doc; + assert!((doc.settings.page_width - 210.0 * mm).abs() < 1e-6 && (doc.settings.bleed[2] - 3.0 * mm).abs() < 1e-6); + assert!(doc.spreads.iter().flat_map(|s| &s.pages).all(|p| (p.margins.top - 20.0 * mm).abs() < 1e-6), "every page"); + app.run("edit.undo", json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!((doc.settings.page_width - 612.0).abs() < 1e-6 && doc.settings.bleed[0] == 0.0, "one undo step"); +} + +#[test] +fn document_setup_reads_a_bare_number_in_the_documents_units() { + let mut app = document_setup_app("millimeters"); + setup_fields(&mut app, json!({"bleedTop": "5", "bleedBottom": "5", "bleedInside": "5", "bleedOutside": "5", "width": "210"})); + confirm(&mut app).unwrap(); + let mm = designcraft_geom::units::PT_PER_MM; + let settings = &app.session.active().unwrap().doc.settings; + assert!(settings.bleed.iter().all(|b| (b - 5.0 * mm).abs() < 1e-6), "5 mm, not 5 picas: {:?}", settings.bleed); + assert!((settings.page_width - 210.0 * mm).abs() < 1e-6, "{}", settings.page_width); +} + +#[test] +fn document_setup_keeps_each_pages_margins_unless_they_are_edited() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3, "margins": 36})).unwrap(); + app.run("layout.marginsAndColumns", json!({"pages": [1], "margins": 90})).unwrap(); + let margins = + |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| p.margins.top).collect::>(); + // Only the page count changes: every page keeps its own margins. + crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); + setup_fields(&mut app, json!({"pages": "4"})); + confirm(&mut app).unwrap(); + assert_eq!(margins(&app), [36.0, 90.0, 36.0, 36.0]); + // Edited margins go to every page. + crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); + setup_fields(&mut app, json!({"marginTop": "1p0"})); + confirm(&mut app).unwrap(); + assert_eq!(margins(&app), [12.0; 4]); +} + +#[test] +fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() { + for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] { + let mut app = document_setup_app("points"); + setup_fields(&mut app, json!({key: value, "bleedInside": "9"})); + assert!(confirm(&mut app).is_err(), "{key}"); + assert!(app.ui.dialog.is_some(), "{key}: the dialog stays open"); + assert_eq!(app.session.active().unwrap().doc.settings.bleed, [0.0; 4], "{key}: nothing changed"); + } +} + +#[test] +fn document_setup_links_edges_and_adjust_layout_applies() { + let mut app = document_setup_app("points"); + let f = app.run("frame.create", json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap(); + crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 900.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + // Typing in a linked margin sets all four. + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let top = labels.iter().filter(|(t, _, _)| t == "36 pt").map(|(_, r, _)| *r).next().expect("the top margin"); + click_dialog(&mut app, &ctx, screen, top.center()); + let select_all = egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + dialog_frame(&mut app, &ctx, screen, vec![select_all, egui::Event::Text("72 pt".into())]); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(["Top", "Bottom", "Inside", "Outside"].iter().all(|e| d.s(&format!("margin{e}")) == "72 pt"), "linked: {:?}", d.fields); + // Adjust Layout applies at once, and the frame follows the margins. + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Adjust Layout").center()); + assert!(app.ui.dialog.is_none(), "applied"); + let doc = &app.session.active().unwrap().doc; + let b = doc.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds(); + assert!((b.y0 - 72.0).abs() < 1e-6 && doc.page(0).unwrap().margins.outside == 72.0, "{b:?}"); +} + +#[test] +fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap(); + let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + app.run("table.select", json!({"what": "table"})).unwrap(); + app.run("app.cellOptionsDialog", json!({})).unwrap(); + let ctx = dialog_context(""); + dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.id, "cellOptions"); + assert_eq!(d.fields["weight"], json!(1.0)); + d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"])); + d.fields.insert("gapColor".into(), json!("[Paper]")); + d.fields.insert("fill".into(), json!("[Black]")); + d.fields.insert("fillTint".into(), json!(0.2)); + confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap(); + let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone(); + assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges"); + assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs"); + assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6)); + assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied"); +} + +#[test] +fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap(); + let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + app.run("table.select", json!({"what": "table"})).unwrap(); + app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap(); + app.run("app.cellOptionsDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + d.fields.insert("seed".into(), json!(5)); + let outer = [true, true, true, true, false, false]; + cell_options_edges_changed(&mut app, &mut d, &outer); + assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0))); + // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen + // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it. + d.fields.insert("weight".into(), json!(5.0)); + cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]); + assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0))); + d.fields.insert("weight".into(), json!(1.0)); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap(); + assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]); +} + +#[test] +fn preferences_ok_saves_a_story_editor_size_that_loads_back() { + // `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`. + let sizes = [(json!("nan"), 20.0), (json!("inf"), 20.0), (json!(null), 20.0), (json!(1e39), 36.0), (json!(3), 8.0), (json!(11), 11.0)]; + for (size, want) in sizes { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.ui.story_editor_size = 20.0; + app.run("app.preferences", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("storyEditorSize".into(), size); + confirm(&mut app).unwrap(); + let saved = serde_json::to_vec(&app.ui).unwrap(); + assert_eq!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_size, want); + } +} + +#[test] +fn preferences_ok_sets_only_the_ruler_units_it_is_given() { + // `ui.dialog.open` takes any fields, so the vertical units can be missing. + for (vertical, want) in [(None, "inches"), (Some("points"), "points")] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("document.preferences", json!({"verticalUnits": "inches"})).unwrap(); + let mut fields = json!({"horizontalUnits": "millimeters", "bg.relativeTo": "topOfPage"}); + if let Some(vertical) = vertical { + fields["verticalUnits"] = json!(vertical); + } + app.ui.dialog = Some(Dialog::new("preferences", fields)); + confirm(&mut app).unwrap(); + let units = app.run("document.preferences", json!({})).unwrap(); + assert_eq!((units["horizontalUnits"].as_str(), units["verticalUnits"].as_str()), (Some("millimeters"), Some(want))); + } +} + +#[test] +fn enter_and_escape_close_the_style_menu_not_numbering_and_section_options() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 2})).unwrap(); + crate::menus::activate(&mut app, "layout.section", &Value::Null); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for pressed in [egui::Key::Enter, egui::Key::Escape] { + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + // The section's Style menu (the first of the two). + let style = labels.iter().filter(|(t, r, c)| t.trim() == "1, 2, 3, 4…" && c.contains_rect(*r)).map(|(_, r, _)| *r).next().unwrap(); + click_dialog(&mut app, &ctx, screen, style.center()); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(egui::Popup::is_any_open(&ctx), "the Style menu opened"); + dialog_frame(&mut app, &ctx, screen, vec![key(pressed)]); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(app.ui.dialog.is_some(), "{pressed:?} with the menu open leaves the dialog open"); + assert!(app.session.active().unwrap().doc.sections.iter().all(|s| s.start_number != Some(0))); + if egui::Popup::is_any_open(&ctx) { + egui::Popup::close_all(&ctx); + dialog_frame(&mut app, &ctx, screen, vec![]); + } + } + // With no menu open, Escape closes the dialog. + dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Escape)]); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn numbering_and_section_options_keep_their_actions_in_view() { + for language in ["en", "ar"] { + for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.language = language.into(); + app.run("file.new", json!({"pages": 2})).unwrap(); + crate::menus::activate(&mut app, "layout.section", &Value::Null); + let ctx = dialog_context(language); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let tr = |s| crate::i18n::tr(language, s); + for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] { + visible_label(&labels, screen, expected); + } + if size.x > 1000.0 { + // Every option fits without scrolling, and choosing one then OK applies it. + visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A"))); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center()); + assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog"); + let doc = &app.session.active().unwrap().doc; + assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically"); + } + } + } +} + +fn select_all_key() -> egui::Event { + egui::Event::Key { + key: egui::Key::A, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() }, + } +} + +/// The Color Picker over a new document's selected frame, a few frames in. +fn picker(fields: Value) -> (DesignApp, egui::Context, egui::Rect, u64) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + app.ui.dialog = Some(Dialog::new("colorPicker", fields)); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 500.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + (app, ctx, screen, id) +} + +/// The rightmost painted `text`: the picker's own field, right of egui's colour editor (which +/// has R/G/B fields of its own). +fn rightmost(labels: &[(String, egui::Rect, egui::Rect)], text: &str) -> egui::Pos2 { + labels + .iter() + .filter(|(t, _, _)| t.trim() == text) + .map(|(_, r, _)| r.center()) + .max_by(|a, b| a.x.total_cmp(&b.x)) + .unwrap_or_else(|| panic!("{text} is painted")) +} + +/// Types `text` one character per frame, with an idle frame after each. +fn type_slowly(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, text: &str) { + for ch in text.chars() { + dialog_frame(app, ctx, screen, vec![egui::Event::Text(ch.into())]); + dialog_frame(app, ctx, screen, vec![]); + } +} + +fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color { + let d = &app.session.active().unwrap().doc; + d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap() +} + +#[test] +fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() { + let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ffffff"})); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "ffffff").center()); + dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); + type_slowly(&mut app, &ctx, screen, "#f5"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f5", "#ffffff"), "half-typed text stays; the colour waits"); + type_slowly(&mut app, &ctx, screen, "9019"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f59019", "#f59019"), "a 7-character #rrggbb commits"); + // Invalid text is replaced by the colour when focus leaves. + dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); + type_slowly(&mut app, &ctx, screen, "zz"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#").center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "f59019"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019"); +} + +#[test] +fn typed_channel_values_are_kept_while_typing() { + let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]})); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, rightmost(&labels, "1")); + dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); + type_slowly(&mut app, &ctx, screen, "12.5"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(rightmost(&labels, "12.5").x > rightmost(&labels, "2").x - 1.0, "the typed text stays in the R field"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203"); + confirm(&mut app).unwrap(); + let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") }; + assert!((r - 12.5 / 255.0).abs() < 1e-6, "{r}"); +} + +#[test] +fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() { + let cmyk = json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]}); + // Picked by hex: converted to CMYK. + let (mut app, ctx, screen, id) = picker(cmyk.clone()); + let hex = app.ui.dialog.as_ref().unwrap().s("hex"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, hex.trim_start_matches('#')).center()); + dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); + type_slowly(&mut app, &ctx, screen, "3366cc"); + confirm(&mut app).unwrap(); + assert!(matches!(fill(&app, id), designcraft_color::Color::Cmyk { .. }), "{:?}", fill(&app, id)); + // A typed C/M/Y/K percent is a percent: M 1 is 1 %. + let (mut app, ctx, screen, id) = picker(cmyk.clone()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, rightmost(&labels, "50")); + dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); + type_slowly(&mut app, &ctx, screen, "1"); + confirm(&mut app).unwrap(); + let designcraft_color::Color::Cmyk { c, m, y, k } = fill(&app, id) else { panic!("not CMYK") }; + assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}"); + // Typed R/G/B values: RGB. + let (mut app, ctx, screen, id) = picker(cmyk); + let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap(); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, rightmost(&labels, &r.to_string())); + dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); + type_slowly(&mut app, &ctx, screen, "10"); + confirm(&mut app).unwrap(); + assert!(matches!(fill(&app, id), designcraft_color::Color::Rgb { .. }), "{:?}", fill(&app, id)); +} + +#[test] +fn ok_without_edits_leaves_the_fill_alone() { + let (mut app, _, _, id) = picker(json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]})); + let before = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.clone(); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill, before); +} + +#[test] +fn dialogs_do_not_dim_the_page() { + let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ff8000"})); + let time = ctx.input(|i| i.time) + 1.0 / 60.0; + let output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(&mut app, ui.ctx())); + fn covers(shape: &egui::Shape, screen: egui::Rect) -> bool { + match shape { + egui::Shape::Rect(r) => r.rect.contains_rect(screen) && r.fill.a() > 0, + egui::Shape::Vec(v) => v.iter().any(|s| covers(s, screen)), + _ => false, + } + } + assert!(app.ui.dialog.is_some()); + assert!(!output.shapes.iter().any(|s| covers(&s.shape, screen)), "nothing paints over the whole window"); +} + +fn draw(app: &mut DesignApp, ctx: &egui::Context) { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); +} + +/// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled". +fn ruled_paragraph() -> (DesignApp, Value) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0}); + app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap(); + let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap(); + (app, rule) +} + +fn undo_steps(app: &DesignApp) -> usize { + app.session.doc().map_or(0, |st| st.history.undo.len()) +} + +#[test] +fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() { + let (mut app, rule) = ruled_paragraph(); + let ctx = egui::Context::default(); + app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap(); + draw(&mut app, &ctx); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(d.id, "paragraphRules"); + let current = d.fields["current"].clone(); + assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule"); + assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false); + // Pick a colour, as the Color menu does. + app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]")); + draw(&mut app, &ctx); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + let mut want = rule.clone(); + want["color"] = json!("[Registration]"); + assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule); +} + +#[test] +fn paragraph_style_options_edit_one_rule_field() { + let (mut app, rule) = ruled_paragraph(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); + draw(&mut app, &ctx); + let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style"); + app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5)); + draw(&mut app, &ctx); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + let mut want = rule.clone(); + want["weight"] = json!(1.5); + assert_eq!(resolved(&app)["ruleBelow"], want); + assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(resolved(&app)["ruleBelow"], rule); +} + +/// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and +/// clicks OK; returns the resolved attributes of the paragraph styled with it. +fn style_section_edit(sections: &[&str], fields: Value) -> Value { + let (mut app, _) = ruled_paragraph(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"}))); + for section in sections { + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section)); + draw(&mut app, &ctx); + } + for (k, v) in fields.as_object().unwrap() { + app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone()); + } + draw(&mut app, &ctx); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); + let own = serde_json::to_value(&style.para).unwrap(); + for (k, v) in fields.as_object().unwrap() { + assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}"); + } + app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone() +} + +#[test] +fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() { + let para = style_section_edit( + &["keep", "border"], + json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3, + "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}), + ); + assert_eq!(para["keepWithNext"], 2); + assert_eq!(para["keepLinesTogether"], true); + assert_eq!(para["keepAllLines"], false); + assert_eq!(para["keepFirst"], 3); + assert_eq!(para["startParagraph"], "nextPage"); + assert_eq!(para["borderOn"], true); + assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0])); + // Fields not edited keep the resolved value. + assert_eq!(para["keepLast"], 2); + assert_eq!(para["ruleBelow"]["weight"], 3.0); +} + +#[test] +fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() { + let para = style_section_edit( + &["bullets", "span"], + json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3, + "p.spanColumns": {"kind": "split", "columns": 3}}), + ); + assert_eq!(para["listType"], "numbers"); + assert_eq!(para["numberStyle"], "upperRoman"); + assert_eq!(para["numberExpression"], "^#)^t"); + assert_eq!(para["startAt"], 3); + assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3})); + let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap(); + assert_eq!(props.number_label(3), "III)\t"); +} + +#[test] +fn paragraph_style_options_ignore_optical_margin_is_set_on_ok() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Flush"})).unwrap(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Flush", "section": "indents"}))); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("ignore_optical_margin_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + h.get_by_label("Ignore Optical Margin").click(); + h.run_steps(3); + h.get_by_label(" OK ").click(); + h.run_steps(3); + let app = h.state(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.styles.para("Flush").unwrap().para.ignore_optical_margin, Some(true)); +} + +#[test] +fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() { + let (mut app, _) = ruled_paragraph(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"}))); + draw(&mut app, &ctx); + app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}])); + let e = confirm(&mut app).unwrap_err(); + assert!(e.contains("bad GREP"), "{e}"); + let d = app.ui.dialog.clone().expect("the dialog stays open"); + assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true)); + assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved"); + draw(&mut app, &ctx); +} + +#[test] +fn paragraph_style_options_show_a_refused_rename_on_general_and_trim_a_new_name() { + let (mut app, _) = ruled_paragraph(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "rules"}))); + draw(&mut app, &ctx); + app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!("Ruled Child")); + let e = confirm(&mut app).unwrap_err(); + let d = app.ui.dialog.clone().expect("the dialog stays open"); + assert_eq!(d.s("section"), "general", "the name field is on General"); + assert!(d.s("status").contains("already exists"), "{e}"); + + app.ui.dialog.as_mut().unwrap().fields.insert("rename".into(), json!(" Fresh ")); + app.ui.dialog.as_mut().unwrap().fields.insert("x.tag".into(), json!("h3")); + confirm(&mut app).unwrap(); + let st = &app.session.doc().unwrap().doc.styles; + assert!(st.para("Fresh").is_some()); + assert_eq!(st.export_tag("Fresh", false).map(|t| t.tag.as_str()), Some("h3")); +} + +/// A frame with two paragraphs of [Basic Paragraph]; the first has a local Word Spacing minimum. +fn two_paragraphs() -> (DesignApp, Value) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One\nTwo"})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("type.para", json!({"attrs": {"wordSpaceMin": 0.7}})).unwrap(); + (app, r["story"].clone()) +} + +/// The resolved paragraph attribute `key` of the paragraph at byte `at`. +fn para_attr(app: &mut DesignApp, story: &Value, at: usize, key: &str) -> Value { + app.run("text.select", json!({"story": story, "anchor": at, "focus": at})).unwrap(); + app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone() +} + +/// The hyphenation video (Graphd Tutorials, 0:39–1:13): the Paragraph panel menu's +/// Hyphenation… opens InDesign's Hyphenation Settings for the selected paragraphs. Preview +/// shows the slider moved to Fewer Hyphens on the page without an undo step, OK makes it one +/// step on the selected paragraph only, and Cancel puts it back. +#[test] +fn hyphenation_settings_preview_apply_and_cancel_on_the_selected_paragraph() { + let (mut app, story) = two_paragraphs(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + let sid = designcraft_doc::StoryId(story.as_u64().unwrap()); + let weight = |app: &DesignApp, para: usize| { + let d = &app.session.doc().unwrap().doc; + d.styles.resolve_para(&d.story(sid).unwrap().paras[para]).0.hyph_weight + }; + assert!(crate::menus::menu_enabled(&app, "app.hyphenationDialog")); + app.run("app.hyphenationDialog", json!({})).unwrap(); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!( + (d.id.as_str(), d.fields["current"]["hyphWeight"].as_f64(), d.fields["current"]["hyphenate"].as_bool()), + ("hyphenation", Some(0.5), Some(true)) + ); + for label in [ + "Hyphenation Settings", + "Hyphenate", + "Words with at Least:", + "letters", + "Hyphen Limit:", + "hyphens", + "Hyphenation Zone:", + "Better Spacing", + "Fewer Hyphens", + "Hyphenate Capitalized Words", + "Hyphenate Last Word", + "Hyphenate Across Column", + "Preview", + ] { + assert!(labels.iter().any(|(t, _, _)| t == label), "{label}: {labels:?}"); + } + // Fewer Hyphens (9 of 10) with Preview: on the page, no undo step. + let before = undo_steps(&app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("hyphWeight".into(), json!(0.9)); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(weight(&app, 0), 0.9, "previewed"); + assert_eq!(undo_steps(&app), before, "a preview is no step"); + // Cancel: back as it was. + cancel(&mut app); + assert_eq!(weight(&app, 0), 0.5); + // Again, and OK: one step, the selected paragraph only. + app.run("app.hyphenationDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("hyphWeight".into(), json!(0.9)); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + confirm(&mut app).unwrap(); + assert_eq!((weight(&app, 0), weight(&app, 1)), (0.9, 0.5)); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + // Paragraph Style Options › Hyphenation has the same form. + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": "hyph"}))); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for label in ["Hyphenation Zone:", "Better Spacing", "Fewer Hyphens", "Hyphenate Last Word", "Hyphenate Across Column"] { + assert!(labels.iter().any(|(t, _, _)| t == label), "style options: {label}"); + } + app.ui.dialog = None; + app.run("edit.deselectAll", json!({})).unwrap(); + assert!(!crate::menus::menu_enabled(&app, "app.hyphenationDialog"), "no paragraph"); +} + +/// Hyphenate differs across the selection: it shows mixed, and the first click turns it on for +/// all. Settings the command refuses show why: a preview goes back and isn't retried until they +/// change, and OK keeps the dialog open. +/// A mixed Better Spacing ↔ Fewer Hyphens slider: a click on its middle step sets every +/// selected paragraph to it, though the knob already sat there. +#[test] +fn hyphenation_settings_mixed_slider_click_sets_the_step() { + let (mut app, story) = two_paragraphs(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + app.run("type.para", json!({"attrs": {"hyphWeight": 0.2}})).unwrap(); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.hyphenationDialog", json!({})).unwrap(); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let rect = |l: &str| labels.iter().find(|(t, _, _)| t == l).map(|(_, r, _)| *r).unwrap(); + let (better, fewer) = (rect("Better Spacing"), rect("Fewer Hyphens")); + click_dialog(&mut app, &ctx, screen, egui::pos2((better.right() + fewer.left()) / 2.0, better.center().y)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphWeight"), Some(&json!(0.5))); +} + +#[test] +fn hyphenation_settings_mixed_checkbox_and_refused_settings() { + let (mut app, story) = two_paragraphs(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + app.run("type.para", json!({"attrs": {"hyphenate": false}})).unwrap(); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.hyphenationDialog", json!({})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields["current"]["hyphenate"].is_null(), "mixed"); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let at = labels.iter().find(|(t, _, _)| t == "Hyphenate").map(|(_, r, _)| r.left_center() - egui::vec2(10.0, 0.0)).unwrap(); + click_dialog(&mut app, &ctx, screen, at); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("hyphenate"), Some(&json!(true)), "the first click turns it on"); + // A refused setting (as a control-channel caller could send it): no preview, the reason. + let before = undo_steps(&app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("hyphWeight".into(), json!("heavy")); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key(PREVIEWED) && d.fields.contains_key("status"), "{:?}", d.fields); + assert!(app.session.doc().unwrap().interaction.is_none(), "the preview went back"); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(app.session.doc().unwrap().interaction.is_none(), "not tried again"); + // OK with it: an error, and the dialog stays open with the reason. + assert!(confirm(&mut app).is_err()); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert!(d.fields.contains_key("status")); + assert_eq!(undo_steps(&app), before); + // Corrected, it previews and applies. + app.ui.dialog.as_mut().unwrap().fields.insert("hyphWeight".into(), json!(0.9)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("status")); + confirm(&mut app).unwrap(); + assert_eq!(para_attr(&mut app, &story, 0, "hyphenate"), true); + assert_eq!(para_attr(&mut app, &story, 4, "hyphWeight"), 0.9); +} + +#[test] +fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() { + let (mut app, story) = two_paragraphs(); + let ctx = egui::Context::default(); + assert!(crate::menus::menu_enabled(&app, "app.justificationDialog")); + app.run("app.justificationDialog", json!({})).unwrap(); + draw(&mut app, &ctx); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(d.id, "justification"); + assert_eq!(d.fields["current"]["wordSpaceMin"], 0.7); + assert_eq!(d.fields["current"]["wordSpaceDesired"], 1.0); + app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.1)); + draw(&mut app, &ctx); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1); + assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceMin"), 0.7, "unedited fields stay"); + assert_eq!(para_attr(&mut app, &story, 4, "wordSpaceDesired"), 1.0, "only the selected paragraph"); + let style = app.session.doc().unwrap().doc.styles.resolve_para_style(designcraft_doc::story::BASIC_PARAGRAPH).0.word_space_desired; + assert_eq!(style, 1.0, "the paragraph style keeps its value"); + + // Cancel (Escape) leaves the paragraph alone. + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + app.run("app.justificationDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.2)); + let before = undo_steps(&app); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events: vec![escape], + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + assert!(app.ui.dialog.is_none(), "cancelled"); + assert_eq!(undo_steps(&app), before); + assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1); + + app.run("edit.deselectAll", json!({})).unwrap(); + assert!(!crate::menus::menu_enabled(&app, "app.justificationDialog"), "nothing to justify"); + assert!(app.run("app.justificationDialog", json!({})).is_err()); +} + +#[test] +fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() { + let (mut app, story) = two_paragraphs(); + let ctx = egui::Context::default(); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.justificationDialog", json!({})).unwrap(); + draw(&mut app, &ctx); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(d.fields["current"]["wordSpaceMin"], Value::Null, "mixed shows empty"); + assert_eq!(d.fields["current"]["wordSpaceMax"], 1.33); + + // Out of range, and minimum above desired: an error, the dialog stays open, nothing changes. + let before = undo_steps(&app); + for (key, v) in [("wordSpaceMax", 20.0), ("glyphScaleMin", 0.2), ("letterSpaceDesired", f64::NAN)] { + app.ui.dialog = Some(d.clone()); + app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(v)); + assert!(confirm(&mut app).is_err(), "{key} = {v}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why"); + } + app.ui.dialog = Some(d.clone()); + app.ui.dialog.as_mut().unwrap().fields.insert("letterSpaceMin".into(), json!(0.1)); + assert!(confirm(&mut app).is_err(), "letter spacing minimum above desired"); + draw(&mut app, &ctx); + assert_eq!(undo_steps(&app), before); + + app.ui.dialog = Some(d); + app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceMax".into(), json!(1.5)); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1); + for (at, min) in [(0, 0.7), (4, 0.8)] { + assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMax"), 1.5); + assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMin"), min, "each paragraph keeps its own minimum"); + } +} + +fn command_app(id: &str, fields: Value) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields)); + app +} + +#[test] +fn generic_new_document_preserves_typed_values_and_text_entry() { + for pages in [json!(2), json!(" 2 ")] { + let mut app = command_app( + "file.new", + json!({ + "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0, + "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40}, + "title": " ", "status": "internal", "primaryTextFrame": true + }), + ); + confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.page_count(), 2); + assert!(!doc.settings.facing_pages); + assert!(doc.title.starts_with("Untitled-")); + for page in doc.spreads.iter().flat_map(|s| &s.pages) { + assert!((page.width - 595.2755905511812).abs() < 0.01); + assert!((page.height - 841.8897637795277).abs() < 0.01); + assert_eq!(page.columns.gutter, 0.0); + assert_eq!(page.margins.top, 10.0); + assert_eq!(page.margins.outside, 40.0); + } + // `primaryTextFrame` is documented since #776, so the dialog passes it on (`status` isn't). + assert!(doc.spreads.iter().any(|s| !s.items.is_empty()), "documented fields reach the command"); + assert!(app.ui.dialog.is_none()); + } +} + +#[test] +fn numbering_commands_document_their_fields() { + let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::>(); + assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]); + assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]); +} + +#[test] +fn generic_command_preserves_array_geometry() { + let mut app = command_app("file.new", json!({})); + confirm(&mut app).unwrap(); + app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]}))); + confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap(); + assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0)); +} + +#[test] +fn generic_explicit_null_uses_the_commands_existing_semantics() { + // file.new accepts null width by using the selected preset's width. + for width in [Value::Null, json!("null")] { + let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "})); + confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.title, "Sample layout"); + assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01); + } +} + +#[test] +fn generic_invalid_number_retains_dialog_without_creating_document() { + let mut app = command_app("file.new", json!({"width": 0})); + assert!(confirm(&mut app).is_err()); + assert!(app.session.active().is_none()); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.fields["width"], 0); + assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range")); +} + +#[test] +fn style_options_preview_choice_is_remembered_on_reopen() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name":"Tutorial","chars":{"size":10}})).unwrap(); + open_style_options(&mut app, true, "Tutorial"); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("style_preview_remember_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + h.get_by_label("Preview").click(); + h.run_steps(3); + cancel(h.state_mut()); + open_style_options(h.state_mut(), true, "Tutorial"); + assert!(h.state().ui.dialog.as_ref().unwrap().b("preview"), "Preview stays checked on reopen"); +} + +#[test] +fn style_options_preview_updates_all_uses_cancels_and_commits_once() { + use egui_kittest::{Harness, kittest::Queryable}; + for paragraph in [true, false] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect":[36,36,300,300],"content":"text","text":"First\nSecond"})).unwrap(); + app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":12})).unwrap(); + let kind = if paragraph { "paragraph" } else { "character" }; + app.run(&format!("style.{kind}.create"), json!({"name":"Tutorial","chars":{"size":10}})).unwrap(); + app.run(&format!("style.{kind}.apply"), json!({"name":"Tutorial"})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let journal = app.session.journal.len(); + open_style_options(&mut app, paragraph, "Tutorial"); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("style_preview_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + h.get_by_label("Preview").click(); + h.run_steps(3); + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(18)); + h.run_steps(3); + let app = h.state_mut(); + assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 18.0); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert_eq!(app.session.journal.len(), journal); + // Repeated previews replace each other, never accumulate undo entries. + app.ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(20)); + h.run_steps(3); + assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 20.0); + h.get_by_label("Preview").click(); + h.run_steps(3); + assert_eq!(h.state().session.doc().unwrap().doc, before); + h.get_by_label("Preview").click(); + h.run_steps(3); + cancel(h.state_mut()); + assert_eq!(h.state().session.doc().unwrap().doc, before); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + open_style_options(h.state_mut(), paragraph, "Tutorial"); + let d = h.state_mut().ui.dialog.as_mut().unwrap(); + d.fields.insert("preview".into(), json!(true)); + d.fields.insert("c.size".into(), json!(24)); + h.run_steps(3); + confirm(h.state_mut()).unwrap(); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); + // Both paragraphs/character runs still use the globally edited definition. + for pos in [0, 6] { + h.state_mut().run("text.select", json!({"story":f["story"],"anchor":pos,"focus":pos+1})).unwrap(); + assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 24.0); + } + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(h.state().session.doc().unwrap().doc, before); + } +} + +#[test] +fn style_preview_refuses_justification_spacing_ok_would_refuse() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let mut d = Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, "p.wordSpaceDesired": 1.1})); + style_options_preview(&mut app, &mut d); + assert_ne!(app.session.doc().unwrap().doc, before, "a valid value previews"); + // Minimum above Desired: the page goes back and the dialog says why. + d.fields.insert("p.wordSpaceMin".into(), json!(1.5)); + style_options_preview(&mut app, &mut d); + assert_eq!(app.session.doc().unwrap().doc, before); + assert!(d.s("status").contains("Word Spacing"), "{:?}", d.fields.get("status")); + assert!(app.session.doc().unwrap().interaction.is_none()); +} + +#[test] +fn invalid_style_preview_leaves_the_starting_document_and_can_be_cancelled() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.character.create", json!({"name":"Emphasis"})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let mut d = Dialog::new("characterStyleOptions", json!({"name":"Emphasis","preview":true,"basedOn":"Emphasis"})); + style_options_preview(&mut app, &mut d); + assert!(d.fields.contains_key("status")); + assert_eq!(app.session.doc().unwrap().doc, before); + app.ui.dialog = Some(d); + cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert!(app.session.doc().unwrap().interaction.is_none()); +} + +#[test] +fn style_preview_rejects_conflicting_scalar_and_nested_rule_fields_without_panicking() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let mut dialog = Dialog::new( + "paragraphStyleOptions", + json!({ + "name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, + "p.ruleAbove": false, "p.ruleAbove.weight": 2 + }), + ); + style_options_preview(&mut app, &mut dialog); + assert!(dialog.fields.contains_key("status")); + assert_eq!(app.session.doc().unwrap().doc, before); + app.ui.dialog = Some(dialog); + cancel(&mut app); + assert!(app.session.doc().unwrap().interaction.is_none()); +} + +#[test] +fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + // A 300 pt frame, 2 columns, 12 pt gutter (picas in the dialog). + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); + let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); + app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "gutter": 12})).unwrap(); + let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + // Fixed Number shows each column's width: (300 - 12) / 2 = 144 pt. + assert_eq!((d.s("columnsKind"), d.s("columnWidth"), d.s("firstBaseline")), ("fixedNumber".into(), "12p0".into(), "ascent".into())); + for (k, v) in [ + ("columnsKind", json!("fixedWidth")), + ("columnWidth", json!("10p0")), + ("firstBaseline", json!("capHeight")), + ("firstBaselineMin", json!("0p6")), + ("balanceColumns", json!(true)), + ("ignoreWrap", json!(true)), + ] { + d.fields.insert(k.into(), v); + } + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + let o = opts(&app); + assert_eq!(o.columns_kind, designcraft_doc::ColumnsKind::FixedWidth); + assert_eq!((o.column_width, o.first_baseline_min, o.columns), (120.0, 6.0, 2)); + assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight); + assert!(o.balance_columns && o.ignore_wrap); + // Fixed Number again: the width isn't sent. + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert_eq!(d.s("columnWidth"), "10p0", "Fixed Width shows its own width"); + d.fields.insert("columnsKind".into(), json!("fixedNumber")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0)); +} + +#[test] +fn baseline_grid_increment_error_explains_the_positive_measure_rule() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); + let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); + for increment in ["0", "-1 pt", "not a measure"] { + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("customGrid".into(), json!(true)); + d.fields.insert("gridIncrement".into(), json!(increment)); + app.ui.dialog = Some(d); + let error = confirm(&mut app).unwrap_err().to_string(); + assert!(error.contains("the baseline grid increment must be a measure greater than zero"), "{increment}: {error}"); + assert!(app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid.is_none()); + } +} + +#[test] +fn text_frame_options_set_a_custom_baseline_grid_relative_to() { + use designcraft_doc::{FrameBaselineGrid, FrameGridRelative}; + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); + let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); + let grid = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid; + let open = |app: &mut DesignApp, fields: &[(&str, Value)]| { + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + for (k, v) in fields { + d.fields.insert((*k).into(), v.clone()); + } + app.ui.dialog = Some(d); + confirm(app) + }; + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + // Turned on, the grid takes the shown start and increment (the document grid's: 3p0 and 1p0). + open(&mut app, &[("customGrid", json!(true)), ("gridRelativeTo", json!("frame"))]).unwrap(); + assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 36.0, increment: 12.0, relative_to: FrameGridRelative::TopOfFrame })); + // The dialog shows the frame's grid; changing Relative To keeps its start and increment. + open(&mut app, &[("gridStart", json!("0p10"))]).unwrap(); + open(&mut app, &[("gridRelativeTo", json!("inset"))]).unwrap(); + assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 10.0, increment: 12.0, relative_to: FrameGridRelative::TopInset })); + open(&mut app, &[("customGrid", json!(false))]).unwrap(); + assert_eq!(grid(&app), None); +} + +#[test] +fn text_frame_options_change_only_what_was_edited() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap(); + let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap()); + app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + let before = opts(&app); + let open = |app: &mut DesignApp, fields: &[(&str, Value)]| { + app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({}))); + let mut d = app.ui.dialog.take().unwrap(); + seed_text_frame_options(app, &mut d); + for (k, v) in fields { + d.fields.insert((*k).into(), v.clone()); + } + app.ui.dialog = Some(d); + confirm(app) + }; + // OK without edits changes nothing (no undo step either). + assert_eq!(open(&mut app, &[]).unwrap(), Value::Null); + assert_eq!(opts(&app), before); + // The rule's weight is in points; unequal insets the user didn't touch stay. + open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap(); + let o = opts(&app); + assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}"); + assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter)); + // One of the rule's insets edited: the other rule settings stay. + open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap(); + let o = opts(&app); + assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0)); + assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule); + // One inset side edited: the others keep their values. + open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap(); + assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]); + open(&mut app, &[("balanceColumns", json!(true))]).unwrap(); + let o = opts(&app); + assert!(o.balance_columns && o.column_rule && o.columns == 2, "{o:?}"); + // An unknown swatch is an error and the dialog stays open. + let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err(); + assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}"); + assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK); + // Each OK is one undo step. + for _ in 0..4 { + app.run("edit.undo", json!({})).unwrap(); + } + assert_eq!(opts(&app), before); +} + +#[test] +fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.newSample", json!({})).unwrap(); + crate::menus::activate(&mut app, "toc.generate", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(TOC)); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in + ["Table of Contents", "Title:", "Include Paragraph Styles:", "Other Styles:", "« Add", "Remove »", "Replace Existing Table of Contents"] + { + visible_label(&labels, screen, expected); + } + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Headline").center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "« Add").center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in ["Entry Style:", "TOC Level 1", "After Entry", "Between Entry and Number:", "Level:"] { + visible_label(&labels, screen, expected); + } + let undo = app.session.doc().unwrap().history.undo.len(); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center()); + assert!(app.ui.dialog.is_none()); + let d = &app.session.doc().unwrap().doc; + let toc = d.toc.clone().unwrap(); + assert_eq!(toc.entries, vec![designcraft_doc::TocEntry::new("Headline", 1)]); + let text = &d.story(toc.story).unwrap().text; + assert!(text.starts_with("Contents\n") && text.contains("\nNotes on the Grid\t"), "{text}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + // Reopened, the dialog shows the table of contents and replaces it. + crate::menus::activate(&mut app, "toc.generate", &Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.b("replace")); + assert_eq!(toc_rows(d).iter().map(|r| r.style.as_str()).collect::>(), ["Headline"]); +} + +#[test] +fn margins_and_columns_link_arithmetic_preview_and_one_undo_step() { + // Adobe's "Set up a modern magazine layout" (1:41–3:04): linked margins to 0.4375 in, then + // 5 columns with a 0.1875 in gutter, unlinked, and "*2" typed after the outside margin. + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"preset": "A4", "pages": 3, "facingPages": true, "margins": 36})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); + open_margins_and_columns(&mut app); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + let mut labels = vec![]; + for _ in 0..3 { + labels = dialog_frame(&mut app, &ctx, screen, vec![]); + } + for expected in + ["Margins and Columns", "Margins", "Top:", "Bottom:", "Inside:", "Outside:", "Columns", "Number:", "Gutter:", "Adjust Layout", "Preview"] + { + visible_label(&labels, screen, expected); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.b("link"), "four equal margins open linked"); + // Linked: one margin typed is all four. + app.ui.dialog.as_mut().unwrap().fields.insert("marginTop".into(), json!("0.4375 in")); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(MARGIN_FIELDS.iter().all(|(k, _, _)| d.s(k) == "0.4375 in"), "{:?}", d.fields); + // Preview: the page changes, with no undo step. + let undo = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let top = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].margins.top; + assert!((top(&app) - 31.5).abs() < 1e-6, "previewed: {}", top(&app)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + // Unlinked (the link button), the outside margin alone: "*2" typed after it is worked out + // when the field is left. + app.ui.dialog.as_mut().unwrap().fields.insert("link".into(), json!(false)); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let field = labels + .iter() + .filter(|(t, _, _)| t.trim() == "0.4375 in") + .map(|(_, r, _)| *r) + .max_by(|a, b| (a.max.x + a.max.y).total_cmp(&(b.max.x + b.max.y))) + .unwrap(); + click_dialog(&mut app, &ctx, screen, field.center()); + dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::End), egui::Event::Text("*2".into())]); + dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Tab)]); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert!( + !d.s("marginOutside").contains('*') && (d.m("marginOutside").unwrap() - 63.0).abs() < 1e-6, + "worked out on leaving the field: {}", + d.s("marginOutside") + ); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("link".into(), json!(false)); + for (k, v) in [("marginOutside", "0.4375 in*2"), ("columns", "5"), ("gutter", "0.1875 in"), ("target", "all")] { + d.fields.insert(k.into(), json!(v)); + } + dialog_frame(&mut app, &ctx, screen, vec![]); + confirm(&mut app).unwrap(); + let pg = app.session.doc().unwrap().doc.spreads[1].pages[0].clone(); + assert_eq!((pg.margins.top, pg.margins.outside, pg.columns.count), (31.5, 63.0, 5)); + assert!((pg.columns.gutter - 13.5).abs() < 1e-6); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + // Cancel after a preview puts the page back. + open_margins_and_columns(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("preview".into(), json!(true)); + d.fields.insert("columns".into(), json!("2")); + dialog_frame(&mut app, &ctx, screen, vec![]); + cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc.spreads[1].pages[0].columns.count, 5); +} + +#[test] +fn create_guides_reads_like_indesigns_and_previews() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 1, "facingPages": false})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); + open_create_guides(&mut app); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + let mut labels = vec![]; + for _ in 0..3 { + labels = dialog_frame(&mut app, &ctx, screen, vec![]); + } + for expected in ["Create Guides", "Rows", "Columns", "Options", "Fit Guides to:", "Margins", "Page", "Remove Existing Ruler Guides", "Preview"] { + visible_label(&labels, screen, expected); + } + // Rows and Columns side by side. + let (r, c) = (visible_label(&labels, screen, "Rows"), visible_label(&labels, screen, "Columns")); + assert!((r.center().y - c.center().y).abs() < 2.0 && r.center().x < c.center().x); + // Thirds, single guides, fitted to the page: clicking the Page radio. + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Page").center()); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.s("fitTo"), "page"); + d.fields.insert("rows".into(), json!("3")); + d.fields.insert("rowGutter".into(), json!("0")); + d.fields.insert("preview".into(), json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let guides = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].pages[0].guides.len(); + assert_eq!(guides(&app), 2, "previewed"); + confirm(&mut app).unwrap(); + assert_eq!(guides(&app), 2, "made once"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(guides(&app), 0, "one undo step"); +} + +fn dialog_context(language: &str) -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, language); + crate::theme::apply(&ctx, &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default())); + ctx +} + +fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, events: Vec) -> Vec<(String, egui::Rect, egui::Rect)> { + let time = ctx.input(|i| i.time) + 1.0 / 60.0; + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| { + show(app, ui.ctx()); + }); + output.textures_delta.clear(); + fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) { + match shape { + egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)), + egui::Shape::Vec(shapes) => { + for s in shapes { + collect(s, clip, labels); + } + } + _ => {} + } + } + let mut labels = Vec::new(); + for shape in output.shapes { + collect(&shape.shape, shape.clip_rect, &mut labels); + } + labels +} + +fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect { + let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted")); + assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}"); + assert!(clip.contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}"); + *rect +} + +fn click_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2) { + for pressed in [true, false] { + dialog_frame( + app, + ctx, + screen, + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } +} + +fn scroll_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2, delta: egui::Vec2) { + dialog_frame( + app, + ctx, + screen, + vec![ + egui::Event::PointerMoved(pos), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta, + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }, + ], + ); + // Let smooth wheel scrolling and scrollbar visibility settle before clicking. + for _ in 0..30 { + dialog_frame(app, ctx, screen, vec![]); + } +} + +fn scope_control(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (request, _reply) = crate::control::ControlRequest::new(method, params); + let crate::control::Outcome::Done(value) = crate::control::handle(app, ctx, &request) else { panic!("ordinary control response") }; + assert_eq!(value["ok"], true, "{value}"); + value["result"].clone() +} + +fn scope_click(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, label: &str) { + let labels = dialog_frame(app, ctx, screen, vec![]); + let pos = visible_label(&labels, screen, label).center(); + click_dialog(app, ctx, screen, pos); +} + +fn scope_dialog() -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) { + scope_dialog_with_selection("red red | red", 7) +} + +fn scope_dialog_with_selection(text: &str, end: usize) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) { + scope_dialog_with_tool(text, end, None) +} + +fn scope_dialog_with_tool(text: &str, end: usize, tool: Option<&str>) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.language = "en".into(); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap(); + let sid = designcraft_engine::doc::StoryId(frame["story"].as_u64().unwrap()); + let ctx = dialog_context("en"); + if let Some(tool) = tool { + scope_control(&mut app, &ctx, "ui.tool.select", json!({"tool": tool})); + } + app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": end})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + for (field, value) in [("find", "red"), ("change", "unused")] { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); + } + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + scope_click(&mut app, &ctx, screen, "document"); + scope_click(&mut app, &ctx, screen, "selection"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection"); + (app, ctx, screen, sid) +} + +fn scope_selected(app: &DesignApp, sid: designcraft_engine::doc::StoryId, a: usize, b: usize) { + let t = app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((t.story, t.range(), t.cell), (sid, a..b, None)); +} + +fn scope_state_unchanged(app: &DesignApp, before: &designcraft_engine::DocState) { + let after = app.session.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc)); + assert_eq!(after.uid, before.uid); + assert_eq!(after.revision, before.revision); + assert_eq!(after.selection, before.selection); + assert_eq!(after.history.limit, before.history.limit); + for (actual, expected) in [(&after.history.undo, &before.history.undo), (&after.history.redo, &before.history.redo)] { + assert_eq!(actual.len(), expected.len()); + for (a, b) in actual.iter().zip(expected) { + assert_eq!(a.label, b.label); + assert_eq!(a.selection, b.selection); + assert!(std::sync::Arc::ptr_eq(&a.doc, &b.doc)); + } + } +} + +#[test] +fn find_scope_dialog_control_effective_noops_retain_bounds() { + for (field, value) in [("objectMode", json!(false)), ("story", Value::Null)] { + let (mut app, ctx, screen, sid) = scope_dialog(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(field)); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().clone(); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], value); + scope_state_unchanged(&app, &before); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 4, 7); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); + } +} + +#[test] +fn find_scope_dialog_explicit_story_ignored_scope_preserves_grep_cursor() { + for physical in [false, true] { + for (text, pattern, hits, changed) in [ + ("é", "é|(?:)", vec![(0, 2)], "X"), + ("é🙂", "é|(?:)", vec![(0, 2), (6, 6)], "X🙂X"), + ("é🙂", "(?:)", vec![(0, 0), (2, 2), (6, 6)], "XéX🙂X"), + ] { + let (mut app, ctx, screen, sid) = scope_dialog_with_selection(text, 0); + for (field, value) in [("find", json!(pattern)), ("change", json!("X")), ("story", json!(sid.0))] { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); + } + scope_click(&mut app, &ctx, screen, "GREP"); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len())); + for &(a, b) in &hits { + scope_click(&mut app, &ctx, screen, "Find Next"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "Found"); + scope_selected(&app, sid, a, b); + let before = app.session.doc().unwrap().clone(); + let cur = app.ui.dialog.as_ref().unwrap().s("scope"); + let next = if cur == "selection" { "document" } else { "selection" }; + if physical { + scope_click(&mut app, &ctx, screen, &cur); + scope_click(&mut app, &ctx, screen, next); + } else { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next})); + } + assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), next); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["story"], json!(sid.0)); + scope_state_unchanged(&app, &before); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len())); + } + scope_click(&mut app, &ctx, screen, "Find Next"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches"); + // An ignored scope change must not revive an exhausted endpoint either. + let before = app.session.doc().unwrap().clone(); + let cur = app.ui.dialog.as_ref().unwrap().s("scope"); + let next = if cur == "selection" { "document" } else { "selection" }; + if physical { + scope_click(&mut app, &ctx, screen, &cur); + scope_click(&mut app, &ctx, screen, next); + } else { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next})); + } + scope_click(&mut app, &ctx, screen, "Find Next"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches"); + scope_state_unchanged(&app, &before); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} replacement(s) made", hits.len())); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, changed); + } + } +} + +#[test] +fn find_scope_dialog_explicit_story_transitions_reset_cursor() { + for remove_override in [false, true] { + let (mut app, ctx, screen, sid) = scope_dialog_with_selection("é🙂", 0); + let other = app.run("frame.create", json!({"rect": [180, 36, 100, 100], "content": "text", "text": "other"})).unwrap(); + app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + for (field, value) in [("find", json!("(?:)")), ("story", json!(sid.0))] { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); + } + scope_click(&mut app, &ctx, screen, "GREP"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 0); + let before = app.session.doc().unwrap().clone(); + let value = if remove_override { Value::Null } else { other["story"].clone() }; + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": value})); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0})); + scope_state_unchanged(&app, &before); + // Away and back still releases continuation even if no Find command intervenes. + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 0); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 2, 2); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "é🙂"); + let other_sid = designcraft_engine::doc::StoryId(other["story"].as_u64().unwrap()); + assert_eq!(app.session.doc().unwrap().doc.story(other_sid).unwrap().text, "other"); + } +} + +#[test] +fn find_scope_dialog_control_mode_changes_release_bounds() { + for object_mode in [false, true] { + let (mut app, ctx, _, sid) = scope_dialog(); + if object_mode { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": true})); + } + // Direct Session consumers share the retained domain even while Object is shown. + let p = json!({"find": "red", "change": "blue", "scope": "selection"}); + let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); + assert_eq!(count.as_array().unwrap().len(), 2); + scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.next", "params": p})); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().clone(); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": !object_mode})); + assert_eq!(app.ui.dialog.as_ref().unwrap().b("objectMode"), !object_mode); + scope_state_unchanged(&app, &before); + let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); + assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); + let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p})); + assert_eq!(changed, json!({"count": 1})); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); + } +} + +#[test] +fn find_scope_dialog_tool_replacement_releases_bounds() { + for (tool, replacement) in [("page", "cmd:layout.pageSize"), ("rectangleFrame", "frameSize")] { + let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool)); + assert_eq!(app.session.tool_id(), tool); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().clone(); + let active = (app.session.active_index(), app.session.documents().len()); + let off = app.session.layout().xf(designcraft_engine::doc::SpreadRef::Doc(0)).translation(); + let x = off.x + before.doc.spreads[0].pages[0].x + 200.0; + let y = off.y + 200.0; + // The Page tool opens Page Size on a double-click (a click selects the page). + let events = if tool == "page" { + json!([{"kind": "doubleclick", "x": x, "y": y}]) + } else { + json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]) + }; + // Real tool -> Action::Dialog -> after_engine; no injected UI request. + scope_control(&mut app, &ctx, "ui.pointer", json!({"events": events})); + assert_eq!(app.ui.dialog.as_ref().unwrap().id, replacement); + assert!(app.session.ui_requests.is_empty()); + assert_eq!((app.session.active_index(), app.session.documents().len()), active); + scope_state_unchanged(&app, &before); + scope_click(&mut app, &ctx, screen, "Cancel"); + assert!(app.ui.dialog.is_none()); + assert_eq!((app.session.active_index(), app.session.documents().len()), active); + scope_state_unchanged(&app, &before); + let p = json!({"find": "red", "change": "blue", "scope": "selection"}); + let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); + assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); + scope_state_unchanged(&app, &before); + let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p})); + assert_eq!(changed, json!({"count": 1})); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); + } +} + +#[test] +fn find_scope_dialog_tool_without_replacement_retains_bounds() { + for tool in ["page", "rectangleFrame"] { + let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool)); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().clone(); + let fields = app.ui.dialog.as_ref().unwrap().fields.clone(); + scope_control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "move", "x": 200, "y": 200}]})); + assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields); + scope_state_unchanged(&app, &before); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 4, 7); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn find_scope_dialog_native_pdf_replacement_releases_bounds() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("three.pdf"); + std::fs::write(&path, crate::browser_import_tests::pdf()).unwrap(); + for dismissal in ["Cancel", "Escape", "control"] { + let (mut app, ctx, screen, sid) = scope_dialog(); + let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen_pick = picked.clone(); + let seen_read = read.clone(); + let pick_path = path.to_string_lossy().to_string(); + let read_path = pick_path.clone(); + app.services.pick_open = Some(Box::new(move |purpose| { + assert_eq!(purpose, "place"); + seen_pick.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Some(pick_path.clone()) + })); + app.services.read = Some(Box::new(move |path| { + assert_eq!(path, read_path); + seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + std::fs::read(path).map_err(|e| e.to_string()) + })); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().clone(); + let active = (app.session.active_index(), app.session.documents().len()); + // Exercise engine.execute -> UiRequest::Pick -> native host PDF replacement. + scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}})); + assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.id, "pdfImport"); + assert_eq!(dialog.s("path"), path.to_string_lossy()); + assert_eq!(dialog.fields["pages"], 3); + assert_eq!(dialog.s("page"), "1"); + assert!(!dialog.b("async")); + assert_eq!(dialog.fields["target"], json!(before.uid)); + assert!(app.session.ui_requests.is_empty()); + assert!(app.pending_pdf.is_none()); + assert_eq!((app.session.active_index(), app.session.documents().len()), active); + scope_state_unchanged(&app, &before); + match dismissal { + "Cancel" => scope_click(&mut app, &ctx, screen, "Cancel"), + "Escape" => { + dialog_frame( + &mut app, + &ctx, + screen, + vec![egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }], + ); + } + "control" => { + scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({})); + } + _ => panic!("known dismissal"), + } + assert!(app.ui.dialog.is_none()); + assert!(app.pending_pdf.is_none()); + assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!((app.session.active_index(), app.session.documents().len()), active); + scope_state_unchanged(&app, &before); + let p = json!({"find": "red", "change": "blue", "scope": "selection"}); + let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p})); + assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); + scope_state_unchanged(&app, &before); + let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p})); + assert_eq!(changed, json!({"count": 1})); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn find_scope_dialog_native_picker_cancel_retains_bounds() { + let (mut app, ctx, screen, sid) = scope_dialog(); + let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = picked.clone(); + app.services.pick_open = Some(Box::new(move |purpose| { + assert_eq!(purpose, "place"); + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + None + })); + let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen_read = read.clone(); + app.services.read = Some(Box::new(move |_| { + seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Err("canceled picker must not read".into()) + })); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().clone(); + let active = (app.session.active_index(), app.session.documents().len()); + let fields = app.ui.dialog.as_ref().unwrap().fields.clone(); + scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}})); + assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields); + assert_eq!((app.session.active_index(), app.session.documents().len()), active); + scope_state_unchanged(&app, &before); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 4, 7); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1); +} + +#[test] +fn find_scope_dialog_exact_baseline_buttons() { + let (mut app, ctx, screen, sid) = scope_dialog_with_selection("red red", 3); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red"); +} + +#[test] +fn find_scope_dialog_grep_tab_alone_restarts_original_selection() { + let (mut app, ctx, screen, sid) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_click(&mut app, &ctx, screen, "GREP"); + assert!(app.ui.dialog.as_ref().unwrap().b("grep")); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("find"), "red"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 4, 7); + scope_click(&mut app, &ctx, screen, "Text"); + assert!(!app.ui.dialog.as_ref().unwrap().b("grep")); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); +} + +#[test] +fn find_scope_dialog_buttons_retain_nonempty_hits_and_change_all() { + let (mut app, ctx, screen, sid) = scope_dialog(); + let history = app.session.doc().unwrap().history.undo.len(); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 4, 7); + scope_click(&mut app, &ctx, screen, "Find Next"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches"); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1); + scope_click(&mut app, &ctx, screen, "Cancel"); + assert!(app.ui.dialog.is_none()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); + app.run("edit.redo", json!({})).unwrap(); + let native = app.run("file.serialize", json!({})).unwrap(); + app.run("file.openBytes", json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); +} + +fn scope_confirm_case(action: &str) { + let (mut app, ctx, screen, sid) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Count"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + match action { + "OK" => scope_click(&mut app, &ctx, screen, "OK"), + "Enter" => { + dialog_frame( + &mut app, + &ctx, + screen, + vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + } + "control" => { + assert_eq!(scope_control(&mut app, &ctx, "ui.dialog.confirm", json!({}))["count"], 2); + } + _ => panic!("known confirmation route"), + } + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red"); + // The closed dialog cannot leave its old seven-byte range for a later direct query. + let matches = app.run("find.find", json!({"find": "blue", "scope": "selection"})).unwrap(); + assert_eq!(matches.as_array().unwrap().len(), 0); +} + +#[test] +fn find_scope_dialog_ok_consumes_retained_bounds() { + scope_confirm_case("OK"); +} + +#[test] +fn find_scope_dialog_enter_consumes_retained_bounds() { + scope_confirm_case("Enter"); +} + +#[test] +fn find_scope_dialog_control_confirm_consumes_retained_bounds() { + scope_confirm_case("control"); +} + +#[test] +fn find_scope_dialog_query_reselection_cancel_and_reopen() { + let (mut app, ctx, screen, sid) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true})); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "r.d"})); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({})); + assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1); + app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 7})).unwrap(); + app.run("find.next", json!({"find": "red", "scope": "selection"})).unwrap(); + scope_control(&mut app, &ctx, "ui.dialog.open", json!({"id": "findChange", "fields": {"find": "red", "scope": "selection"}})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); + app.run("text.select", json!({"story": sid.0, "anchor": 4, "focus": 7})).unwrap(); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 4, 7); + app.run("app.findChange", json!({})).unwrap(); + for (field, value) in [("find", "red"), ("scope", "selection")] { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value})); + } + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); +} + +#[test] +fn find_scope_dialog_word_reselection_limits_count_and_change_buttons() { + let (mut app, ctx, screen, sid) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let selected = app.session.doc().unwrap().selection.clone(); + let frame = selected.text.unwrap().frame.unwrap(); + let point = { + let st = app.session.doc().unwrap(); + let cs = app.session.cache.get(&st.doc, sid, None); + let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap(); + let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5); + assert_eq!(cs.frames[fi].frame, frame); + assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1)); + let loc = st.doc.find(frame).unwrap(); + st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner + }; + let before = app.session.doc().unwrap().doc.clone(); + let revision = app.session.doc().unwrap().revision; + app.run("text.selectWord", json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection, selected); + assert!(app.session.doc().unwrap().revision > revision, "a new revision"); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)"); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn find_scope_dialog_failed_native_drop_alert_releases_bounds() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("broken.designcraft"); + std::fs::write(&path, b"not a native document").unwrap(); + for dismissal in ["OK", "Escape", "control"] { + let (mut app, ctx, screen, sid) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)"); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + let before = app.session.doc().unwrap().doc.clone(); + let selected = app.session.doc().unwrap().selection.clone(); + let revision = app.session.doc().unwrap().revision; + let history = app.session.doc().unwrap().history.undo.len(); + let uid = app.session.doc().unwrap().uid; + let error = app.open_dropped(&path.to_string_lossy()).unwrap_err(); + let alert = app.ui.dialog.as_ref().unwrap(); + assert_eq!(alert.id, "alert"); + assert_eq!(alert.s("title"), "Can't Open the File"); + assert_eq!(alert.s("message"), error); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); + assert_eq!(app.session.doc().unwrap().selection, selected); + assert_eq!(app.session.doc().unwrap().revision, revision); + assert_eq!(app.session.doc().unwrap().uid, uid); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history); + match dismissal { + "OK" => scope_click(&mut app, &ctx, screen, "OK"), + "Escape" => { + dialog_frame( + &mut app, + &ctx, + screen, + vec![egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }], + ); + } + "control" => { + scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({})); + } + _ => panic!("known dismissal"), + } + assert!(app.ui.dialog.is_none()); + let p = json!({"find": "red", "change": "blue", "scope": "selection"}); + assert_eq!(app.run("find.find", p.clone()).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}])); + assert_eq!(app.run("find.change", p).unwrap(), json!({"count": 1})); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1); + } +} + +#[test] +fn find_scope_dialog_child_errors_and_explicit_parent() { + let (mut app, ctx, screen, sid) = scope_dialog(); + app.run("text.select", json!({"story": sid.0, "anchor": 13, "focus": 13})).unwrap(); + app.run("table.insert", json!({"rows": 1, "cols": 1})).unwrap(); + app.run("text.insert", json!({"text": "red child", "raw": true})).unwrap(); + let child = app.session.doc().unwrap().selection.text.unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let selection = app.session.doc().unwrap().selection.clone(); + let history = app.session.doc().unwrap().history.undo.len(); + for label in ["Count", "Find Next", "Change All"] { + scope_click(&mut app, &ctx, screen, label); + assert!(app.ui.dialog.as_ref().unwrap().s("status").contains("not supported")); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); + assert_eq!(app.session.doc().unwrap().selection, selection); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history); + } + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"})); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0})); + scope_click(&mut app, &ctx, screen, "Count"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 match(es)"); + scope_click(&mut app, &ctx, screen, "Change All"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 replacement(s) made"); + assert_eq!(app.session.doc().unwrap().doc.text_story(sid, child.cell).unwrap().text, "red child"); + assert!(app.session.doc().unwrap().doc.story(sid).unwrap().text.starts_with("blue blue | blue")); +} + +#[test] +fn find_scope_dialog_error_confirmation_and_escape_release_context() { + for escape in [false, true] { + let (mut app, ctx, screen, sid) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Find Next"); + scope_selected(&app, sid, 0, 3); + if escape { + dialog_frame( + &mut app, + &ctx, + screen, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + } else { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "["})); + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true})); + scope_click(&mut app, &ctx, screen, "OK"); + } + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); + assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1); + } +} + +#[test] +fn find_scope_dialog_domain_and_object_changes_release_original_range() { + for route in ["scope", "object", "menu", "command"] { + let (mut app, ctx, screen, _) = scope_dialog(); + scope_click(&mut app, &ctx, screen, "Find Next"); + match route { + "scope" => { + for scope in ["story", "selection"] { + scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": scope})); + } + } + "object" => { + scope_click(&mut app, &ctx, screen, "Object"); + scope_click(&mut app, &ctx, screen, "Text"); + } + "menu" => crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null), + "command" => { + app.run("app.newDocumentDialog", json!({})).unwrap(); + } + _ => panic!("known reset route"), + } + assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1); + } +} + +#[test] +fn dialog_title_and_actions_fit_scaled_viewports() { + for language in ["en", "ar"] { + for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0)] { + for (command, title, ok, cancel) in + [("app.preferences", "Preferences", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "Create", "Close")] + { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.language = language.into(); + app.run("file.new", json!({})).unwrap(); + app.run(command, json!({})).unwrap(); + let ctx = dialog_context(language); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in [title, ok, cancel] { + visible_label(&labels, screen, crate::i18n::tr(language, expected)); + } + } + } + } +} + +#[test] +fn preferences_first_setting_switches_interface_language() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("app.preferences", json!({})).unwrap(); + let ctx = dialog_context(""); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let heading = visible_label(&labels, screen, "Interface Language"); + let combo = visible_label(&labels, screen, "English"); + let scaling = visible_label(&labels, screen, "When Scaling"); + assert!(heading.bottom() <= combo.top() && combo.bottom() <= scaling.top(), "the language comes first: {heading:?} {combo:?} {scaling:?}"); + let pane = labels.iter().filter(|(_, rect, _)| rect.left() >= heading.left() - 1.0 && rect.top() < heading.top()); + assert!(pane.clone().all(|(text, _, _)| text == "Preferences"), "nothing above it: {:?}", pane.collect::>()); + + // Choosing a language applies it at once; the dialog stays open. + click_dialog(&mut app, &ctx, screen, combo.center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for (_, name) in crate::i18n::LANGUAGES { + assert!(labels.iter().any(|(text, _, _)| text == name), "{name} is listed by its own name"); + } + let deutsch = visible_label(&labels, screen, "Deutsch").center(); + click_dialog(&mut app, &ctx, screen, deutsch); + assert_eq!(app.ui.language, "de"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let heading = visible_label(&labels, screen, crate::i18n::tr("de", "Interface Language")); + let combo = visible_label(&labels, screen, "Deutsch"); + + // The names stay endonyms in the German interface. + click_dialog(&mut app, &ctx, screen, combo.center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for name in ["English", "Français", "日本語", "Українська"] { + assert!(labels.iter().any(|(text, _, _)| text == name), "{name}"); + } + click_dialog(&mut app, &ctx, screen, heading.center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(!labels.iter().any(|(text, _, _)| text == "Français"), "the list closes"); + + // The control channel's command and the combo show the same setting. + app.run("app.language", json!({"lang": "ja"})).unwrap(); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(labels.iter().any(|(text, _, _)| text == "日本語")); + assert!(labels.iter().any(|(text, _, _)| text == crate::i18n::tr("ja", "Interface Language"))); + + // Cancel puts back the language the dialog opened with; OK keeps the choice. + let cancel_button = visible_label(&labels, screen, crate::i18n::tr("ja", "Cancel")).center(); + click_dialog(&mut app, &ctx, screen, cancel_button); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.language, ""); + app.run("app.preferences", json!({})).unwrap(); + app.run("app.language", json!({"lang": "it"})).unwrap(); + confirm(&mut app).unwrap(); + assert_eq!(app.ui.language, "it"); + app.run("app.preferences", json!({})).unwrap(); + app.run("app.language", json!({"lang": "uk"})).unwrap(); + cancel(&mut app); + assert_eq!(app.ui.language, "it"); +} + +#[test] +fn preferences_sidebar_scroll_keeps_selected_options_visible() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("app.preferences", json!({})).unwrap(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let sidebar = visible_label(&labels, screen, "General").center(); + assert!(!labels.iter().any(|(text, rect, clip)| text == "File Handling" && clip.contains_rect(*rect)), "last section starts below the sidebar"); + scroll_dialog(&mut app, &ctx, screen, sidebar, egui::vec2(0.0, -600.0)); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let files = visible_label(&labels, screen, "File Handling").center(); + click_dialog(&mut app, &ctx, screen, files); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("section"), "files"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in ["Document Recovery Data", "Save recovery data every:", "OK", "Cancel"] { + visible_label(&labels, screen, expected); + } +} + +#[test] +fn preferences_horizontal_scroll_reaches_clipped_options() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("app.preferences", json!({})).unwrap(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(450.0, 280.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let body = visible_label(&labels, screen, "When Scaling").center(); + // The last General option sits below this short viewport. + scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(0.0, -600.0)); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let option = "Absolute Numbering (instead of Section Numbering)"; + let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == option).unwrap(); + assert!(rect.right() > clip.right(), "rightmost option starts horizontally clipped: {rect:?}, {clip:?}"); + scroll_dialog(&mut app, &ctx, screen, body, egui::vec2(-600.0, 0.0)); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in [option, "Preferences", "OK", "Cancel"] { + visible_label(&labels, screen, expected); + } + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, option).center()); + assert!(app.ui.dialog.as_ref().unwrap().b("absolutePageNumbers")); +} + +/// Scroll the dialog body down at `at` until `text` is painted unclipped on screen. +fn scroll_to_label(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, at: egui::Pos2, text: &str) -> egui::Rect { + for _ in 0..40 { + let labels = dialog_frame(app, ctx, screen, vec![]); + if let Some((_, rect, _)) = labels.iter().find(|(t, r, clip)| t.trim() == text && screen.contains_rect(*r) && clip.contains_rect(*r)) { + return *rect; + } + scroll_dialog(app, ctx, screen, at, egui::vec2(0.0, -60.0)); + } + panic!("{text} never scrolled into view"); +} + +#[test] +fn new_document_vertical_scroll_reaches_every_field_and_preset() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("app.newDocumentDialog", json!({})).unwrap(); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(392.0, 271.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let body = visible_label(&labels, screen, "Width").center(); + let shown = |labels: &[(String, egui::Rect, egui::Rect)]| labels.iter().any(|(t, r, clip)| t == "Primary Text Frame" && clip.contains_rect(*r)); + assert!(!shown(&labels), "the details start vertically clipped"); + let ptf = scroll_to_label(&mut app, &ctx, screen, body, "Primary Text Frame"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in ["New Document", "Create", "Close"] { + visible_label(&labels, screen, expected); + } + click_dialog(&mut app, &ctx, screen, ptf.center()); + assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "the caption toggles its checkbox"); + // Below the details: the preset tabs and cards. + scroll_to_label(&mut app, &ctx, screen, body, "[Default]"); +} + +#[test] +fn arabic_new_document_fields_remain_reachable_and_editable() { + for size in [egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0), egui::vec2(1178.0, 814.0)] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.language = "ar".into(); + app.run("app.newDocumentDialog", json!({})).unwrap(); + let fields = [("height", "66p1"), ("gutter", "1p2"), ("marginBottom", "3p3"), ("marginOutside", "3p4")]; + for (field, value) in fields { + app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(value)); + } + let ctx = dialog_context("ar"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + // With craft-fonts' Noto Sans Arabic the rows above are taller, so at the smallest size the + // Height field starts partly below the body's clip: scroll to it like the other fields. + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let (_, _, body) = labels.iter().find(|(text, _, _)| text.trim() == "66p1").expect("66p1 is painted"); + let height = scroll_to_label(&mut app, &ctx, screen, body.center(), "66p1"); + click_dialog(&mut app, &ctx, screen, height.center()); + dialog_frame( + &mut app, + &ctx, + screen, + vec![ + egui::Event::Key { + key: egui::Key::A, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() }, + }, + egui::Event::Text("88p8".into()), + ], + ); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("height"), "88p8", "numeric fields accept edits"); + let caption = scroll_to_label(&mut app, &ctx, screen, height.center(), crate::i18n::tr("ar", "Primary Text Frame")); + click_dialog(&mut app, &ctx, screen, caption.center()); + assert!(app.ui.dialog.as_ref().unwrap().b("primaryTextFrame"), "checkboxes remain clickable"); + for (_, value) in &fields[1..] { + scroll_to_label(&mut app, &ctx, screen, height.center(), value); + } + } +} + +#[test] +fn resized_dialogs_cancel_and_reopen_without_applying_edits() { + for (command, title, field, ok, cancel) in + [("app.preferences", "Preferences", "recoveryMinutes", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "pages", "Create", "Close")] + { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run(command, json!({})).unwrap(); + let original = app.ui.dialog.as_ref().unwrap().fields[field].clone(); + app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(42)); + let ctx = dialog_context("en"); + for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0), egui::vec2(589.0, 407.0)] { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in [title, ok, cancel] { + visible_label(&labels, screen, expected); + } + } + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(589.0, 407.0)); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, cancel).center()); + assert!(app.ui.dialog.is_none()); + assert!(app.session.active().is_none(), "cancelling must not create a document"); + app.run(command, json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], original, "cancelled edits must not survive reopening"); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, title); + dialog_frame( + &mut app, + &ctx, + screen, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(app.ui.dialog.is_none(), "Escape must also close the reopened dialog"); + } +} + +#[test] +fn paragraph_style_options_tabs_section_adds_a_stop_on_its_ruler() { + use egui_kittest::kittest::Queryable; + let (app, _) = ruled_paragraph(); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "tabs"}))); + h.run_steps(4); + h.get_by_label("Clear All"); + // The ruler sits below the row of alignment buttons; its strip takes the click. + let b = h.get_by_label("Right-aligned tab").rect(); + h.get_by_label("Right-aligned tab").click(); + h.run_steps(2); + let left = h.get_by_label("Left-aligned tab").rect(); + let at = egui::pos2(left.min.x + crate::panels::tabs::PAD + 100.0, b.max.y + 14.0); + crate::test_window::click_at(&mut h, at); + let d = h.state().app.ui.dialog.clone().unwrap(); + let tabs = d.fields.get("p.tabs").cloned().unwrap_or_default(); + assert_eq!(tabs.as_array().map(Vec::len), Some(1), "{tabs}"); + assert_eq!(tabs[0]["align"], "right"); + confirm(&mut h.state_mut().app).unwrap(); + let app = &mut h.state_mut().app; + let style = app.session.execute("type.tabs.get", &json!({"style": "Ruled Child"})).unwrap(); + assert_eq!(style["tabs"], tabs); + assert_eq!(app.session.execute("type.tabs.get", &json!({})).unwrap()["tabs"], tabs, "the paragraph follows its style"); +} + +#[test] +fn parses_command_params() { + let f = command_fields("{name, type: custom|lastPageNumber|chapterNumber, text?, rule?: {on, weight}, flag?: bool} — creates"); + let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect(); + assert_eq!(keys, ["name", "type", "text", "rule", "flag"]); + assert_eq!(f[1].choices, ["custom", "lastPageNumber", "chapterNumber"]); + assert!(!f[0].optional && f[2].optional); + assert!(f[4].boolean); + assert!(command_fields("{}").is_empty()); + assert!(command_fields("no params").is_empty()); + // A parenthetical after the key describes the value. + let f = command_fields("{angle (degrees, CCW), ids?}"); + let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect(); + assert_eq!(keys, ["angle", "ids"]); + assert!(!f[0].optional && f[1].optional); + assert_eq!(f[0].hint, "degrees, CCW"); + let f = command_fields("{scaleX? (%), ref?: 0..8, ids?: parent items (default: all)}"); + let keys: Vec<&str> = f.iter().map(|f| f.key.as_str()).collect(); + assert_eq!(keys, ["scaleX", "ref", "ids"]); + assert!(f.iter().all(|f| f.optional)); + assert_eq!(f[0].hint, "%"); + assert_eq!(f[2].hint, "parent items (default: all)"); + // Every command with a "…" label parses without panicking. + for c in designcraft_engine::command_specs() { + let _ = command_fields(c.params); + } +} + +fn test_app() -> crate::DesignApp { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 1})).unwrap(); + app +} + +#[test] +fn toc_dialog_keeps_the_character_styles_and_sorting_of_its_entries() { + let mut app = test_app(); + app.session.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap(); + app.session.execute("style.character.create", &json!({"name": "Number"})).unwrap(); + app.session.execute("style.character.create", &json!({"name": "Dots"})).unwrap(); + let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Pears\nApples"})).unwrap()["story"] + .clone(); + app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 8})).unwrap(); + app.session.execute("style.paragraph.apply", &json!({"name": "Head"})).unwrap(); + app.session.execute("layout.pages.insert", &json!({"count": 1})).unwrap(); + let entries = json!([{"style": "Head", "pageNumberStyle": "Number", "separatorStyle": "Dots", "sort": true}]); + app.session.execute("toc.generate", &json!({"page": 2, "entries": entries})).unwrap(); + let before = app.session.active().unwrap().doc.toc.clone().unwrap(); + // The dialog shows the options, and OK (Replace Existing) writes them back unchanged. + open_toc(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + let row = &toc_rows(d)[0]; + assert_eq!((row.page_number_style.as_str(), row.separator_style.as_str(), row.sort), ("Number", "Dots", true)); + let chars: Vec = serde_json::from_value(d.fields["charStyles"].clone()).unwrap(); + assert_eq!(chars, ["Number", "Dots"], "[None] is the menu's first choice, not a style"); + let p = toc_params(&app, d); + assert_eq!( + (&p["entries"][0]["pageNumberStyle"], &p["entries"][0]["separatorStyle"], &p["entries"][0]["sort"]), + (&json!("Number"), &json!("Dots"), &json!(true)) + ); + confirm(&mut app).expect("OK regenerates the table of contents"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.toc.as_ref().unwrap().entries, before.entries); + // [None] and unsorted are left out of the params. + let mut d = Dialog::new(TOC, json!({"included": [{"style": "Head", "level": 1, "separator": "^t"}]})); + d.fields.insert("replace".into(), json!(true)); + let p = toc_params(&app, &d); + assert!(p["entries"][0].get("pageNumberStyle").is_none() && p["entries"][0].get("sort").is_none(), "{p}"); +} + +#[test] +fn paragraph_style_options_dialog_saves_edits() { + let mut app = test_app(); + let name = app.session.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap()["name"].as_str().unwrap().to_string(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": name, "p.align": "center"}))); + confirm(&mut app).expect("OK saves the style edit"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.styles.para(&name).unwrap().para.align, Some(designcraft_doc::Align::Center)); +} + +#[test] +fn paragraph_style_options_align_to_grid_shows_and_sets_the_style_grid_alignment() { + use designcraft_doc::GridAlign; + use egui_kittest::kittest::Queryable; + let mut app = test_app(); + app.session.execute("style.paragraph.create", &json!({"name": "Grid Body", "para": {"gridAlign": "firstLineOnly"}})).unwrap(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"}))); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + let grid = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| { + h.state().app.session.active().unwrap().doc.styles.para("Grid Body").unwrap().para.grid_align + }; + h.run_steps(4); + h.get_by_value("First Line Only"); + confirm(&mut h.state_mut().app).unwrap(); + assert_eq!(grid(&h), Some(GridAlign::FirstLineOnly), "OK without edits keeps the style's alignment"); + h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Grid Body", "section": "indents"}))); + h.run_steps(4); + h.get_by_value("First Line Only").click(); + h.run_steps(3); + h.get_by_label("All Lines").click(); + h.run_steps(3); + confirm(&mut h.state_mut().app).unwrap(); + assert_eq!(grid(&h), Some(GridAlign::AllLines)); +} + +#[test] +fn delete_paragraph_style_dialog_removes_the_style_and_reassigns_text() { + let mut app = test_app(); + let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string(); + let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap(); + app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap(); + app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + app.session.execute("style.paragraph.apply", &json!({"name": name})).unwrap(); + app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH}))); + confirm(&mut app).expect("OK deletes the style"); + let st = app.session.active().unwrap(); + assert!(st.doc.styles.para(&name).is_none(), "style removed"); + let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap(); + assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "text reassigned to the replacement style"); +} + +#[test] +fn delete_paragraph_style_dialog_defaults_replacement_to_basic_paragraph() { + let mut app = test_app(); + let name = app.session.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string(); + // No `replaceWith` set — the dialog's default field. + app.ui.dialog = Some(Dialog::new("deleteParagraphStyle", json!({"name": name}))); + confirm(&mut app).expect("OK deletes the style with the default replacement"); + let st = app.session.active().unwrap(); + assert!(st.doc.styles.para(&name).is_none()); +} + +#[test] +fn character_style_options_dialog_saves_edits() { + let mut app = test_app(); + let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); + app.ui.dialog = Some(Dialog::new("characterStyleOptions", json!({"name": name, "c.tracking": 20.0}))); + confirm(&mut app).expect("OK saves the style edit"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.styles.char_style(&name).unwrap().chars.tracking, Some(20.0)); +} + +#[test] +fn delete_character_style_dialog_removes_the_style_and_reassigns_text() { + let mut app = test_app(); + let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); + let sid = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap(); + app.session.execute("text.insert", &json!({"text": "Hello"})).unwrap(); + app.session.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap(); + app.session.execute("style.character.apply", &json!({"name": name})).unwrap(); + app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE}))); + confirm(&mut app).expect("OK deletes the style"); + let st = app.session.active().unwrap(); + assert!(st.doc.styles.char_style(&name).is_none(), "style removed"); + let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).unwrap(); + assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "text reassigned to the replacement style"); +} + +#[test] +fn delete_character_style_dialog_defaults_replacement_to_none() { + let mut app = test_app(); + let name = app.session.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); + // No `replaceWith` set — the dialog's default field. + app.ui.dialog = Some(Dialog::new("deleteCharacterStyle", json!({"name": name}))); + confirm(&mut app).expect("OK deletes the style with the default replacement"); + let st = app.session.active().unwrap(); + assert!(st.doc.styles.char_style(&name).is_none()); +} + +/// File › Export EPUB… opens EPUB Export Options from the document's setting; OK stores a +/// changed Split Document as one undo step, and an unchanged one adds none. +#[test] +fn epub_export_passes_its_options_to_the_engine() { + use std::io::Read; + use std::sync::{Arc, Mutex}; + let mut app = test_app(); + app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap(); + let r = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "One\nTwo"})).unwrap(); + let sid = r["story"].as_u64().unwrap(); + for anchor in [0, 4] { + app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": anchor})).unwrap(); + app.session.execute("style.paragraph.apply", &json!({"name": "Chapter"})).unwrap(); + } + let written: Arc>> = Arc::new(Mutex::new(Vec::new())); + let sink = written.clone(); + app.services.write = Some(Box::new(move |_: &str, bytes: &[u8]| { + *sink.lock().unwrap() = bytes.to_vec(); + Ok(()) + })); + crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "split": {"style": "Chapter"}})).unwrap(); + let bytes = written.lock().unwrap().clone(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut opf = String::new(); + z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); + assert!(opf.contains("properties=\"cover-image\""), "the first page is the cover: {opf}"); + assert!(z.by_name("OEBPS/content2.xhtml").is_ok(), "the split override reaches the export"); + assert_eq!(app.session.active().unwrap().doc.settings.epub_split, designcraft_doc::EpubSplit::Off, "an override is not stored"); + crate::menus::export_epub(&mut app, &json!({"path": "book.epub", "cover": false})).unwrap(); + let bytes = written.lock().unwrap().clone(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut opf = String::new(); + z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); + assert!(!opf.contains("cover-image"), "a caller's cover: false stays: {opf}"); +} + +#[test] +fn epub_export_options_store_split_document() { + use designcraft_doc::EpubSplit; + let mut app = test_app(); + app.session.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap(); + let undo_steps = |app: &crate::DesignApp| app.session.active().map(|st| st.history.undo.len()); + app.run("app.exportEpub", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.id.as_str(), d.b("split"), d.s("style").as_str()), ("epubExport", false, designcraft_doc::BASIC_PARAGRAPH)); + d.fields.insert("split".into(), json!(true)); + d.fields.insert("style".into(), json!("Chapter")); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::Style("Chapter".into())); + assert_eq!(undo_steps(&app), before.map(|n| n + 1)); + open_epub_export(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| (d.b("split"), d.s("mode"), d.s("style"))), Some((true, "style".into(), "Chapter".into()))); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before.map(|n| n + 1), "unchanged: no undo step"); + open_epub_export(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("exportTags")); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags); + open_epub_export(&mut app); + cancel(&mut app); + assert_eq!(app.session.active().unwrap().doc.settings.epub_split, EpubSplit::ExportTags, "Cancel stores nothing"); +} + +#[test] +fn pdf_export_defaults() { + let d = Dialog::new("pdfExport", json!({})); + let keys: Vec<&str> = d.fields.iter().map(|(k, _)| k.as_str()).collect(); + // serde_json::Map keeps keys sorted. + let expected = [ + "bleed", + "compressImages", + "flatten", + "marksBleed", + "marksCrop", + "marksOffset", + "marksPageInfo", + "marksWeight", + "preset", + "spreads", + "standard", + "tagged", + ]; + assert_eq!(keys, expected); + assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing")); + assert_eq!(d.fields["standard"].as_str(), Some("none")); + assert_eq!(d.fields["compressImages"].as_bool(), Some(false)); + assert_eq!(d.fields["flatten"].as_str(), Some("")); + assert_eq!(d.fields["spreads"].as_bool(), Some(false)); + assert_eq!(d.fields["bleed"].as_bool(), Some(true)); + assert_eq!(d.fields["marksCrop"].as_bool(), Some(false)); + assert_eq!(d.fields["marksBleed"].as_bool(), Some(false)); + assert_eq!(d.fields["marksPageInfo"].as_bool(), Some(false)); + assert_eq!(d.fields["marksWeight"].as_str(), Some("0.25")); + assert_eq!(d.fields["marksOffset"].as_str(), Some("6")); + assert_eq!(d.fields["tagged"].as_bool(), Some(true)); +} + +#[test] +fn pdf_export_override_keeps_override() { + let d = Dialog::new("pdfExport", json!({"bleed": false})); + assert_eq!(d.fields["bleed"].as_bool(), Some(false)); + assert_eq!(d.fields["preset"].as_str(), Some("Desktop Printing")); + assert_eq!(d.fields["tagged"].as_bool(), Some(true)); +} + +#[test] +fn pdf_export_preset_high_quality_print_keeps_flatten() { + let mut d = Dialog::new("pdfExport", json!({})); + d.fields.insert("flatten".into(), json!("medium")); + apply_pdf_preset(&mut d, "Desktop Printing"); + assert_eq!(d.s("standard"), "none"); + assert!(!d.b("compressImages")); + assert!(!d.b("marksCrop")); + assert!(!d.b("marksBleed")); + assert!(!d.b("marksPageInfo")); + assert_eq!(d.s("flatten"), "medium", "a leave-unchanged preset must not touch flatten"); +} + +#[test] +fn pdf_export_preset_press_quality_keeps_flatten() { + let mut d = Dialog::new("pdfExport", json!({})); + d.fields.insert("flatten".into(), json!("high")); + apply_pdf_preset(&mut d, "Commercial Printing"); + assert_eq!(d.s("standard"), "none"); + assert!(d.b("compressImages")); + assert!(d.b("marksCrop")); + assert!(d.b("marksBleed")); + assert!(!d.b("marksPageInfo")); + assert_eq!(d.s("flatten"), "high"); +} + +#[test] +fn pdf_export_preset_smallest_file_size_sets_flatten_low() { + let mut d = Dialog::new("pdfExport", json!({})); + apply_pdf_preset(&mut d, "Screen and Email"); + assert_eq!(d.s("standard"), "none"); + assert!(d.b("compressImages")); + assert!(!d.b("marksCrop")); + assert!(!d.b("marksBleed")); + assert!(!d.b("marksPageInfo")); + assert_eq!(d.s("flatten"), "low"); +} + +/// The PDF/X-1a preset exports X-1a with the High Resolution flattener and printer's marks. +#[test] +fn pdf_export_preset_pdf_x1a_flattens_at_high_resolution() { + let mut d = Dialog::new("pdfExport", json!({})); + apply_pdf_preset(&mut d, "PDF/X-1a:2003"); + assert_eq!(d.s("standard"), "x1a"); + assert_eq!(d.s("flatten"), "high"); + assert!(d.b("marksCrop") && d.b("marksBleed")); + assert!(PDF_EXPORT_PRESETS.contains(&"PDF/X-1a:2003")); +} + +#[test] +fn pdf_export_preset_pdf_x4_keeps_flatten() { + let mut d = Dialog::new("pdfExport", json!({})); + d.fields.insert("flatten".into(), json!("medium")); + apply_pdf_preset(&mut d, "PDF/X-4"); + assert_eq!(d.s("standard"), "x4"); + assert!(!d.b("compressImages")); + assert!(d.b("marksCrop")); + assert!(d.b("marksBleed")); + assert!(!d.b("marksPageInfo")); + assert_eq!(d.s("flatten"), "medium"); +} + +#[test] +fn pdf_export_preset_pdf_a2b_keeps_flatten() { + let mut d = Dialog::new("pdfExport", json!({})); + d.fields.insert("flatten".into(), json!("low")); + apply_pdf_preset(&mut d, "PDF/A-2b"); + assert_eq!(d.s("standard"), "a2b"); + assert!(!d.b("compressImages")); + assert!(!d.b("marksCrop")); + assert!(!d.b("marksBleed")); + assert!(!d.b("marksPageInfo")); + assert_eq!(d.s("flatten"), "low"); +} + +#[test] +fn open_pdf_export_seeds_fields_from_settings() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.pdf_export.standard = "x4".into(); + app.ui.pdf_export.tagged = false; + app.ui.pdf_export.marks_crop = true; + app.ui.pdf_export.flatten = String::new(); + app.ui.flattener = "medium".into(); + open_pdf_export(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.id, "pdfExport"); + assert_eq!(d.s("standard"), "x4"); + assert!(!d.b("tagged")); + assert!(d.b("marksCrop")); + assert_eq!(d.s("pages"), "all"); + assert_eq!(d.s("flatten"), "medium", "empty flatten falls back to the global flattener"); + assert_eq!(d.s("title"), "", "no document → empty title"); + + // A non-empty persisted flatten is used verbatim, not the global fallback. + app.ui.pdf_export.flatten = "low".into(); + app.ui.flattener = "medium".into(); + open_pdf_export(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.s("flatten"), "low"); +} + +#[test] +fn pdf_export_preset_custom_changes_nothing() { + let mut d = Dialog::new("pdfExport", json!({})); + d.fields.insert("standard".into(), json!("x4")); + d.fields.insert("compressImages".into(), json!(true)); + d.fields.insert("marksCrop".into(), json!(true)); + d.fields.insert("marksBleed".into(), json!(true)); + d.fields.insert("marksPageInfo".into(), json!(true)); + d.fields.insert("flatten".into(), json!("high")); + let before = d.fields.clone(); + apply_pdf_preset(&mut d, "Custom"); + assert_eq!(d.fields, before); +} + +#[test] +fn confirm_pdf_export_writes_file_and_persists_settings() { + use std::sync::{Arc, Mutex}; + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let writes: Arc)>>> = Arc::new(Mutex::new(Vec::new())); + let sink = writes.clone(); + app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { + sink.lock().unwrap().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + app.services.pick_save = Some(Box::new(|_name: &str| Some("/tmp/designcraft-test.pdf".to_string()))); + + app.ui.dialog = Some(Dialog::new("pdfExport", json!({}))); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("standard".into(), json!("x4")); + d.fields.insert("bleed".into(), json!(false)); + d.fields.insert("marksCrop".into(), json!(true)); + d.fields.insert("tagged".into(), json!(false)); + d.fields.insert("title".into(), json!("Report")); + } + confirm(&mut app).unwrap(); + + let got = writes.lock().unwrap(); + assert_eq!(got.len(), 1, "confirming the dialog writes exactly one file"); + assert_eq!(got[0].0, "/tmp/designcraft-test.pdf"); + assert!(got[0].1.starts_with(b"%PDF"), "the written bytes are a PDF"); + drop(got); + + assert_eq!(app.ui.pdf_export.standard, "x4"); + assert!(!app.ui.pdf_export.bleed); + assert!(app.ui.pdf_export.marks_crop); + assert!(!app.ui.pdf_export.tagged); +} + +#[test] +fn update_link_asks_before_replacing_edits_made_in_the_layout() { + let dir = std::env::temp_dir().join(format!("dc-update-link-dialog-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("note.txt"); + std::fs::write(&path, "One").unwrap(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let r = app.session.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true, "rect": [72, 72, 300, 200]})).unwrap(); + let sid = r["story"].as_u64().unwrap(); + let text = |app: &crate::DesignApp| app.session.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone(); + + // Not edited in the layout: updates without asking. + std::fs::write(&path, "Two").unwrap(); + crate::panels::properties::update_links(&mut app, json!({"story": sid})); + assert!(app.ui.dialog.is_none()); + assert_eq!(text(&app), "Two"); + + // Edited in the layout: asks first; Cancel changes nothing. + app.session.execute("story.setText", &json!({"story": sid, "text": "Mine"})).unwrap(); + std::fs::write(&path, "Three").unwrap(); + crate::panels::properties::update_links(&mut app, json!({"story": sid})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.id.as_str(), d.s("files").as_str()), ("updateLink", "note.txt")); + app.ui.dialog = None; + assert_eq!(text(&app), "Mine"); + + // Window › Links › Update Link (all links) asks too; confirming updates. + crate::menus::activate(&mut app, "links.update", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("updateLink")); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(text(&app), "Three"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn confirm_pdf_export_cancelled_save_writes_nothing() { + use std::sync::{Arc, Mutex}; + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let writes: Arc)>>> = Arc::new(Mutex::new(Vec::new())); + let sink = writes.clone(); + app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { + sink.lock().unwrap().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + app.services.pick_save = Some(Box::new(|_name: &str| None)); + + app.ui.dialog = Some(Dialog::new("pdfExport", json!({}))); + let r = confirm(&mut app).unwrap(); + assert_eq!(r, Value::Null); + assert!(writes.lock().unwrap().is_empty(), "cancelling the save picker must not write"); +} + +use designcraft_doc::{CharAttrs, CharacterStyle}; + +/// A document with character styles Base (bold) and Emphasis (italic) on the first two letters. +fn styled_app() -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.character.create", json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap(); + app.run("style.character.create", json!({"name": "Emphasis", "chars": {"fontStyle": "Italic"}})).unwrap(); + let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 2})).unwrap(); + app.run("style.character.apply", json!({"name": "Emphasis"})).unwrap(); + app +} + +/// One control-channel request, as the control port or MCP would send it. +fn ctl(app: &mut DesignApp, method: &str, params: Value) -> Value { + let (req, _reply) = crate::control::ControlRequest::new(method, params); + match crate::control::handle(app, &egui::Context::default(), &req) { + crate::control::Outcome::Done(v) => v, + crate::control::Outcome::Screenshot { .. } => Value::Null, + } +} + +fn char_style(app: &DesignApp, name: &str) -> Option { + app.session.active().and_then(|st| st.doc.styles.char_style(name).cloned()) +} + +#[test] +fn character_style_options_set_exactly_the_edited_attributes() { + let mut app = styled_app(); + assert_eq!(ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}))["ok"], true); + ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 14})); + ctl(&mut app, "ui.dialog.set", json!({"field": "c.fill", "value": "[Paper]"})); + ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": "Base"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert!(app.ui.dialog.is_none()); + let st = char_style(&app, "Emphasis").unwrap(); + assert_eq!(st.based_on.as_deref(), Some("Base")); + assert_eq!(st.chars, CharAttrs { font_style: Some("Italic".into()), size: Some(14.0), fill: Some("[Paper]".into()), ..Default::default() }); +} + +#[test] +fn character_style_options_unset_cleared_fields_and_rename_every_use() { + let mut app = styled_app(); + ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}})); + ctl(&mut app, "ui.dialog.set", json!({"field": "c.fontStyle", "value": null})); + ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Strong"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert!(char_style(&app, "Emphasis").is_none()); + assert!(char_style(&app, "Strong").unwrap().chars.is_empty()); + let st = app.session.active().unwrap(); + let story = st.doc.stories.values().next().unwrap(); + assert!(story.chars.iter().any(|r| r.format.style == "Strong")); + // A taken name keeps the dialog open with the reason. + ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Strong"}})); + ctl(&mut app, "ui.dialog.set", json!({"field": "rename", "value": "Base"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.s("status").is_empty())); + assert!(char_style(&app, "Strong").is_some()); +} + +#[test] +fn new_character_style_opens_its_options_and_creates_the_style() { + let mut app = styled_app(); + crate::menus::activate(&mut app, "style.character.create", &Value::Null); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("characterStyleOptions", true, "Character Style 1")); + ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 9})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let st = char_style(&app, "Character Style 1").unwrap(); + assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), ..Default::default() })); + crate::menus::activate(&mut app, "style.character.create", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("rename"), "Character Style 2"); +} + +#[test] +fn new_paragraph_style_opens_its_options_and_creates_the_style() { + let mut app = styled_app(); + crate::menus::activate(&mut app, "style.paragraph.create", &Value::Null); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.id.as_str(), d.b("new"), d.s("rename").as_str()), ("paragraphStyleOptions", true, "Paragraph Style 1")); + ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 20})); + ctl(&mut app, "ui.dialog.set", json!({"field": "basedOn", "value": designcraft_doc::BASIC_PARAGRAPH})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap(); + assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); + assert_eq!(st.chars, CharAttrs { size: Some(20.0), ..Default::default() }); +} + +#[test] +fn style_rows_open_their_options_except_none() { + let mut app = styled_app(); + open_style_options(&mut app, false, "Emphasis"); + let d = app.ui.dialog.take().unwrap(); + assert_eq!((d.id.as_str(), d.s("name").as_str()), ("characterStyleOptions", "Emphasis")); + open_style_options(&mut app, false, designcraft_doc::NO_CHAR_STYLE); + assert!(app.ui.dialog.is_none()); + open_style_options(&mut app, true, designcraft_doc::BASIC_PARAGRAPH); + assert_eq!(app.ui.dialog.take().unwrap().id, "paragraphStyleOptions"); +} + +#[test] +fn style_options_sections_draw() { + let mut app = styled_app(); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp| { + for _ in 0..2 { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))), + max_texture_side: Some(8192), + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + } + }; + for lang in ["", "ar"] { + app.run("app.language", json!({"lang": lang})).unwrap(); + for fields in [json!({"name": "Emphasis"}), json!({"new": true}), json!({"name": "Emphasis", "c.size": null, "c.underline": false})] { + for section in ["general", "chars", "advanced", "color", "openType", "underline", "strikethrough"] { + let mut f = fields.clone(); + f["section"] = json!(section); + app.ui.dialog = Some(Dialog::new("characterStyleOptions", f)); + frame(&mut app); + assert!(app.ui.dialog.is_some(), "{section} stays open"); + } + } + for section in + ["general", "chars", "advanced", "border", "shading", "keep", "span", "bullets", "color", "openType", "underline", "strikethrough"] + { + for fields in [ + json!({"new": true}), + json!({"new": true, "p.listType": "bullets", "p.spanColumns": {"kind": "span", "columns": 0}, "p.borderOn": true}), + json!({"new": true, "p.listType": "numbers", "p.startAt": 1, "p.spanColumns": {"kind": "split", "columns": 2}, "p.keepLinesTogether": true}), + ] { + let mut f = fields; + f["section"] = json!(section); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", f)); + frame(&mut app); + assert!(app.ui.dialog.is_some(), "{section} stays open"); + } + } + } +} + +#[test] +fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { + use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + use egui_kittest::{Harness, kittest::Queryable}; + fn drag(h: &mut Harness<'static, DesignApp>, from: Pos2, to: Pos2) { + h.event(Event::PointerMoved(from)); + h.run_steps(1); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for step in 1..=8 { + h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0))); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + } + let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.ui.dialog = Some(Dialog::new("insertTable", Value::Null)); + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut DesignApp| { + if !ready { + crate::theme::install_fonts(ui.ctx(), &app.ui.language); + crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default())); + ready = true; + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + let centred = rect(&h); + assert!((centred.center() - egui::pos2(600.0, 400.0)).length() < 1.0, "{centred:?}"); + assert!(centred.width() < 1000.0 && centred.height() < 700.0, "the area is the dialog, not the backdrop: {centred:?}"); + + let title = h.get_by_label("Create Table").rect().center(); + drag(&mut h, title, title + vec2(100.0, 60.0)); + let moved = rect(&h); + assert!((moved.min - centred.min - vec2(100.0, 60.0)).length() < 2.0, "{centred:?} -> {moved:?}"); + + let body = egui::pos2(moved.right() - 40.0, moved.center().y); + drag(&mut h, body, body + vec2(-150.0, 80.0)); + assert_eq!(rect(&h), moved, "a drag in the body leaves the dialog in place"); + + // The title row stays inside the top edge. + let title = h.get_by_label("Create Table").rect().center(); + drag(&mut h, title, title - vec2(0.0, 1000.0)); + assert!(rect(&h).top().abs() < 1.0, "{:?}", rect(&h)); + + // Opened again, the dialog starts centred. + h.state_mut().ui.dialog = None; + h.run_steps(2); + h.state_mut().ui.dialog = Some(Dialog::new("insertTable", Value::Null)); + h.run_steps(4); + assert!((rect(&h).center() - centred.center()).length() < 1.0, "{:?}", rect(&h)); + + // Past the left edge, about 100 px of the title row stays inside. + let title = h.get_by_label("Create Table").rect().center(); + drag(&mut h, title, title - vec2(900.0, 0.0)); + assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h)); +} + +#[test] +fn the_new_document_window_drags_mostly_aside_and_keeps_its_preview() { + use egui::{Event, Modifiers, PointerButton, vec2}; + use egui_kittest::{Harness, kittest::Queryable}; + let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::unique("dialog"))).unwrap(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "A"})).unwrap(); + app.ui.new_document_preview = true; + app.run("app.newDocumentDialog", json!({})).unwrap(); + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut DesignApp| { + if !ready { + crate::theme::install_fonts(ui.ctx(), &app.ui.language); + crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default())); + ready = true; + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(6); + let preview = h.state().session.new_document_preview(); + assert!(preview.is_some(), "Preview is on"); + let centred = rect(&h); + assert!(centred.width() > 900.0, "{centred:?}"); + let from = h.get_all_by_label("New Document").map(|n| n.rect().center()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap(); + let to = from + vec2(1300.0, 0.0); + h.event(Event::PointerMoved(from)); + h.run_steps(1); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for step in 1..=8 { + h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0))); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + // All but 100 px of the window's width is past the right edge, over the preview. + assert!((rect(&h).left() - 1300.0).abs() < 2.0, "{:?}", rect(&h)); + let app = h.state(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("newDocument")); + assert_eq!(app.session.new_document_preview(), preview, "moving the window keeps the preview"); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn margins_dialog_reads_bare_numbers_in_the_ruler_unit() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap(); + crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null); + for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] { + ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "15"})); + } + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let top = app.session.active().unwrap().doc.page(0).unwrap().margins.top; + assert!((top - 15.0 * 72.0 / 25.4).abs() < 0.01, "top margin was {top} pt"); +} +fn facing_app(pages: u64) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": pages, "facingPages": true})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + app +} + +fn guide_counts(app: &DesignApp) -> Vec { + let doc = &app.session.active().unwrap().doc; + (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect() +} + +#[test] +fn create_guides_dialog_targets_the_page_in_view() { + let mut app = facing_app(6); + crate::canvas::go_to_page(&mut app, 4); + crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); + ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert_eq!(guide_counts(&app), vec![0, 0, 0, 0, 4, 0]); + // "Both pages of the spread" covers the facing pair. + crate::canvas::go_to_page(&mut app, 1); + crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); + ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"})); + ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "spread"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]); +} + +#[test] +fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() { + let mut app = facing_app(4); + app.run("layout.parents.edit", json!({"on": true})).unwrap(); + crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread"); + for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] { + ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "20 pt"})); + } + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); + ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let doc = &app.session.active().unwrap().doc; + for pg in &doc.parents[0].pages { + assert_eq!((pg.margins.top, pg.margins.outside, pg.guides.len()), (20.0, 20.0, 2)); + } + // Every document page shows the parent's guides. + assert!((0..doc.page_count()).all(|abs| doc.inherited_guides(abs).len() == 2)); +} + +#[test] +fn other_dialogs_keep_reading_bare_numbers_as_picas() { + let mut app = facing_app(2); + app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap(); + app.ui.dialog = Some(Dialog::new("newDocument", json!({"width": "15"}))); + assert_eq!(app.ui.dialog.as_ref().unwrap().m("width"), Some(180.0)); +} +#[test] +fn character_style_options_set_the_digits() { + let mut app = styled_app(); + ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}})); + ctl(&mut app, "ui.dialog.set", json!({"field": "c.digits", "value": "farsi"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); +} From a72dfe2e49ae8c5fb56fbcb9e458645e13f6f2b3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:14 +0000 Subject: [PATCH 07/70] refactor(ui-egui): move the tests module of menus.rs to menus/tests.rs --- crates/ui-egui/src/menus.rs | 2998 +---------------------------- crates/ui-egui/src/menus/tests.rs | 2981 ++++++++++++++++++++++++++++ 2 files changed, 2982 insertions(+), 2997 deletions(-) create mode 100644 crates/ui-egui/src/menus/tests.rs diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a32d26e30..d2165b8e6 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -3582,3000 +3582,4 @@ pub fn command_search(app: &DesignApp, query: &str) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - /// The entries (command ids) of a menu bar menu, submenus included. - fn menu_ids(title: &str) -> Vec<&'static str> { - let items = MENUS.iter().find(|(t, _)| *t == title).map(|(_, items)| *items).unwrap_or_default(); - items.iter().filter_map(|e| e.split_once(':').map(|(_, rest)| rest.split('|').next().unwrap_or(rest))).collect() - } - - #[test] - fn view_items_are_in_the_view_menu_as_in_indesign() { - let (view, typ) = (menu_ids("View"), menu_ids("Type")); - for id in [ - "view.rotateSpread", - "view.proofSetup", - "view.proofColors", - "view.flattenerPreview", - "view.separations", - "view.taggedFrames", - "view.tagMarkers", - ] { - assert!(view.contains(&id), "{id} is in View"); - assert!(!typ.contains(&id), "{id} isn't in Type"); - } - // Screen Mode and Extras are View submenus; Show Hidden Characters stays in Type. - assert!(view.contains(&"view.screenMode") && view.contains(&"view.frameEdges")); - assert!(typ.contains(&"view.hiddenCharacters") && !view.contains(&"view.hiddenCharacters")); - // W still toggles Normal / Preview without a menu entry. - assert_eq!(ui_label("view.togglePreview").and_then(|c| c.1), Some("W")); - } - - /// The submenu paths of a menu bar menu ("View/Screen Mode"), as Edit › Menus keys them. - fn submenu_paths(title: &str) -> Vec { - let items = MENUS.iter().find(|(t, _)| *t == title).map(|(_, items)| *items).unwrap_or_default(); - let mut stack = vec![title.to_string()]; - let mut out = Vec::new(); - for e in items { - if let Some(name) = e.strip_prefix('>') { - let path = format!("{}/{name}", stack.last().map_or("", String::as_str)); - out.push(path.clone()); - stack.push(path); - } else if *e == "<" { - stack.pop(); - } - } - out - } - - /// A command's menu path names the menu entries that really hold it. - #[test] - fn define_lists_command_path_matches_the_type_menu() { - let spec = designcraft_engine::command_specs().iter().find(|c| c.id == "list.define").expect("list.define is a command"); - assert_eq!(spec.menu[0], "Type"); - assert!(submenu_paths("Type").contains(&spec.menu.join("/")), "{:?} is not a Type submenu", spec.menu); - assert!(menu_ids("Type").contains(&"list.define")); - } - - #[test] - fn screen_mode_shows_the_current_mode() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let mode = |app: &DesignApp, m: &str| checked(app, "view.screenMode", &json!({ "mode": m })); - assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(true), Some(false))); - app.ui.screen_mode = crate::ScreenMode::Preview; - assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(false), Some(true))); - } - - fn walk(items: &[Item], out: &mut Vec<(String, String, Value)>) { - for it in items { - match it { - Item::Sub(_, c) => walk(c, out), - Item::Cmd { label, id, params, .. } => out.push((label.clone(), id.clone(), params.clone())), - Item::Sep => {} - } - } - } - - /// Exercise the real dropdown, including clipping and wheel input, on a short viewport. - #[test] - fn oversized_edit_menu_scrolls_to_preferences() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 260.0)); - let mut tick = 0; - let mut frame = |app: &mut DesignApp, events: Vec| { - tick += 1; - let mut output = - ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { - egui::MenuBar::new().ui(ui, |ui| menu_bar(app, ui)); - }); - output.textures_delta.clear(); - let mut labels = Vec::new(); - fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) { - match shape { - egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)), - egui::Shape::Vec(shapes) => { - for shape in shapes { - collect(shape, clip, labels); - } - } - _ => {} - } - } - for shape in output.shapes { - collect(&shape.shape, shape.clip_rect, &mut labels); - } - labels - }; - frame(&mut app, vec![]); - let labels = frame(&mut app, vec![]); - let edit = labels.iter().find(|(text, _, _)| text == "Edit").unwrap().1.center(); - for pressed in [true, false] { - frame( - &mut app, - vec![ - egui::Event::PointerMoved(edit), - egui::Event::PointerButton { pos: edit, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - for _ in 0..3 { - frame(&mut app, vec![]); - } - let layer = ctx.layer_id_at(egui::pos2(edit.x + 80.0, 100.0)).expect("menu layer"); - let bounds = ctx.memory(|m| m.area_rect(layer.id)).expect("menu bounds"); - let track = egui::pos2(bounds.right() - 9.0, bounds.bottom() - 25.0); - for pressed in [true, false] { - frame( - &mut app, - vec![ - egui::Event::PointerMoved(track), - egui::Event::PointerButton { pos: track, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - assert!(egui::Popup::is_any_open(&ctx), "clicking the scroll track must not dismiss the menu"); - frame( - &mut app, - vec![ - egui::Event::PointerMoved(egui::pos2(edit.x + 80.0, 100.0)), - egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -3000.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }, - ], - ); - let mut labels = Vec::new(); - for _ in 0..60 { - labels = frame(&mut app, vec![]); - } - let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == "Preferences…").expect("Preferences is rendered"); - assert!(screen.contains_rect(*rect) && clip.contains_rect(*rect), "Preferences must be visible after scrolling: {rect:?}, {clip:?}"); - let pos = rect.center(); - for pressed in [true, false] { - frame( - &mut app, - vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); - assert!(!egui::Popup::is_any_open(&ctx), "choosing a command dismisses the menu"); - } - - #[test] - fn formatting_affects_text_sends_swatches_to_the_text() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - for (name, color) in [("Cyan", "#00ffff"), ("Magenta", "#ff00ff")] { - let created = app.run("swatch.create", json!({"name": name, "color": color})).unwrap(); - assert_eq!(created["name"], name); - } - let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap(); - let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap()); - app.run("selection.set", json!({"ids": [fid]})).unwrap(); - let text_fill = |app: &crate::DesignApp| { - let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone(); - st.char_format_at(2).over.fill.clone() - }; - let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone(); - assert!(!crate::panels::colors_affect_text(&app)); - crate::panels::apply_swatch(&mut app, false, "C=100 M=0 Y=0 K=0", None).unwrap(); - assert_eq!(frame_fill(&app), "C=100 M=0 Y=0 K=0"); - assert_eq!(text_fill(&app), None); - let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap(); - assert_eq!(r["on"], true, "toggles on"); - assert!(crate::panels::colors_affect_text(&app)); - crate::panels::apply_swatch(&mut app, false, "C=0 M=100 Y=0 K=0", Some(0.5)).unwrap(); - assert_eq!(frame_fill(&app), "C=100 M=0 Y=0 K=0", "the frame is left alone"); - assert_eq!(text_fill(&app).as_deref(), Some("C=0 M=100 Y=0 K=0")); - assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("C=0 M=100 Y=0 K=0".to_string(), 0.5))); - } - - #[test] - fn transform_menu_items_open_their_dialogs() { - for id in ["transform.move", "transform.scale", "transform.rotate", "transform.shear"] { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - activate(&mut app, id, &Value::Null); - let dialog = app.ui.dialog.as_ref().map(|d| d.id.clone()); - assert_eq!(dialog.as_deref(), Some(format!("cmd:{id}").as_str()), "{id} opens its dialog"); - } - } - - #[test] - fn pdf_export_menu_item_opens_the_dialog_or_exports() { - // No params: the menu item opens the options dialog. - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - activate(&mut app, "app.exportPdf", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfExport")); - // Explicit options: programmatic callers still export directly, opening no dialog. - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - activate(&mut app, "app.exportPdf", &json!({"path": "/tmp/x.pdf"})); - assert!(app.ui.dialog.is_none()); - } - - #[test] - fn snap_preferences_are_a_command() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let r = run_ui(&mut app, "view.snapPreferences", &json!({"smartSpacing": false, "zone": 8})).unwrap().unwrap(); - assert_eq!(r["smartSpacing"], false); - assert_eq!(r["alignEdges"], true, "unnamed switches keep their value"); - assert_eq!(r["zone"], 8.0); - assert!(!app.ui.smart_spacing && (app.ui.snap_zone - 8.0).abs() < 1e-9); - let r = run_ui(&mut app, "view.snapPreferences", &json!({"zone": -3})).unwrap().unwrap(); - assert_eq!(r["zone"], 0.0, "a negative zone turns snapping off"); - } - - /// Every command with a shortcut in effect: (command key, shortcut), in dispatch order. UI - /// commands come first: where one shares keys with an engine command (⌘N, ⌘O…) it's the one - /// with the dialog. - fn effective_shortcuts(app: &DesignApp) -> Vec<(String, String)> { - app.keymap.catalog().iter().filter_map(|b| crate::keys::shortcut(&app.keymap, &b.command).map(|s| (b.command.key(), s))).collect() - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn shortcut_edits_wait_for_the_dialog_and_the_menu_bar_owns_its_paste_chord() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - crate::shortcuts_dialog::open(&mut app, None); - for (id, p) in [ - ("window.setShortcut", json!({"id": "app.palette", "shortcut": "F2"})), - ("window.resetShortcuts", json!({})), - ("window.importShortcuts", json!({"text": ""})), - ] { - assert!(run_ui(&mut app, id, &p).unwrap().is_err(), "{id} while the dialog is open"); - } - crate::shortcuts_dialog::close(&mut app, false).unwrap(); - // A chord of the user's: the default one is the bar's from the start. - run_ui(&mut app, "window.setShortcut", &json!({"id": "edit.pasteInPlace", "shortcut": "Cmd+Alt+V", "steal": true})).unwrap().unwrap(); - let held = egui::Modifiers::COMMAND | egui::Modifiers::ALT; - app.native_menu = true; - assert_eq!(paste_chord_command(&app, held), Some("edit.pasteInPlace"), "before the bar carries it"); - app.native_shortcuts.insert("edit.pasteInPlace".into(), "Cmd+Alt+V".into()); - assert_eq!(paste_chord_command(&app, held), None, "the bar's key equivalent runs it, once"); - } - - #[test] - fn custom_shortcuts_override_defaults() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert_eq!(shortcut_of(&app, "app.preferences").as_deref(), Some("Cmd+K")); - let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "app.preferences", "shortcut": "Cmd+Alt+Shift+9"})).unwrap().unwrap(); - assert_eq!(r["shortcut"], "Cmd+Alt+Shift+9"); - assert!(effective_shortcuts(&app).contains(&("app.preferences".into(), "Cmd+Alt+Shift+9".into()))); - // Taking another command's keys reports the conflict. - let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Alt+Shift+9"})).unwrap().unwrap(); - assert_eq!(r["conflicts"], json!(["app.preferences"])); - run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": ""})).unwrap().unwrap(); - assert_eq!(shortcut_of(&app, "app.palette"), None); - assert!(run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Nope"})).unwrap().is_err()); - run_ui(&mut app, "window.resetShortcuts", &json!({})).unwrap().unwrap(); - // ⌘N is the New Document dialog, not a bare file.new. - let first_cmd_n = effective_shortcuts(&app).into_iter().find(|(_, s)| s == "Cmd+N").map(|(i, _)| i); - assert_eq!(first_cmd_n.as_deref(), Some("app.newDocumentDialog")); - assert_eq!(shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+Enter")); - assert_eq!( - crate::keys::chord_text(egui::Modifiers { command: true, shift: true, ..Default::default() }, egui::Key::K).as_deref(), - Some("Cmd+Shift+K") - ); - if cfg!(target_os = "macos") { - assert_eq!(shortcut_text("Cmd+Alt+3"), "⌥⌘3"); - assert_eq!(shortcut_text("Cmd+Shift+."), "⇧⌘."); - } else { - assert_eq!(shortcut_text("Cmd+Alt+3"), "Ctrl+Alt+3"); - } - } - - /// One frame of key presses through the shortcut dispatcher. - fn press_keys(app: &mut crate::DesignApp, ctx: &egui::Context, keys: &[(egui::Key, egui::Modifiers)]) { - let events = keys - .iter() - .flat_map(|&(key, modifiers)| { - [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }) - }) - .collect(); - ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| shortcuts(app, &ui.ctx().clone())).textures_delta.clear(); - } - - #[test] - fn shortcuts_saved_as_a_map_by_older_versions_load_unchanged() { - let saved = br#"{"shortcuts": {"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": [""]}}"#; - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui = crate::UiState::from_preferences_json(saved).unwrap(); - app.sync_keymap(); - assert_eq!(shortcut_of(&app, "app.preferences").as_deref(), Some("Cmd+Alt+Shift+9")); - assert_eq!(shortcut_of(&app, "app.palette"), None, "a removed default stays removed"); - assert_eq!(shortcut_of(&app, "file.close"), None); - assert_eq!(shortcut_of(&app, "app.save").as_deref(), Some("Cmd+S")); - // Saved again it reads back the same, in the map form an older version reads. - let resaved = serde_json::to_vec(&app.ui).unwrap(); - assert_eq!(crate::UiState::from_preferences_json(&resaved).unwrap().shortcuts, app.ui.shortcuts); - let saved: Value = serde_json::from_slice(&resaved).unwrap(); - assert_eq!(saved["shortcuts"], json!({"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": ""})); - } - - #[test] - fn panel_shortcuts_open_their_panels() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let shown = |app: &crate::DesignApp, p: &str| crate::panel_docking::showing(app, p); - assert!(!shown(&app, "layers")); - press_keys(&mut app, &ctx, &[(egui::Key::F7, egui::Modifiers::NONE)]); - assert!(shown(&app, "layers"), "F7 opens Layers"); - // A panel without a default key takes one. - let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "window.panel", "params": {"panel": "links"}, "shortcut": "Shift+F12"})) - .unwrap() - .unwrap(); - assert_eq!(r["shortcut"], "Shift+F12"); - press_keys(&mut app, &ctx, &[(egui::Key::F12, egui::Modifiers::SHIFT)]); - assert!(shown(&app, "links"), "the new key opens Links"); - } - - #[test] - fn a_reassigned_tool_key_selects_the_tool_and_the_old_key_does_not() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let none = egui::Modifiers::NONE; - run_ui(&mut app, "window.setShortcut", &json!({"id": "pen", "shortcut": "Y"})).unwrap().unwrap(); - press_keys(&mut app, &ctx, &[(egui::Key::P, none)]); - assert_eq!(app.session.tool_id(), "selection", "P no longer selects the Pen"); - press_keys(&mut app, &ctx, &[(egui::Key::Y, none)]); - assert_eq!(app.session.tool_id(), "pen"); - // Tools sharing a key take turns. - press_keys(&mut app, &ctx, &[(egui::Key::B, none)]); - assert_eq!(app.session.tool_id(), "contentCollector"); - press_keys(&mut app, &ctx, &[(egui::Key::B, none)]); - assert_eq!(app.session.tool_id(), "contentPlacer"); - } - - #[test] - fn split_window_panes_have_their_own_views() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp| { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app); - assert_eq!(run_ui(&mut app, "window.split", &json!({})).unwrap().unwrap(), json!(true)); - frame(&mut app); - frame(&mut app); - // Both panes have a canvas, each half as wide. - let r0 = app.canvas_rect.unwrap(); - let r1 = app.other_pane.as_ref().and_then(|o| o.1).unwrap(); - assert!(r0.width() < 800.0 && r1.width() < 800.0 && (r0.center().x - r1.center().x).abs() > 300.0, "{r0:?} {r1:?}"); - // Zooming the right pane leaves the left alone. - app.switch_pane(1); - let z0 = app.view().unwrap().zoom; - crate::canvas::set_zoom(&mut app, z0 * 3.0); - app.switch_pane(0); - assert!((app.view().unwrap().zoom - z0).abs() < 1e-9); - app.switch_pane(1); - assert!((app.view().unwrap().zoom - z0 * 3.0).abs() < 1e-6); - assert_eq!(run_ui(&mut app, "window.split", &json!({})).unwrap().unwrap(), json!(false)); - assert_eq!(app.pane, 0); - frame(&mut app); - } - - #[test] - fn split_window_dispatches_text_once_to_the_shared_document() { - for focus_pane in [0, 1] { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let made = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap(); - let story = made["story"].as_u64().unwrap(); - app.session.set_tool("type"); - app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); - assert!(app.session.wants_text()); - app.run("window.split", json!({"on": true})).unwrap(); - app.focus_pane = focus_pane; - - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - frame(&mut app, vec![]); - let undo_before = app.session.active().unwrap().history.undo.len(); - frame(&mut app, vec![egui::Event::Text("A".into())]); - let text = app.run("story.get", json!({"story": story})).unwrap(); - assert_eq!(text["text"], "A", "one key press with pane {focus_pane} focused"); - assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.run("story.get", json!({"story": story})).unwrap()["text"], ""); - - // A press and key arriving together must use the newly focused pane, whichever - // canvas is drawn first. Middle-click changes pane focus without moving the caret. - let other = app.other_pane.as_ref().and_then(|p| p.1).unwrap().center(); - frame(&mut app, vec![egui::Event::PointerMoved(other)]); - frame( - &mut app, - vec![ - egui::Event::PointerButton { pos: other, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE }, - egui::Event::Text("B".into()), - ], - ); - assert_eq!(app.focus_pane, 1 - focus_pane); - assert_eq!(app.run("story.get", json!({"story": story})).unwrap()["text"], "B", "a key in the pane-switch frame is dispatched once"); - assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1); - } - } - - #[test] - fn split_window_click_focus_routes_menu_zoom_but_hover_scroll_stays_local() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("window.split", json!({"on": true})).unwrap(); - let ctx = egui::Context::default(); - let mut time = 0.0; - let mut frame = |app: &mut crate::DesignApp, events| { - time += 0.1; - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - time: Some(time), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - for _ in 0..3 { - frame(&mut app, vec![]); - } - let left = app.canvas_rect.unwrap().center(); - let right = app.other_pane.as_ref().and_then(|p| p.1).unwrap().center(); - let cameras = |app: &mut crate::DesignApp| { - let current = app.pane; - app.switch_pane(0); - let left = *app.view().unwrap(); - app.switch_pane(1); - let right = *app.view().unwrap(); - app.switch_pane(current); - [left, right] - }; - let button = - |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(&mut app, vec![egui::Event::PointerMoved(right)]); - frame(&mut app, vec![button(right, true)]); - frame(&mut app, vec![button(right, false)]); - assert_eq!((app.pane, app.focus_pane), (1, 1)); - let before = cameras(&mut app); - app.run("view.zoom", json!({"zoom": 2.0})).unwrap(); - let zoomed = cameras(&mut app); - assert_eq!(zoomed[0], before[0], "menu zoom leaves the other camera alone"); - assert!((zoomed[1].zoom - 2.0).abs() < 1e-9); - - frame(&mut app, vec![egui::Event::PointerMoved(left)]); - frame( - &mut app, - vec![egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -40.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }], - ); - let scrolled = cameras(&mut app); - assert_eq!(scrolled[1], zoomed[1], "hover scroll leaves the focused camera alone"); - assert_ne!(scrolled[0].origin, zoomed[0].origin); - assert_eq!((app.pane, app.focus_pane), (1, 1), "hovering does not move menu focus"); - - frame(&mut app, vec![button(left, true)]); - frame(&mut app, vec![button(left, false)]); - assert_eq!((app.pane, app.focus_pane), (0, 0)); - app.run("view.zoom", json!({"zoom": 1.0})).unwrap(); - let final_views = cameras(&mut app); - assert!((final_views[0].zoom - 1.0).abs() < 1e-9); - assert_eq!(final_views[1], scrolled[1]); - } - - #[test] - fn split_window_contextual_bars_have_independent_widget_ids() { - fn id_warnings(shape: &egui::Shape, found: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| id_warnings(shape, found)), - egui::Shape::Text(text) if text.galley.text().contains("use of widget ID") => found.push(text.galley.text().to_string()), - _ => {} - } - } - - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - for rect in [[36, 36, 280, 180], [300, 36, 550, 180]] { - app.run("frame.create", json!({"rect": rect, "content": "unassigned"})).unwrap(); - } - app.run("edit.selectAll", json!({})).unwrap(); - app.run("window.split", json!({"on": true})).unwrap(); - let ctx = egui::Context::default(); - ctx.options_mut(|options| options.warn_on_id_clash = true); - let mut warnings = Vec::new(); - for _ in 0..4 { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut output = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - warnings.clear(); - for shape in &output.shapes { - id_warnings(&shape.shape, &mut warnings); - } - output.textures_delta.clear(); - } - assert!(warnings.is_empty(), "both bars reused the same interactive widget IDs: {warnings:?}"); - let bars: Vec<_> = (0_u8..2) - .map(|pane| ctx.memory(|memory| memory.area_rect(egui::Id::unique(("task_bar", egui::ViewportId::ROOT, pane)))).unwrap()) - .collect(); - assert!(!bars[0].intersects(bars[1]), "each pane keeps its own bar: {bars:?}"); - } - - #[test] - fn show_document_grid_toggles_from_the_grids_and_guides_menu() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let tree = menu_tree(); - let mut items = vec![]; - for (_, entries) in &tree { - walk(entries, &mut items); - } - assert!(items.iter().any(|(label, id, _)| id == "view.documentGrid" && label == "Show/Hide Document Grid")); - assert_eq!(shortcut_of(&app, "view.documentGrid").as_deref(), Some("Cmd+'")); - assert_eq!(checked(&app, "view.documentGrid", &json!({})), Some(false)); - assert_eq!(run_ui(&mut app, "view.documentGrid", &json!({})).unwrap().unwrap(), json!(true)); - assert!(app.ui.document_grid); - assert_eq!(checked(&app, "view.documentGrid", &json!({})), Some(true)); - run_ui(&mut app, "view.documentGrid", &json!({})).unwrap().unwrap(); - assert!(!app.ui.document_grid); - } - - #[test] - fn interface_language_switches_and_validates() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - run_ui(&mut app, "app.language", &json!({"lang": "de"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "de"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "de"})), Some(true)); - assert!(run_ui(&mut app, "app.language", &json!({"lang": "xx"})).unwrap().is_err()); - assert_eq!(app.ui.language, "de"); - // The language is set in Preferences, not from a menu; without `lang` the command opens it. - let mut items = Vec::new(); - for (_, entries) in menu_tree() { - walk(&entries, &mut items); - } - assert!(!items.iter().any(|(_, id, _)| id == "app.language"), "no menu item sets the language"); - run_ui(&mut app, "app.language", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); - assert_eq!(app.ui.language, "de"); - } - - #[test] - fn every_interface_language_is_selectable_persisted_and_keeps_document_data() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мої слова · Zażółć gęślą jaźń"})).unwrap(); - let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); - for (code, _) in crate::i18n::LANGUAGES { - run_ui(&mut app, "app.language", &json!({"lang": code})).unwrap().unwrap(); - assert_eq!(app.ui.language, *code); - assert_eq!(checked(&app, "app.language", &json!({"lang": code})), Some(true), "{code}"); - assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(), "{code}"); - let bytes = serde_json::to_vec(&app.ui).unwrap(); - let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(restored.language, *code); - } - } - - #[test] - fn arabic_dialog_and_language_switch_keep_finite_widget_geometry() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp| { - for _ in 0..4 { - let mut output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))), - max_texture_side: Some(8192), - ..Default::default() - }, - |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - ); - output.textures_delta.clear(); - } - }; - app.run("app.language", json!({"lang": "ar"})).unwrap(); - frame(&mut app); - app.run("app.newDocumentDialog", json!({})).unwrap(); - frame(&mut app); // egui asserts that all allocated rectangles are finite. - crate::dialogs::confirm(&mut app).unwrap(); - frame(&mut app); - assert_eq!(app.session.documents().len(), 1); - for lang in ["uk", "ru", "zh", "", "ar", "pt-br", "it", "cs", "pl", "ka"] { - app.run("app.language", json!({"lang": lang})).unwrap(); - frame(&mut app); - } - } - - #[test] - fn story_direction_is_checked() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 400], "content": "text", "text": "縦", "vertical": true})).unwrap(); - assert_eq!(checked(&app, "type.storyDirection", &json!({"vertical": true})), Some(true)); - assert_eq!(checked(&app, "type.storyDirection", &json!({"vertical": false})), Some(false)); - } - - #[test] - fn proof_setup_and_colors() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert_eq!(checked(&app, "view.proofColors", &Value::Null), Some(false)); - let r = run_ui(&mut app, "view.proofSetup", &json!({"target": "deuteranopia"})).unwrap().unwrap(); - assert_eq!(r["on"], true); - assert_eq!(checked(&app, "view.proofSetup", &json!({"target": "deuteranopia"})), Some(true)); - run_ui(&mut app, "view.proofSetup", &json!({"simulatePaper": "toggle"})).unwrap().unwrap(); - assert!(app.ui.proof_setup.simulate_paper); - run_ui(&mut app, "view.proofColors", &json!({})).unwrap().unwrap(); - assert!(!app.ui.proof_colors); - assert!(run_ui(&mut app, "view.proofSetup", &json!({"target": "nope"})).unwrap().is_err()); - } - - #[test] - fn lock_guides_and_lock_column_guides_are_checked_in_grids_and_guides() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let view = menu_ids("View"); - assert!(view.contains(&"view.lockGuides") && view.contains(&"view.lockColumnGuides")); - assert_eq!(ui_label("view.lockGuides").and_then(|c| c.1), Some("Cmd+Alt+;")); - // Lock Guides: off at first, toggles, and `on` sets it. - assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(false)); - assert_eq!(app.run("view.lockGuides", json!({})).unwrap(), json!(true)); - assert!(app.ui.guides_locked); - assert_eq!(app.run("view.lockGuides", json!({"on": true})).unwrap(), json!(true)); - assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(true)); - assert_eq!(app.run("view.lockGuides", json!({"on": false})).unwrap(), json!(false)); - // Lock Column Guides: the document's setting, on in new documents. - assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(true)); - app.run("view.lockColumnGuides", json!({})).unwrap(); - assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(false)); - } - - #[test] - fn fitting_has_indesigns_shortcuts() { - // LYH Studio episode 6 (7:00): "Fit Content to Frame (Ctrl + Shift + Alt + C)" fills the - // photo frames proportionally. - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png(); - let f = app.run("frame.create", json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].as_u64().unwrap(); - app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "a.png", "frame": f})).unwrap(); - app.run("selection.set", json!({"ids": [f]})).unwrap(); - let width = |app: &crate::DesignApp| { - let it = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone(); - let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("graphic") }; - it.xf.transform_rect_bbox(g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1))).width() - }; - for (id, keys) in [ - ("fit.fillFrameProportionally", "Cmd+Alt+Shift+C"), - ("fit.contentProportionally", "Cmd+Alt+Shift+E"), - ("fit.frameToContent", "Cmd+Alt+C"), - ("fit.contentToFrame", "Cmd+Alt+E"), - ("fit.centerContent", "Cmd+Shift+E"), - ] { - assert_eq!(shortcut_of(&app, id).as_deref(), Some(keys)); - } - let ctx = egui::Context::default(); - let press = |app: &mut crate::DesignApp, key: egui::Key| { - let modifiers = - egui::Modifiers { alt: true, ctrl: !cfg!(target_os = "macos"), shift: true, mac_cmd: cfg!(target_os = "macos"), command: true }; - let input = egui::RawInput { - events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| shortcuts(app, &ui.ctx().clone())); - out.textures_delta.clear(); - }; - press(&mut app, egui::Key::C); - assert!((width(&app) - 400.0).abs() < 1e-6, "filled: {}", width(&app)); - press(&mut app, egui::Key::E); - assert!((width(&app) - 200.0).abs() < 1e-6, "fitted: {}", width(&app)); - } - - #[test] - fn tab_and_presentation_hide_floating_panels_too() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp| { - for _ in 0..2 { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - } - }; - // The docked panel's tab and a floating panel group. - let tab = crate::panel_docking::tab_id("preflight"); - let docked = || ctx.read_response(tab).is_some(); - let group = crate::panel_docking::floating_layer("preflight"); - let shown = |layer: egui::LayerId| ctx.memory(|m| m.areas().is_visible(&layer)); - let toggles = [ - ("window.hidePanels", json!({}), json!({})), - ("window.hidePanelsExceptTools", json!({}), json!({})), - ("view.screenMode", json!({"mode": "presentation"}), json!({"mode": "normal"})), - ]; - app.run("window.panel", json!({"panel": "preflight"})).unwrap(); - frame(&mut app); - assert!(docked()); - for (id, hide, show) in &toggles { - app.run(id, hide.clone()).unwrap(); - frame(&mut app); - assert!(!docked(), "{id} hides the dock"); - app.run(id, show.clone()).unwrap(); - frame(&mut app); - assert!(docked(), "{id} again brings it back"); - } - app.run("window.floatPanel", json!({"panel": "preflight", "x": 400, "y": 200})).unwrap(); - frame(&mut app); - assert!(app.ui.docking.is_some() && shown(group)); - for (id, hide, show) in &toggles { - app.run(id, hide.clone()).unwrap(); - frame(&mut app); - assert!(!shown(group), "{id} hides the floating panel"); - app.run(id, show.clone()).unwrap(); - frame(&mut app); - assert!(shown(group), "{id} again brings it back"); - } - } - - #[test] - fn tab_hides_panels_and_documents_cycle() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert_eq!(shortcut_of(&app, "window.hidePanels").as_deref(), Some("Tab")); - run_ui(&mut app, "window.hidePanels", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.hidden_panels, 1); - run_ui(&mut app, "window.hidePanelsExceptTools", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.hidden_panels, 2); - run_ui(&mut app, "window.hidePanelsExceptTools", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.hidden_panels, 0); - for _ in 0..3 { - app.session.execute("file.new", &json!({})).unwrap(); - } - assert_eq!(app.session.active_index(), Some(2)); - run_ui(&mut app, "window.nextDocument", &json!({})).unwrap().unwrap(); - assert_eq!(app.session.active_index(), Some(0)); - run_ui(&mut app, "window.previousDocument", &json!({})).unwrap().unwrap(); - assert_eq!(app.session.active_index(), Some(2)); - } - - #[test] - fn rotate_spread_view() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 3})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp| { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app); - frame(&mut app); - assert_eq!(run_ui(&mut app, "view.rotateSpread", &json!({"angle": 90})).unwrap().unwrap(), json!(90)); - frame(&mut app); - // Only the spread in view turns: its canvas footprint swaps width and height. - let d = app.session.active().unwrap().doc.clone(); - let turned: Vec = d.spreads.iter().enumerate().filter(|(_, sp)| sp.pages[0].view_rotation == 1).map(|(i, _)| i).collect(); - assert_eq!(turned.len(), 1); - let layout = designcraft_tools::CanvasLayout::new(&d, false); - let slot = layout.slots[turned[0]]; - let b = d.spreads[turned[0]].bounds(); - assert!((slot.bounds.width() - b.height()).abs() < 1e-6 && (slot.bounds.height() - b.width()).abs() < 1e-6); - assert_eq!(checked(&app, "view.rotateSpread", &json!({"angle": 0})), Some(false)); - run_ui(&mut app, "view.rotateSpread", &json!({"angle": 0})).unwrap().unwrap(); - assert_eq!(checked(&app, "view.rotateSpread", &json!({"angle": 0})), Some(true)); - frame(&mut app); - } - - #[test] - fn hand_tool_hold_starts_power_zoom() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, t: f64, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - time: Some(t), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app, 0.0, vec![]); - frame(&mut app, 0.05, vec![]); - app.select_tool("hand"); - let r = app.canvas_rect.unwrap(); - let p = r.center(); - let z0 = app.view().unwrap().zoom; - frame(&mut app, 0.1, vec![egui::Event::PointerMoved(p)]); - frame( - &mut app, - 0.2, - vec![egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }], - ); - frame(&mut app, 0.4, vec![]); - assert!(app.power_zoom.is_none(), "not yet"); - frame(&mut app, 0.8, vec![]); - assert!(app.power_zoom.is_some(), "holding still starts Power Zoom"); - frame( - &mut app, - 0.9, - vec![egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }], - ); - assert!(app.power_zoom.is_none()); - assert!((app.view().unwrap().zoom - z0).abs() < 1e-9, "back at the zoom it started from"); - } - - #[test] - fn middle_drag_pans_with_any_tool() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // A drawing tool: a primary drag would make a frame, a middle drag must not. - app.select_tool("rectangleFrame"); - let p = app.canvas_rect.unwrap().center(); - let v0 = *app.view().unwrap(); - let items = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum::(); - let items0 = items(&app); - let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; - frame(&mut app, vec![egui::Event::PointerMoved(p), button(p, true)]); - for i in 1..=8 { - frame(&mut app, vec![egui::Event::PointerMoved(p + egui::vec2(10.0 * i as f32, 5.0 * i as f32))]); - } - frame(&mut app, vec![button(p + egui::vec2(80.0, 40.0), false)]); - let v = *app.view().unwrap(); - assert!((v.zoom - v0.zoom).abs() < 1e-9, "panning keeps the zoom"); - assert!(v.origin.x < v0.origin.x && v.origin.y < v0.origin.y, "dragging right/down moves the view: {v0:?} -> {v:?}"); - assert_eq!(items(&app), items0, "the tool saw nothing"); - } - - #[test] - fn layout_menu_goes_through_pages_and_spreads_with_their_shortcuts() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap(); - let spread = |app: &crate::DesignApp| { - let st = app.session.active().unwrap(); - crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // The Layout menu lists them, as InDesign's does, before Go to Page. - let layout = MENUS.iter().find(|m| m.0 == "Layout").unwrap().1; - let at = |id: &str| layout.iter().position(|e| e.starts_with(&format!("ui:{id}"))).unwrap(); - assert!(at("view.firstPage") < at("view.previousPage")); - assert!(at("view.previousPage") < at("view.nextPage")); - assert!(at("view.nextPage") < at("view.lastPage")); - assert!(at("view.lastPage") < at("view.nextSpread")); - assert!(at("view.nextSpread") < at("view.previousSpread")); - assert!(at("view.previousSpread") < at("view.goToPage")); - let shift = egui::Modifiers::SHIFT; - let cmd_shift = egui::Modifiers { shift: true, command: true, ctrl: true, ..Default::default() }; - let alt = egui::Modifiers::ALT; - // Pages 1 | 2-3 | 4-5 | 6-7. - frame(&mut app, key(egui::Key::PageDown, shift)); - assert_eq!(page(&app), 1, "Next Page"); - frame(&mut app, key(egui::Key::PageDown, shift)); - assert_eq!(page(&app), 2, "Next Page goes to the right page of the spread"); - frame(&mut app, key(egui::Key::PageUp, shift)); - assert_eq!(page(&app), 1, "Previous Page"); - frame(&mut app, key(egui::Key::PageDown, cmd_shift)); - assert_eq!(page(&app), 6, "Last Page"); - frame(&mut app, key(egui::Key::PageDown, shift)); - assert_eq!(page(&app), 6, "Next Page stops at the last page"); - frame(&mut app, key(egui::Key::PageUp, cmd_shift)); - assert_eq!(page(&app), 0, "First Page"); - frame(&mut app, key(egui::Key::PageUp, shift)); - assert_eq!(page(&app), 0, "Previous Page stops at the first page"); - frame(&mut app, key(egui::Key::PageDown, alt)); - assert_eq!(spread(&app), 1, "Next Spread"); - frame(&mut app, key(egui::Key::PageDown, alt)); - frame(&mut app, key(egui::Key::PageDown, alt)); - frame(&mut app, key(egui::Key::PageDown, alt)); - assert_eq!(spread(&app), 3, "Next Spread stops at the last spread"); - frame(&mut app, key(egui::Key::PageUp, alt)); - assert_eq!(spread(&app), 2, "Previous Spread"); - // The spread is centred, the zoom kept. - let zoom = app.view().unwrap().zoom; - app.run("view.previousSpread", json!({})).unwrap(); - let st = app.session.active().unwrap(); - let slot = designcraft_tools::layout::CanvasLayout::new(&st.doc, false).slots[1]; - let (v, r) = (*app.view().unwrap(), app.canvas_rect.unwrap()); - let centre = (v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom); - assert!((centre.0 - slot.bounds.center().x).abs() < 1e-6 && (centre.1 - slot.bounds.center().y).abs() < 1e-6); - assert_eq!(v.zoom, zoom); - } - - #[test] - fn go_back_and_go_forward_retrace_the_pages_viewed() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap(); - let can = |app: &crate::DesignApp| (menu_enabled(app, "view.goBack"), menu_enabled(app, "view.goForward")); - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // In the Layout menu after Go to Page. - let layout = MENUS.iter().find(|m| m.0 == "Layout").unwrap().1; - let at = |id: &str| layout.iter().position(|e| *e == format!("ui:{id}")).unwrap(); - assert_eq!(at("view.goBack"), at("view.goToPage") + 1); - assert_eq!(at("view.goForward"), at("view.goBack") + 1); - assert_eq!(can(&app), (false, false), "one page viewed: nowhere to go"); - let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; - let cmd_shift = egui::Modifiers { shift: true, ..cmd }; - let shift = egui::Modifiers::SHIFT; - // Pages viewed: 1, 5, 7. - app.run("view.goToPage", json!({"page": 5})).unwrap(); - frame(&mut app, vec![]); - frame(&mut app, key(egui::Key::PageDown, cmd_shift)); - assert_eq!(page(&app), 6); - frame(&mut app, vec![]); - assert_eq!(can(&app), (true, false)); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(page(&app), 4, "Go Back"); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(page(&app), 0, "Go Back again"); - frame(&mut app, vec![]); - assert_eq!(can(&app), (false, true), "back at the first page viewed"); - frame(&mut app, key(egui::Key::PageDown, cmd)); - assert_eq!(page(&app), 4, "Go Forward"); - frame(&mut app, key(egui::Key::PageDown, cmd)); - assert_eq!(page(&app), 6, "Go Forward again"); - frame(&mut app, vec![]); - assert_eq!(can(&app), (true, false)); - // After going back, viewing another page drops the pages ahead. - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(page(&app), 4); - frame(&mut app, key(egui::Key::PageDown, shift)); - assert_eq!(page(&app), 5, "Next Page"); - frame(&mut app, vec![]); - assert_eq!(can(&app), (true, false), "nothing ahead after a new page"); - frame(&mut app, key(egui::Key::PageDown, cmd)); - assert_eq!(page(&app), 5, "Go Forward does nothing"); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(page(&app), 4, "Go Back returns to the page before Next Page"); - } - - #[test] - fn go_back_waits_for_the_view_to_be_fitted() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp| { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app); - frame(&mut app); - app.run("view.goToPage", json!({"page": 5})).unwrap(); - frame(&mut app); - assert!(menu_enabled(&app, "view.goBack")); - // Leaving parent pages through the Pages panel: the canvas refits on the next frame. - app.view_mut().unwrap().fitted = false; - assert!(!menu_enabled(&app, "view.goBack"), "the refit would replace where Go Back went"); - crate::canvas::go_through_history(&mut app, -1); - frame(&mut app); - assert!(menu_enabled(&app, "view.goBack"), "the unfitted Go Back used no history entry"); - } - - #[test] - fn next_spread_at_the_last_spread_is_no_jump() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap(); - let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; - let alt = egui::Modifiers::ALT; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // Pages 1 | 2-3 | 4-5 | 6-7: page 6 is the left page of the last spread. - app.run("view.goToPage", json!({"page": 6})).unwrap(); - frame(&mut app, vec![]); - assert_eq!(page(&app), 5); - // Next Spread has no spread to go to; centring the last one moves the view to its fold. - frame(&mut app, key(egui::Key::PageDown, alt)); - frame(&mut app, key(egui::Key::PageDown, alt)); - assert_ne!(page(&app), 5, "the view moved to the right page"); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(page(&app), 0, "Go Back returns to the page before Go to Page"); - assert!(!menu_enabled(&app, "view.goBack")); - } - - #[test] - fn go_back_returns_to_the_view_a_jump_left_and_scrolling_adds_no_entry() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - let spread = |app: &crate::DesignApp| { - let st = app.session.active().unwrap(); - crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() - }; - let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; - let alt = egui::Modifiers::ALT; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // Pages 1 | 2-3 | 4-5 | 6-7. Spread 2-3 fitted: the view centre is on the fold. - frame(&mut app, key(egui::Key::PageDown, alt)); - app.run("view.fitSpread", json!({})).unwrap(); - frame(&mut app, vec![]); - let before = *app.view().unwrap(); - frame(&mut app, key(egui::Key::PageDown, alt)); - assert_eq!(spread(&app), 2, "Next Spread"); - frame(&mut app, key(egui::Key::PageUp, cmd)); - let v = *app.view().unwrap(); - assert!((v.origin - before.origin).hypot() < 1e-6, "Go Back shows the spread as it was: {:?} vs {:?}", v.origin, before.origin); - assert_eq!(v.zoom, before.zoom); - // Zoomed in after the jump: Go Back keeps the magnification in use, as InDesign's does, and - // centres the same place. - let centre = |app: &crate::DesignApp| { - let (v, r) = (app.view().unwrap(), app.canvas_rect.unwrap()); - designcraft_geom::Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom) - }; - let place = centre(&app); - frame(&mut app, key(egui::Key::PageDown, alt)); - app.run("view.zoomIn", json!({})).unwrap(); - let zoomed = app.view().unwrap().zoom; - assert!(zoomed > before.zoom); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(app.view().unwrap().zoom, zoomed, "the zoom in use is kept"); - assert!((centre(&app) - place).hypot() < 1e-6, "the same place: {:?} vs {place:?}", centre(&app)); - // Scrolling down two spreads is not a jump: Go Forward keeps its page, and Go Back skips - // from where the scroll ended straight to the page before the first jump. - let slots = designcraft_tools::layout::CanvasLayout::new(&app.session.active().unwrap().doc, false).slots; - app.view_mut().unwrap().origin.y += slots[3].bounds.center().y - slots[1].bounds.center().y; - frame(&mut app, vec![]); - assert_eq!(spread(&app), 3); - assert!(menu_enabled(&app, "view.goForward"), "scrolling kept the page ahead"); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(spread(&app), 0, "Go Back"); - assert!(!menu_enabled(&app, "view.goBack"), "the scroll added no entry"); - frame(&mut app, key(egui::Key::PageDown, cmd)); - assert_eq!(spread(&app), 3, "Go Forward returns to where the scroll ended"); - frame(&mut app, key(egui::Key::PageDown, cmd)); - assert_eq!(spread(&app), 2); - } - - #[test] - fn go_back_after_presentation_returns_to_the_last_spread_presented() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - let spread = |app: &crate::DesignApp| { - let st = app.session.active().unwrap(); - crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() - }; - let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // Scrolled off the page's centre, so the place Go Back returns to is not just the page. - let view = app.view_mut().unwrap(); - view.origin.x += 40.0; - view.origin.y += 60.0; - frame(&mut app, vec![]); - assert_eq!(spread(&app), 0); - let before = *app.view().unwrap(); - // Presentation goes on to spreads 1 and 2; leaving it puts spread 0 back as it was. - app.run("view.screenMode", json!({"mode": "presentation"})).unwrap(); - frame(&mut app, vec![]); - frame(&mut app, key(egui::Key::ArrowRight, egui::Modifiers::NONE)); - frame(&mut app, key(egui::Key::ArrowRight, egui::Modifiers::NONE)); - assert_eq!(spread(&app), 2); - app.run("view.screenMode", json!({"mode": "normal"})).unwrap(); - frame(&mut app, vec![]); - assert_eq!(spread(&app), 0); - assert!(!menu_enabled(&app, "view.goForward")); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(spread(&app), 2, "Go Back shows the last spread presented"); - frame(&mut app, key(egui::Key::PageUp, cmd)); - assert_eq!(spread(&app), 0, "Go Back again, the view Presentation was entered from"); - let v = *app.view().unwrap(); - assert!((v.origin - before.origin).hypot() < 1e-6, "where it was: {:?} vs {:?}", v.origin, before.origin); - assert!(!menu_enabled(&app, "view.goBack"), "the presentation is one jump: spread 1 isn't kept"); - frame(&mut app, key(egui::Key::PageDown, cmd)); - assert_eq!(spread(&app), 2, "Go Forward"); - } - - #[test] - fn presentation_shows_one_spread_and_goes_through_them_with_keys_and_clicks() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); - app.session.execute("frame.create", &json!({"rect": [100, 100, 300, 300]})).unwrap(); - let id = app.session.active().unwrap().selection.items[0]; - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }, - ] - }; - let click = |pos: egui::Pos2, modifiers: egui::Modifiers| { - vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers }, - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers }, - ] - }; - let spread = |app: &crate::DesignApp| { - let st = app.session.active().unwrap(); - crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() - }; - // The spread fills the screen: as wide or as tall as it, centred. - let fills = |app: &crate::DesignApp| { - let st = app.session.active().unwrap(); - let b = designcraft_tools::layout::CanvasLayout::new(&st.doc, false).slots[spread(app)].bounds; - let (v, r) = (*app.view().unwrap(), app.canvas_rect.unwrap()); - let (w, h) = (b.width() * v.zoom, b.height() * v.zoom); - let x0 = (b.x0 - v.origin.x) * v.zoom; - let y0 = (b.y0 - v.origin.y) * v.zoom; - ((w - r.width() as f64).abs() < 0.01 || (h - r.height() as f64).abs() < 0.01) - && w <= r.width() as f64 + 0.01 - && h <= r.height() as f64 + 0.01 - && (x0 * 2.0 + w - r.width() as f64).abs() < 0.01 - && (y0 * 2.0 + h - r.height() as f64).abs() < 0.01 - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - // The user's own view (zoomed in, scrolled) comes back after Presentation. - let view = app.view_mut().unwrap(); - view.zoom = 2.0; - view.origin.x += 150.0; - view.origin.y += 300.0; - let before = *app.view().unwrap(); - app.run("view.screenMode", json!({"mode": "presentation"})).unwrap(); - frame(&mut app, vec![]); - frame(&mut app, vec![]); - assert_eq!(app.canvas_rect.unwrap().size(), egui::vec2(1400.0, 900.0), "the whole window"); - assert_eq!(spread(&app), 0); - assert!(fills(&app)); - let bounds = app.session.active().unwrap().doc.item(id).unwrap().bounds(); - frame(&mut app, key(egui::Key::ArrowRight)); - frame(&mut app, vec![]); - assert_eq!(spread(&app), 1, "Right Arrow shows the next spread"); - assert!(fills(&app)); - assert_eq!(app.session.active().unwrap().doc.item(id).unwrap().bounds(), bounds, "the arrow doesn't nudge the selection"); - frame(&mut app, key(egui::Key::PageDown)); - assert_eq!(spread(&app), 2, "Page Down"); - frame(&mut app, key(egui::Key::ArrowLeft)); - assert_eq!(spread(&app), 1, "Left Arrow"); - frame(&mut app, key(egui::Key::End)); - assert_eq!(spread(&app), 3, "End"); - frame(&mut app, key(egui::Key::ArrowRight)); - assert_eq!(spread(&app), 3, "the last spread stays"); - frame(&mut app, key(egui::Key::Home)); - assert_eq!(spread(&app), 0, "Home"); - frame(&mut app, key(egui::Key::PageUp)); - assert_eq!(spread(&app), 0, "the first spread stays"); - let c = app.canvas_rect.unwrap().center(); - frame(&mut app, click(c, egui::Modifiers::NONE)); - frame(&mut app, vec![]); - assert_eq!(spread(&app), 1, "a click shows the next spread"); - assert!(fills(&app)); - frame(&mut app, click(c, egui::Modifiers::SHIFT)); - frame(&mut app, vec![]); - assert_eq!(spread(&app), 0, "Shift-click the previous one"); - assert_eq!(app.session.active().unwrap().selection.items, vec![id], "clicks don't select"); - assert_eq!(app.session.tool_id(), "selection"); - // Out of Presentation, the view is the one it was entered from, and the arrow keys nudge - // again. - app.run("view.screenMode", json!({"mode": "normal"})).unwrap(); - assert_eq!(*app.view().unwrap(), before); - frame(&mut app, vec![]); - frame(&mut app, key(egui::Key::ArrowRight)); - assert_ne!(app.session.active().unwrap().doc.item(id).unwrap().bounds(), bounds); - } - - #[test] - fn tool_shortcuts_work_after_drawing_on_the_canvas() { - // Clicking the canvas gives it keyboard focus; single-key tool shortcuts must still switch - // tools without pressing Esc first (#1). - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }, - ] - }; - let button = |pos: egui::Pos2, pressed: bool| egui::Event::PointerButton { - pos, - button: egui::PointerButton::Primary, - pressed, - modifiers: Default::default(), - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - frame(&mut app, key(egui::Key::F)); - assert_eq!(app.session.tool_id(), "rectangleFrame"); - // Draw a frame. - let a = app.canvas_rect.unwrap().center(); - let b = a + egui::vec2(120.0, 80.0); - frame(&mut app, vec![egui::Event::PointerMoved(a), button(a, true)]); - for i in 1..=4 { - frame(&mut app, vec![egui::Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))]); - } - frame(&mut app, vec![button(b, false)]); - frame(&mut app, vec![]); - assert!(app.session.active().is_some_and(|d| !d.selection.items.is_empty()), "drew a frame"); - frame(&mut app, key(egui::Key::V)); - assert_eq!(app.session.tool_id(), "selection", "V switches tools straight after drawing"); - frame(&mut app, key(egui::Key::F)); - assert_eq!(app.session.tool_id(), "rectangleFrame"); - } - - #[test] - fn escape_and_shift_w_leave_presentation_for_the_previous_mode() { - // Presentation hides every control, so the keyboard must get out of it (#493). - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "graphic"})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - let selected = |app: &crate::DesignApp| app.session.active().map(|d| d.selection.items.len()).unwrap_or(0); - frame(&mut app, vec![]); - frame(&mut app, vec![]); - app.run("view.screenMode", json!({"mode": "preview"})).unwrap(); - app.select_tool("rectangleFrame"); - assert_eq!(selected(&app), 1, "the new frame is selected"); - - frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT)); - assert_eq!(app.ui.screen_mode, ScreenMode::Presentation, "Shift+W enters Presentation"); - assert_eq!(app.session.tool_id(), "rectangleFrame", "Shift+W is not a tool shortcut"); - frame(&mut app, key(egui::Key::Escape, egui::Modifiers::NONE)); - assert_eq!(app.ui.screen_mode, ScreenMode::Preview, "Esc returns to the mode Presentation was entered from"); - assert_eq!(app.session.tool_id(), "rectangleFrame", "Esc only left Presentation"); - assert_eq!(selected(&app), 1, "Esc only left Presentation"); - - frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT)); - frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT)); - assert_eq!(app.ui.screen_mode, ScreenMode::Preview, "Shift+W leaves Presentation for the previous mode"); - - app.run("view.screenMode", json!({"mode": "presentation"})).unwrap(); - frame(&mut app, key(egui::Key::W, egui::Modifiers::NONE)); - assert_eq!(app.ui.screen_mode, ScreenMode::Normal, "W from any mode but Normal goes to Normal"); - - // Outside Presentation, Esc keeps its usual meaning. - frame(&mut app, key(egui::Key::Escape, egui::Modifiers::NONE)); - assert_eq!(app.ui.screen_mode, ScreenMode::Normal); - assert_eq!(app.session.tool_id(), "selection"); - } - - #[test] - fn cmd_plus_zooms_the_canvas_not_the_window() { - // A German keyboard has its own + key, so Cmd+= arrives as Plus; it must zoom the canvas like - // Cmd+- does, not hand the key to egui's whole-window zoom. - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let key = |k: egui::Key, modifiers: egui::Modifiers| { - vec![ - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, - ] - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - let scale = ctx.zoom_factor(); - for (k, m, zooms_in) in [ - (egui::Key::Plus, egui::Modifiers::COMMAND, true), - (egui::Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, true), - (egui::Key::Equals, egui::Modifiers::COMMAND, true), - (egui::Key::Minus, egui::Modifiers::COMMAND, false), - ] { - let z0 = app.view().unwrap().zoom; - frame(&mut app, key(k, m)); - frame(&mut app, vec![]); - let z = app.view().unwrap().zoom; - assert!(if zooms_in { z > z0 } else { z < z0 }, "{k:?} {m:?}: {z0} -> {z}"); - assert_eq!(ctx.zoom_factor(), scale, "{k:?} {m:?} leaves the UI scale alone"); - } - // With a native menu (macOS) its accelerator takes Cmd+= itself, but never sees the Plus key - // standing in for = (#781). - app.native_shortcuts.insert("view.zoomIn".to_string(), shortcut_of(&app, "view.zoomIn").unwrap()); - for (k, m, zooms_in) in [ - (egui::Key::Plus, egui::Modifiers::COMMAND, true), - (egui::Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, true), - (egui::Key::Equals, egui::Modifiers::COMMAND, false), - ] { - let z0 = app.view().unwrap().zoom; - frame(&mut app, key(k, m)); - frame(&mut app, vec![]); - let z = app.view().unwrap().zoom; - assert_eq!(z > z0, zooms_in, "native menu, {k:?} {m:?}: {z0} -> {z}"); - } - // A shortcut the user set runs here until the native menu bar carries it as its key - // equivalent; then only the bar runs it, once. - run_ui(&mut app, "window.setShortcut", &json!({"id": "view.zoomOut", "shortcut": "Cmd+9"})).unwrap().unwrap(); - let zooms_out = |app: &mut crate::DesignApp, k: egui::Key| { - let z0 = app.view().unwrap().zoom; - frame(app, key(k, egui::Modifiers::COMMAND)); - frame(app, vec![]); - app.view().unwrap().zoom < z0 - }; - assert!(zooms_out(&mut app, egui::Key::Num9), "no native bar: the app runs it"); - app.native_shortcuts.insert("view.zoomOut".to_string(), "Cmd+9".to_string()); - assert!(!zooms_out(&mut app, egui::Key::Num9), "the bar's key equivalent runs only there"); - // A second binding of a command whose first the bar holds runs here. - let cmd = craft_keymap::CommandRef::new("view.zoomOut"); - let bindings = ["Cmd+F11", "Cmd+9"].map(|s| craft_keymap::Binding::parse(s).unwrap()).to_vec(); - app.keymap.set_bindings(&cmd, bindings, craft_keymap::Policy::Steal).unwrap(); - app.ui.shortcuts = app.keymap.overrides().clone(); - app.native_shortcuts.insert("view.zoomOut".to_string(), "Cmd+F11".to_string()); - assert!(!zooms_out(&mut app, egui::Key::F11), "the bar runs its own key"); - assert!(zooms_out(&mut app, egui::Key::Num9), "the second binding runs in the app"); - } - - #[test] - fn the_quick_apply_shortcut_opens_it_without_running_an_entry() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - let cmd_return = - |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - frame(&mut app, vec![cmd_return(true), cmd_return(false)]); - frame(&mut app, vec![]); - assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open"); - assert_eq!(app.session.documents().len(), 1, "the first entry (New Document) didn't run"); - // Pressing the shortcut again, or holding it until it repeats, doesn't run it either. - frame(&mut app, vec![cmd_return(true), cmd_return(false)]); - let repeat = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::COMMAND }; - frame(&mut app, vec![repeat, cmd_return(false)]); - assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open"); - assert_eq!(app.session.documents().len(), 1, "a second ⌘Return or a repeat doesn't run the first entry"); - // A plain Return still does. - let enter = - |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; - frame(&mut app, vec![enter(true), enter(false)]); - assert_eq!(app.ui.palette, None, "Return runs the first entry and closes Quick Apply"); - assert_eq!(app.session.documents().len(), 2); - } - - #[test] - fn quick_apply_rows_are_left_aligned() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - app.ui.palette = Some(String::new()); - let ctx = egui::Context::default(); - let mut shapes = Vec::new(); - for _ in 0..3 { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - shapes = out.shapes; - } - let label_x = |label: &str| { - // The palette is painted last, over anything else with the same text. - shapes.iter().rev().find_map(|s| match &s.shape { - egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos.x), - _ => None, - }) - }; - // Rows that show a shortcut or a style kind, and rows that show neither, among the first visible ones. - let items = quick_apply_items(&app.session, "", false); - let first = items.iter().take(10); - let plain = first.clone().find(|it| it.shortcut.is_none() && it.kind.is_empty()).expect("a row without a shortcut"); - let with_sc = first.clone().find(|it| it.shortcut.is_some()).expect("a row with a shortcut"); - let (a, b) = (label_x(&plain.label).expect("plain row drawn"), label_x(&with_sc.label).expect("shortcut row drawn")); - assert!((a - b).abs() < 0.5, "{:?} at x {a}, {:?} at x {b}", plain.label, with_sc.label); - } - - #[test] - fn copy_and_paste_keys_work_for_objects_without_a_native_menu() { - // Without a native menu the paste key arrives only as a paste event, which needs text on - // the system clipboard (#164, #185). - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp, events: Vec| { - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - out.platform_output.commands - }; - let count = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads[0].items.len(); - frame(&mut app, vec![]); - frame(&mut app, vec![]); - let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone(); - app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); - let n = count(&app); - let copied = frame(&mut app, vec![egui::Event::Copy]) - .into_iter() - .find_map(|c| match c { - egui::OutputCommand::CopyText(t) => Some(t), - _ => None, - }) - .expect("copying objects puts text on the system clipboard"); - assert!(!copied.is_empty()); - frame(&mut app, vec![egui::Event::Paste(copied.clone())]); - assert_eq!(count(&app), n + 1, "the paste key pastes the copied rectangle"); - - // Pasting into text anchors the copied object; the clipboard placeholder isn't typed. - let r = app.session.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Hello"})).unwrap(); - let story = r["story"].as_u64().unwrap(); - app.session.execute("tool.select", &json!({"tool": "type"})).unwrap(); - app.session.execute("text.select", &json!({"story": story, "anchor": 5, "focus": 5})).unwrap(); - frame(&mut app, vec![egui::Event::Paste(copied.clone())]); - // Shift pastes without formatting. - frame(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), egui::Event::Paste(copied)]); - let text = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(story)).unwrap().text.clone(); - assert!(text.starts_with("Hello") && !text.contains('\u{FFFC}'), "{text:?}"); - assert!(text.contains(designcraft_doc::OBJECT_MARK), "{text:?}"); - } - - #[test] - fn paste_with_no_insertion_point_makes_a_text_frame_from_other_apps_text() { - // #518: text copied in another app pastes as a new, selected text frame; the text an - // object copy stands for still pastes the objects. One paste each way, with and without - // a native menu. - let selected_text = |app: &crate::DesignApp| { - let d = app.session.active().unwrap(); - let it = d.doc.item(*d.selection.items.first()?)?; - Some(d.doc.story(it.text_frame()?.story)?.text.clone()) - }; - let ctx = egui::Context::default(); - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - native_frame(&mut app, &ctx, vec![], None); - native_frame(&mut app, &ctx, vec![], None); - // The paste keys without a native menu: a paste event. - native_frame(&mut app, &ctx, vec![egui::Event::Paste("From elsewhere".into())], None); - assert_eq!(document_items(&app), (1, 1), "pasted once"); - assert_eq!(selected_text(&app).as_deref(), Some("From elsewhere")); - let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone(); - app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); - let copied = native_frame(&mut app, &ctx, vec![egui::Event::Copy], None) - .platform_output - .commands - .into_iter() - .find_map(|c| match c { - egui::OutputCommand::CopyText(t) => Some(t), - _ => None, - }) - .expect("copying objects puts text on the system clipboard"); - native_frame(&mut app, &ctx, vec![egui::Event::Paste(copied)], None); - assert_eq!(document_items(&app), (3, 1)); - assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame"); - - // A native menu: Paste reads the system clipboard. - let clip = std::rc::Rc::new(std::cell::RefCell::new(Some("Menu text".to_string()))); - let read = clip.clone(); - let services = crate::Services { clipboard_text: Some(Box::new(move || read.borrow().clone())), ..Default::default() }; - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), services); - app.native_menu = true; - app.session.execute("file.new", &json!({})).unwrap(); - native_frame(&mut app, &ctx, vec![], None); - native_frame(&mut app, &ctx, vec![], None); - native_frame(&mut app, &ctx, vec![], Some("edit.paste")); - native_frame(&mut app, &ctx, vec![], None); - assert_eq!(document_items(&app), (1, 1), "pasted once"); - assert_eq!(selected_text(&app).as_deref(), Some("Menu text")); - // Objects copied since that text was copied paste as objects. - let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone(); - app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); - native_frame(&mut app, &ctx, vec![], Some("edit.copy")); - native_frame(&mut app, &ctx, vec![], Some("edit.paste")); - assert_eq!(document_items(&app), (3, 1)); - assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame"); - // Newer text from another app wins. - *clip.borrow_mut() = Some("Newer".into()); - native_frame(&mut app, &ctx, vec![], Some("edit.paste")); - assert_eq!(document_items(&app), (4, 1)); - assert_eq!(selected_text(&app).as_deref(), Some("Newer")); - } - - #[test] - fn sample_scripts_run() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - for (name, text) in app.ui.scripts.clone() { - let r = app.session.execute("script.run", &json!({"text": text})); - assert!(r.is_ok(), "{name}: {r:?}"); - } - } - - #[test] - fn new_window_shows_a_second_view() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let ctx = egui::Context::default(); - let frame = |app: &mut crate::DesignApp| { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - frame(&mut app); - assert_eq!(run_ui(&mut app, "window.newWindow", &json!({})).unwrap().unwrap(), json!(true)); - assert!(!app.split); - frame(&mut app); - frame(&mut app); - // Pane 1 was drawn (its rect is held for it) and has its own view. - assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some() || app.pane == 1); - app.switch_pane(1); - assert!(app.view().is_some(), "the second window has a view"); - app.switch_pane(0); - assert_eq!(checked(&app, "window.newWindow", &Value::Null), Some(true)); - run_ui(&mut app, "window.newWindow", &json!({"on": false})).unwrap().unwrap(); - frame(&mut app); - } - - #[test] - fn panels_float_and_dock() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "swatches", "x": 50, "y": 60})).unwrap().unwrap(); - assert_eq!(r["floating"], json!(["swatches"])); - let window = &app.ui.docking.as_ref().unwrap().floating[0]; - assert_eq!([window.rect[0], window.rect[1]], [50.0, 60.0]); - // Showing a floating panel leaves it where it is. - run_ui(&mut app, "window.panel", &json!({"panel": "swatches"})).unwrap().unwrap(); - assert_eq!(app.ui.open_panel, None); - let r = run_ui(&mut app, "window.dockPanel", &json!({"panel": "swatches"})).unwrap().unwrap(); - assert_eq!(r["floating"], json!([])); - assert!(app.ui.docking.as_ref().unwrap().floating.is_empty()); - assert!(run_ui(&mut app, "window.floatPanel", &json!({"panel": "nope"})).unwrap().is_err()); - // Float-only panels (Type › Tabs) have their own windows outside the layout. - let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "tabs", "x": 10, "y": 20})).unwrap().unwrap(); - assert_eq!(r["floating"], json!(["tabs"])); - assert_eq!(app.ui.floating, [("tabs".to_string(), [10.0, 20.0])]); - run_ui(&mut app, "window.dockPanel", &json!({"panel": "tabs"})).unwrap().unwrap(); - assert!(app.ui.floating.is_empty()); - } - - /// One frame as the desktop app runs it: queued synthetic input, then the native menu item - /// chosen during the frame (`menu`), then the app's logic and ui. - fn native_frame(app: &mut crate::DesignApp, ctx: &egui::Context, events: Vec, menu: Option<&str>) -> egui::FullOutput { - let mut input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), - events, - ..Default::default() - }; - app.raw_input_hook(ctx, &mut input); - let mut menu = menu; - let mut out = ctx.run_ui(input, |ui| { - let ctx = ui.ctx().clone(); - if let Some(id) = menu.take() { - activate_native(app, &ctx, id, &Value::Null); - } - app.logic(&ctx); - app.ui(ui); - }); - out.textures_delta.clear(); - out - } - - /// A document with two frames, nothing selected, and Quick Apply's search field focused - /// holding `text`. - fn app_with_focused_field(ctx: &egui::Context, text: &str) -> crate::DesignApp { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); - app.session.execute("frame.create", &json!({"rect": [236, 36, 400, 200]})).unwrap(); - app.session.execute("edit.deselectAll", &json!({})).unwrap(); - app.ui.palette = Some(text.into()); - for _ in 0..3 { - native_frame(&mut app, ctx, vec![], None); - } - assert!(ctx.text_edit_focused()); - app - } - - fn field_selection(ctx: &egui::Context) -> Option<(usize, usize)> { - let id = ctx.memory(|m| m.focused())?; - let r = egui::TextEdit::load_state(ctx, id)?.cursor.char_range()?; - Some((r.primary.index.min(r.secondary.index).into(), r.primary.index.max(r.secondary.index).into())) - } - - fn document_items(app: &crate::DesignApp) -> (usize, usize) { - let d = app.session.active().unwrap(); - (d.doc.spreads.iter().flat_map(|sp| &sp.items).count(), d.selection.items.len()) - } - - #[test] - fn native_select_all_selects_the_focused_fields_text() { - // The Mac menu bar takes ⌘A before the window sees it (#30). - let ctx = egui::Context::default(); - let mut app = app_with_focused_field(&ctx, "frame"); - native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); - native_frame(&mut app, &ctx, vec![], None); - assert_eq!(field_selection(&ctx), Some((0, 5)), "the field's whole text is selected"); - assert_eq!(document_items(&app), (2, 0), "the document selection is unchanged"); - } - - #[test] - fn native_paste_and_copy_act_on_the_focused_field() { - let ctx = egui::Context::default(); - let mut app = app_with_focused_field(&ctx, "frame"); - native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); - native_frame(&mut app, &ctx, vec![], None); - // Copy puts the field's selected text on the clipboard. - native_frame(&mut app, &ctx, vec![], Some("edit.copy")); - let out = native_frame(&mut app, &ctx, vec![], None); - assert!(out.platform_output.commands.contains(&egui::OutputCommand::CopyText("frame".into())), "{:?}", out.platform_output.commands); - // Paste asks the integration for the clipboard, which it hands to the field as a paste. - let out = native_frame(&mut app, &ctx, vec![], Some("edit.paste")); - let commands = &out.viewport_output[&egui::ViewportId::ROOT].commands; - assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}"); - native_frame(&mut app, &ctx, vec![egui::Event::Paste("text".into())], None); - assert_eq!(app.ui.palette.as_deref(), Some("text")); - assert_eq!(document_items(&app), (2, 0), "nothing was pasted into the document"); - } - - #[test] - fn native_copy_and_paste_use_the_system_clipboard_for_canvas_text() { - let ctx = egui::Context::default(); - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200], "content": "text", "text": "hello"})).unwrap(); - let story = *app.session.active().unwrap().doc.stories.keys().next().unwrap(); - app.select_tool("type"); - app.run("text.select", json!({"story": story.0, "anchor": 0, "focus": 5})).unwrap(); - for _ in 0..3 { - native_frame(&mut app, &ctx, vec![], None); - } - assert!(app.session.wants_text()); - - native_frame(&mut app, &ctx, vec![], Some("edit.copy")); - let copied = native_frame(&mut app, &ctx, vec![], None); - assert!(copied.platform_output.commands.contains(&egui::OutputCommand::CopyText("hello".into()))); - - let paste = native_frame(&mut app, &ctx, vec![], Some("edit.paste")); - let commands = &paste.viewport_output[&egui::ViewportId::ROOT].commands; - assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}"); - native_frame(&mut app, &ctx, vec![egui::Event::Paste("world".into())], None); - assert_eq!(app.session.active().unwrap().doc.story(story).unwrap().text, "world"); - } - - #[test] - fn native_undo_and_redo_act_on_the_focused_field() { - let ctx = egui::Context::default(); - let mut app = app_with_focused_field(&ctx, ""); - native_frame(&mut app, &ctx, vec![egui::Event::Text("abc".into())], None); - assert_eq!(app.ui.palette.as_deref(), Some("abc")); - native_frame(&mut app, &ctx, vec![], Some("edit.undo")); - native_frame(&mut app, &ctx, vec![], None); - assert_eq!(app.ui.palette.as_deref(), Some(""), "the field's typing is undone"); - assert_eq!(document_items(&app), (2, 0), "the document's last frame is still there"); - native_frame(&mut app, &ctx, vec![], Some("edit.redo")); - native_frame(&mut app, &ctx, vec![], None); - assert_eq!(app.ui.palette.as_deref(), Some("abc")); - assert_eq!(document_items(&app), (2, 0)); - } - - #[test] - fn native_editing_items_are_enabled_for_a_focused_field() { - let ctx = egui::Context::default(); - let mut app = app_with_focused_field(&ctx, "frame"); - // Nothing is selected in the document, so its Copy and Cut are off; the field's are on. - assert!(!menu_enabled(&app, "edit.copy") && !menu_enabled(&app, "edit.cut")); - for id in ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"] { - assert!(native_menu_enabled(&app, &ctx, id), "{id}"); - } - assert!(!native_menu_enabled(&app, &ctx, "edit.duplicate"), "other items follow the document"); - app.ui.palette = None; - native_frame(&mut app, &ctx, vec![], None); - native_frame(&mut app, &ctx, vec![], None); - assert!(!native_menu_enabled(&app, &ctx, "edit.copy"), "without a focused field, as the document says"); - } - - #[test] - fn native_select_all_without_a_focused_field_selects_the_documents_items() { - let ctx = egui::Context::default(); - let mut app = app_with_focused_field(&ctx, "frame"); - app.ui.palette = None; - native_frame(&mut app, &ctx, vec![], None); - native_frame(&mut app, &ctx, vec![], None); - assert!(!ctx.text_edit_focused()); - native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); - assert_eq!(document_items(&app), (2, 2)); - } - - #[test] - fn command_search_matches_labels_in_the_interface_language() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.language = "de".into(); - let label = crate::i18n::tr("de", "Group"); - let items = command_search(&app, &label.to_lowercase()); - let group = items.iter().find(|i| i.id == "object.group").unwrap(); - assert_eq!(group.label, label); - assert_eq!(group.shortcut.as_deref(), Some("Cmd+G")); - assert!(command_search(&app, "group").iter().any(|i| i.id == "object.group"), "English labels match too"); - assert!(command_search(&app, " ").is_empty()); - assert!(command_search(&app, "e").len() <= 14); - } - - #[test] - fn quick_apply_lists_styles_then_commands() { - let mut s = designcraft_engine::Session::new(); - s.execute("file.new", &json!({})).unwrap(); - s.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap(); - let items = quick_apply_items(&s, "body", false); - assert_eq!(items[0].id, "style.paragraph.apply"); - assert_eq!(items[0].params, json!({"name": "Body Copy"})); - assert_eq!(items[0].kind, "Paragraph Style"); - assert!(quick_apply_items(&s, "", false).iter().all(|i| i.kind.is_empty())); - assert!(quick_apply_items(&s, "preferences", false).iter().any(|i| i.id == "app.preferences")); - } - - #[test] - fn searched_ui_commands_run_without_parameters_and_keep_preferences() { - // Without a value these reset a setting or need a place the test host always has. - let searched: Vec<&str> = quick_commands().map(|c| c.0).collect(); - for id in ["app.flattener", "view.screenMode", "view.zoom", "window.taskBarPin"] { - assert!(!searched.contains(&id), "{id} is searched"); - } - // A placed PDF: a graphic with layers. - let mut scratch = designcraft_engine::Session::new(); - scratch.execute("file.new", &json!({})).unwrap(); - let pdf = scratch.execute("file.exportPdf", &json!({})).unwrap()["base64"].clone(); - let contexts = ["nothing selected", "text insertion point", "text frame selected", "table cell", "placed PDF selected"]; - // A two-page document, a saved workspace and non-default preferences, a host with window - // controls, and file dialogs that are dismissed. - let setup = |context: usize| { - let services = crate::Services { - pick_open: Some(Box::new(|_| None)), - pick_save: Some(Box::new(|_| None)), - clipboard_text: Some(Box::new(|| None)), - ..Default::default() - }; - let mut app = DesignApp::new(designcraft_engine::Session::new(), services); - app.custom_titlebar = true; - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))); - app.run("file.new", json!({"pages": 2})).unwrap(); - app.session.prefs.recent_files.push("/nowhere/recent.dcraft".into()); - app.ui.shortcuts.insert("view.rulers", vec!["Ctrl+Alt+R".into()]); - app.ui.hidden_menu_items.push("view.guides".into()); - app.ui.ui_scale = 1.25; - app.ui.brightness = crate::theme::Brightness::Light; - app.ui.task_bar_at = Some([200.0, 200.0]); - run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); - match context { - 1 => { - app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": "One", "caret": true})).unwrap(); - } - 2 => { - let f = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": "One"})).unwrap()["id"].clone(); - app.run("selection.set", json!({"ids": [f]})).unwrap(); - } - 3 => { - app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap(); - app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); - } - 4 => { - let f = app.run("frame.create", json!({"rect": [72, 72, 400, 400]})).unwrap()["id"].clone(); - app.run("file.place", json!({"base64": pdf, "name": "a.pdf", "frame": f})).unwrap(); - app.run("selection.set", json!({"ids": [f]})).unwrap(); - } - _ => {} - } - app.ui.dialog = None; - app - }; - let prefs = |app: &DesignApp| { - let u = &app.ui; - json!({ - "shortcuts": u.shortcuts, "hiddenMenuItems": u.hidden_menu_items, "uiScale": u.ui_scale, - "brightness": u.brightness, "workspace": u.workspace, "customWorkspaces": u.custom_workspaces, - "docking": u.docking, "dockingHidden": u.docking_hidden, "floating": u.floating, - }) - }; - let quick = quick_apply_items(&setup(0).session, "workspace", false); - assert!(quick.iter().any(|i| i.id == "window.newWorkspace")); - // Deleting needs a workspace name: the application bar's workspace menu lists them. - assert!(!quick.iter().any(|i| i.id == "window.deleteWorkspace")); - // Each command runs as Quick Apply runs an entry. One that needs a selection may fail - // without it, but runs in one of the contexts; none changes a preference it wasn't asked to. - // Opening a panel or collapsing the dock to icons changes where the panels are, as it should. - let opens_a_panel = [ - "app.tabsPanel", - "app.characterStylesPanel", - "app.paragraphStylesPanel", - "app.characterPanel", - "app.paragraphPanel", - "app.glyphsPanel", - "app.tablePanel", - "window.collapseToIcons", - ]; - let arrangement = ["docking", "dockingHidden", "floating"]; - let mut failed = Vec::new(); - for (id, ..) in quick_commands().filter(|(id, ..)| UI_COMMANDS.iter().any(|c| c.0 == *id)) { - let mut errors = Vec::new(); - for (i, context) in contexts.iter().enumerate() { - let mut app = setup(i); - let before = prefs(&app); - match app.run(id, json!({})) { - Err(e) => errors.push(format!("{context}: {e}")), - Ok(_) => { - let after = prefs(&app); - let changed: Vec<&String> = - before.as_object().unwrap().iter().filter(|(k, v)| after.get(k.as_str()) != Some(*v)).map(|(k, _)| k).collect(); - let changed: Vec<&String> = - changed.into_iter().filter(|k| !(opens_a_panel.contains(&id) && arrangement.contains(&k.as_str()))).collect(); - if !changed.is_empty() { - failed.push(format!("{id} ({context}): changed {changed:?}")); - } - } - } - } - if errors.len() == contexts.len() { - failed.push(format!("{id}: {errors:?}")); - } - } - assert!(failed.is_empty(), "{failed:#?}"); - } - - #[test] - fn distribute_rows_menu_dispatches_an_undoable_edit() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let frame = app.run("frame.create", json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap(); - app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 0})).unwrap(); - app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); - app.run("table.setRowHeight", json!({"row": 0, "height": 40, "mode": "exactly"})).unwrap(); - app.run("table.setRowHeight", json!({"row": 1, "height": 80, "mode": "exactly"})).unwrap(); - app.run("table.selectTable", json!({})).unwrap(); - activate(&mut app, "table.distributeRows", &Value::Null); - assert!(app.ui.dialog.is_none()); - let info = app.run("table.get", json!({})).unwrap(); - assert_eq!(info["rows"][0]["height"], 60.0); - assert_eq!(info["rows"][1]["height"], 60.0); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.run("table.get", json!({})).unwrap()["rows"][0]["height"], 40.0); - } - - #[test] - fn every_menu_entry_is_a_command() { - let mut all = Vec::new(); - for (_, items) in menu_tree() { - walk(&items, &mut all); - } - assert!(all.len() > 80, "{}", all.len()); - assert!(all.iter().any(|(label, id, _)| label == "Distribute Rows Evenly" && id == "table.distributeRows")); - for (label, id, params) in &all { - assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "menu entry {label}: unknown command {id}"); - assert!(!label.is_empty() && label != id, "menu entry {id} has no label"); - if let Some(o) = params.as_object() { - assert!(!o.is_empty(), "{id}: empty fixed params"); - } - } - // Nested submenus parse (Type › Insert Special Character › Symbols › …). - let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; - let special = ty.iter().find_map(|i| match i { - Item::Sub(n, c) if n == "Insert Special Character" => Some(c.clone()), - _ => None, - }); - assert!(special.is_some_and(|c| c.iter().any(|i| matches!(i, Item::Sub(n, _) if n == "Symbols")))); - // Fixed-parameter variants keep their own labels. - assert!(all.iter().any(|(l, id, _)| l == "Fill Frame Proportionally" && id == "fit.fillFrameProportionally")); - } - - #[test] - fn context_menus_hold_commands_and_menu_bar_submenus() { - let tree = menu_tree(); - for entries in [CONTEXT_OBJECT, CONTEXT_GRAPHIC_FRAME, CONTEXT_OBJECT_TAIL, CONTEXT_TEXT_FRAME, CONTEXT_TEXT, CONTEXT_CANVAS] { - for path in entries.iter().filter_map(|e| e.strip_prefix("menu:")) { - assert!(menu_bar_submenu(&tree, path).is_some(), "no menu bar submenu {path}"); - } - let mut all = Vec::new(); - for (_, items) in context_parse(entries) { - walk(&items, &mut all); - } - for (label, id, _) in &all { - assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "context entry {label}: unknown command {id}"); - } - } - } - - #[test] - fn the_type_menu_follows_indesigns_order() { - // InDesign's Type menu, as Chris Nielsen opens it in "Numbering Page Sections" (2:09). - let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; - let labels: Vec = ty - .iter() - .map(|i| match i { - Item::Sep => "-".to_string(), - Item::Sub(n, _) => format!("{n} >"), - Item::Cmd { label, .. } => label.clone(), - }) - .collect(); - let expected = [ - "Size >", - "-", - "Character", - "Paragraph", - "Tabs", - "Glyphs", - "-", - "Character Styles", - "Paragraph Styles", - "-", - "Create Outlines", - "Find/Replace Font…", - "Reload Fonts", - "Change Case >", - "-", - "Type on a Path >", - "-", - "Notes >", - "Track Changes >", - "-", - "Insert Footnote", - "Document Footnote Options…", - "Insert Endnote", - ]; - assert_eq!(&labels[..expected.len()], expected, "{labels:?}"); - let pos = |l: &str| labels.iter().position(|x| x == l).unwrap_or_else(|| panic!("{l} in {labels:?}")); - assert!(pos("Hyperlinks & Cross-References >") < pos("Text Variables >")); - assert!(pos("Text Variables >") < pos("Bulleted & Numbered Lists >")); - assert!(pos("Bulleted & Numbered Lists >") < pos("Insert Special Character >")); - assert!(pos("Insert Special Character >") < pos("Insert White Space >")); - assert!(pos("Insert Break Character >") < pos("Fill with Placeholder Text")); - assert!(pos("Fill with Placeholder Text") < pos("Show Hidden Characters")); - // Alignment, styles and point sizes keep their shortcuts, out of the menu as in InDesign. - for gone in ["Align Left", "Bold", "Increase Point Size", "Paragraph Rules…"] { - assert!(!labels.iter().any(|l| l == gone), "{gone}"); - } - let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let all = effective_shortcuts(&app); - for (id, sc) in [ - ("type.alignLeft", "Cmd+Shift+L"), - ("app.characterPanel", "Cmd+T"), - ("app.paragraphPanel", "Cmd+Alt+T"), - ("app.insertCurrentPageNumber", "Cmd+Alt+Shift+N"), - ] { - assert_eq!(all.iter().find(|(i, _)| i == id).map(|(_, s)| s.as_str()), Some(sc), "{id}"); - } - // Markers › Current Page Number carries ⌥⇧⌘N. - let markers = ty - .iter() - .find_map(|i| match i { - Item::Sub(n, c) if n == "Insert Special Character" => { - c.iter().find_map(|i| if let Item::Sub(n, c) = i { (n == "Markers").then(|| c.clone()) } else { None }) - } - _ => None, - }) - .unwrap(); - assert!(matches!(&markers[0], Item::Cmd { label, shortcut: Some("Cmd+Alt+Shift+N"), .. } if label == "Current Page Number")); - } - - #[test] - fn type_panel_items_open_their_panels_and_the_marker_shortcut_inserts_a_page_number() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - activate(&mut app, "app.characterPanel", &Value::Null); - assert!(crate::panel_docking::showing(&app, "character")); - // Paragraph Styles opens floating, grouped with Character Styles, as in InDesign. - activate(&mut app, "app.paragraphStylesPanel", &Value::Null); - let layout = app.ui.docking.as_ref().unwrap(); - assert!( - layout - .floating - .iter() - .flat_map(crate::panel_docking::window_groups) - .any(|g| g.panels == ["characterStyles", "paragraphStyles"] && g.active == 1) - ); - let story = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "Page "})).unwrap()["story"].clone(); - app.run("text.select", json!({"story": story, "anchor": 5, "focus": 5})).unwrap(); - activate(&mut app, "app.insertCurrentPageNumber", &Value::Null); - let d = &app.session.doc().unwrap().doc; - assert_eq!(d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text, "Page \u{e000}"); - } - - #[test] - fn custom_workspaces_save_apply_and_delete() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.dock_tab = "swatches".into(); - app.ui.control_bar = true; - run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); - run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); - app.ui.dock_tab = "properties".into(); - run_ui(&mut app, "window.workspace", &json!({"name": "Mine"})).unwrap().unwrap(); - assert_eq!((app.ui.dock_tab.as_str(), app.ui.control_bar, app.ui.workspace.as_str()), ("swatches", true, "Mine")); - app.ui.dock_tab = "layers".into(); - run_ui(&mut app, "window.resetWorkspace", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.dock_tab, "swatches", "reset to the saved arrangement"); - run_ui(&mut app, "window.deleteWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); - assert!(app.ui.custom_workspaces.is_empty()); - assert_eq!(app.ui.workspace, "Essentials"); - } - - /// New Workspace › Capture (Learn Skills Daily's InDesign course, 11:40): Panel Locations and - /// Menu Customization, both on by default. - #[test] - fn new_workspace_captures_panel_locations_and_menu_customization() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - // The dialog offers both, checked. - run_ui(&mut app, "window.newWorkspace", &json!({})).unwrap().unwrap(); - let d = app.ui.dialog.take().unwrap(); - assert_eq!( - (d.id.as_str(), d.fields["panelLocations"].clone(), d.fields["menuCustomization"].clone()), - ("newWorkspace", json!(true), json!(true)) - ); - // Both captured. - app.ui.dock_tab = "swatches".into(); - app.ui.hidden_menu_items = vec!["Type/Glyphs".into()]; - run_ui(&mut app, "window.newWorkspace", &json!({"name": "All"})).unwrap().unwrap(); - // Menus only: choosing it leaves the panels where they are. - app.ui.hidden_menu_items = vec!["Layout/Pages".into()]; - run_ui(&mut app, "window.newWorkspace", &json!({"name": "Menus", "panelLocations": false})).unwrap().unwrap(); - // Panels only: the menus stay as they are. - app.ui.dock_tab = "layers".into(); - run_ui(&mut app, "window.newWorkspace", &json!({"name": "Panels", "menuCustomization": false})).unwrap().unwrap(); - app.ui.dock_tab = "properties".into(); - app.ui.hidden_menu_items.clear(); - run_ui(&mut app, "window.workspace", &json!({"name": "Menus"})).unwrap().unwrap(); - assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("properties", vec!["Layout/Pages".to_string()])); - run_ui(&mut app, "window.workspace", &json!({"name": "Panels"})).unwrap().unwrap(); - assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("layers", vec!["Layout/Pages".to_string()])); - run_ui(&mut app, "window.workspace", &json!({"name": "All"})).unwrap().unwrap(); - assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("swatches", vec!["Type/Glyphs".to_string()])); - // A workspace saved before the options existed restores its panels. - let old: crate::SavedWorkspace = serde_json::from_value(json!({"name": "Old", "dockTab": "pages"})).unwrap(); - assert!(!old.keep_panels && old.hidden_menu_items.is_none()); - } - - #[test] - fn essentials_classic_is_the_control_panel_and_iconic_groups() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - run_ui(&mut app, "window.workspace", &json!({"name": "Essentials Classic"})).unwrap().unwrap(); - assert!(app.ui.control_bar && !app.ui.dock_expanded); - let groups = app.ui.icon_groups.clone().unwrap(); - assert_eq!(groups[0], ["pages", "layers", "links"]); - assert_eq!(groups.last().unwrap(), &["gradient"]); - assert_eq!(checked(&app, "window.workspace", &json!({"name": "Essentials Classic"})), Some(true)); - assert_eq!(checked(&app, "window.workspace", &json!({"name": "Essentials"})), Some(false)); - // Window › Pages opens Pages from its icon group, not the Properties stack. - run_ui(&mut app, "window.panel", &json!({"panel": "pages"})).unwrap().unwrap(); - assert!(crate::panel_docking::showing(&app, "pages")); - let layout = app.ui.docking.clone().unwrap(); - assert!(!layout.contains(&"properties".to_string())); - assert_eq!(crate::panel_docking::tab_group(&layout, "pages"), ["pages", "layers", "links"]); - // A workspace saved from it keeps the groups. - run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); - run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); - assert_eq!((app.ui.icon_groups.as_ref(), app.ui.dock_expanded, app.ui.control_bar), (None, true, false)); - run_ui(&mut app, "window.workspace", &json!({"name": "Mine"})).unwrap().unwrap(); - assert_eq!(app.ui.icon_groups, Some(groups)); - } - - #[test] - fn typography_workspace_opens_its_panels_from_named_icon_groups_and_resets() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - run_ui(&mut app, "window.workspace", &json!({"name":"Typography"})).unwrap().unwrap(); - assert!(app.ui.control_bar); - assert!(!app.ui.dock_expanded); - assert!(app.ui.open_panel.is_none()); - let groups = app.ui.icon_groups.clone().unwrap(); - assert_eq!(groups[0], ["pages", "layers", "swatches"]); - assert_eq!(groups[4], ["paragraph", "paragraphStyles"]); - assert_eq!(groups[5], ["character", "characterStyles"]); - for panel in ["pages", "paragraphStyles", "characterStyles"] { - run_ui(&mut app, "window.panel", &json!({"panel":panel})).unwrap().unwrap(); - assert!(crate::panel_docking::showing(&app, panel), "{panel}"); - assert!(app.ui.docking.as_ref().unwrap().floating.is_empty(), "{panel} opens from its icon group"); - } - run_ui(&mut app, "window.resetWorkspace", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.icon_groups, Some(groups)); - assert!(app.ui.open_panel.is_none()); - assert!(!app.ui.dock_expanded); - run_ui(&mut app, "window.workspace", &json!({"name":"Essentials"})).unwrap().unwrap(); - assert!(app.ui.icon_groups.is_none()); - assert!(app.ui.dock_expanded); - } - - #[test] - fn the_window_menu_is_in_indesigns_order_and_reaches_every_panel() { - let window = menu_tree().into_iter().find(|(m, _)| *m == "Window").unwrap().1; - let names: Vec<&str> = window - .iter() - .filter_map(|i| match i { - Item::Sub(n, _) => Some(n.as_str()), - Item::Cmd { label, .. } => Some(label.as_str()), - Item::Sep => None, - }) - .collect(); - assert_eq!(&names[..4], ["Arrange", "Workspace", "Articles", "Color"]); - let sub = |name: &str| { - window - .iter() - .find_map(|i| match i { - Item::Sub(n, c) if n == name => Some(c.clone()), - _ => None, - }) - .unwrap() - }; - // Window › Workspace › Essentials Classic, Window › Color › Gradient & Swatches. - assert!( - sub("Workspace") - .iter() - .any(|i| matches!(i, Item::Cmd { id, params, .. } if id == "window.workspace" && params["name"] == "Essentials Classic")) - ); - let color: Vec = - sub("Color").iter().filter_map(|i| if let Item::Cmd { label, .. } = i { Some(label.clone()) } else { None }).collect(); - assert_eq!(color, ["Color", "Gradient", "Swatches"]); - // Every panel is in the menu. - fn panels(items: &[Item], out: &mut Vec) { - for i in items { - match i { - Item::Sub(_, c) => panels(c, out), - Item::Cmd { id, params, .. } if id == "window.panel" => out.extend(params["panel"].as_str().map(str::to_string)), - _ => {} - } - } - } - let mut found = Vec::new(); - panels(&window, &mut found); - for (id, _, _) in crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS) { - assert!(found.iter().any(|p| p == id), "Window menu misses the {id} panel"); - } - } - - #[test] - fn interactive_workspaces_show_their_panels() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.dock_expanded = false; - run_ui(&mut app, "window.workspace", &json!({"name": "Interactive for PDF"})).unwrap().unwrap(); - assert_eq!((app.ui.dock_tab.as_str(), app.ui.dock_expanded, app.ui.open_panel.as_deref()), ("pages", true, Some("buttons"))); - run_ui(&mut app, "window.workspace", &json!({"name": "Digital Publishing"})).unwrap().unwrap(); - assert_eq!((app.ui.dock_tab.as_str(), app.ui.open_panel.as_deref()), ("pages", Some("liquid"))); - run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); - assert_eq!(app.ui.open_panel, None); - } - - #[test] - fn hide_and_show_menu_items() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let items = all_menu_items(); - let (menu, label) = items.iter().find(|(m, _)| m == "Edit").cloned().expect("Edit items"); - let key = menu_key(&menu, &label); - run_ui(&mut app, "window.hideMenuItem", &json!({"item": key})).unwrap().unwrap(); - assert!(app.ui.hidden_menu_items.contains(&key)); - run_ui(&mut app, "window.hideMenuItem", &json!({"item": key, "hidden": false})).unwrap().unwrap(); - assert!(app.ui.hidden_menu_items.is_empty()); - assert!(items.len() > 100, "every menu's items are listed: {}", items.len()); - } - - /// The Type menu as drawn: every item label. - fn drawn_type_menu(app: &mut DesignApp) -> Vec { - let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; - let ctx = egui::Context::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 4000.0)); - let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { - menu_items(app, ui, &ty, "Type"); - }); - out.textures_delta.clear(); - fn collect(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Text(t) => out.push(t.galley.job.text.trim().to_string()), - egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), - _ => {} - } - } - let mut labels = Vec::new(); - out.shapes.iter().for_each(|s| collect(&s.shape, &mut labels)); - labels - } - - /// Tate-Chu-Yoko, Ruby, Kenten and Warichu are in the Type menu of InDesign's Japanese edition - /// only: they show while Show CJK Features is on, which follows the interface language until - /// the user sets it. Hidden, they still run. - #[test] - fn cjk_menu_items_follow_show_cjk_features() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; - let cjk: Vec = ty - .iter() - .filter_map(|i| match i { - Item::Cmd { label, id, .. } if CJK_ONLY.contains(&id.as_str()) => Some(label.clone()), - _ => None, - }) - .collect(); - assert_eq!(cjk.len(), 4, "{cjk:?}"); - let drawn = |app: &mut DesignApp| { - let labels = drawn_type_menu(app); - assert!(labels.iter().any(|l| l == crate::i18n::tr(&app.ui.language, "Story Direction")), "in both editions: {labels:?}"); - let shown: Vec = cjk.iter().map(|l| labels.iter().any(|d| d == crate::i18n::tr(&app.ui.language, l))).collect(); - assert!(shown.iter().all(|s| *s == shown[0]), "{shown:?}"); - shown[0] - }; - for (lang, on) in [("", false), ("de", false), ("ja", true), ("zh", true), ("ko", true)] { - app.ui.language = lang.into(); - assert_eq!(crate::cjk_features(&app), on, "{lang}"); - assert_eq!(drawn(&mut app), on, "{lang}"); - } - app.run("prefs.set", json!({"cjkFeatures": false})).unwrap(); - assert!(!drawn(&mut app), "off in a Korean interface"); - app.ui.language = String::new(); - app.run("prefs.set", json!({"cjkFeatures": true})).unwrap(); - assert!(drawn(&mut app), "on in an English interface"); - assert!(quick_apply_items(&app.session, "ruby", crate::cjk_features(&app)).iter().any(|i| i.id == "app.rubyDialog")); - app.run("prefs.set", json!({"cjkFeatures": false})).unwrap(); - assert!(!drawn(&mut app)); - assert!(!quick_apply_items(&app.session, "ruby", crate::cjk_features(&app)).iter().any(|i| i.id == "app.rubyDialog")); - app.run("app.rubyDialog", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("ruby"), "hidden, not removed"); - } - - /// Preferences › Type › Show CJK Features: left as it is, it keeps following the interface - /// language; changed, it is kept in prefs.json. - #[test] - fn show_cjk_features_is_a_persisted_preference() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.ui.language = "ja".into(); - run_ui(&mut app, "app.preferences", &json!({})).unwrap().unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cjkFeatures"], true); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(app.session.prefs.cjk_features, None, "untouched: follows the language"); - run_ui(&mut app, "app.preferences", &json!({})).unwrap().unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("cjkFeatures".into(), json!(false)); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(app.session.prefs.cjk_features, Some(false)); - assert!(!crate::cjk_features(&app)); - // prefs.json round trip; a file from before the setting follows the language. - let saved = serde_json::to_vec(&app.session.prefs).unwrap(); - assert_eq!(serde_json::from_slice::(&saved).unwrap().cjk_features, Some(false)); - assert_eq!(serde_json::from_str::(r#"{"scaleStrokes": false}"#).unwrap().cjk_features, None); - assert_eq!(app.run("prefs.set", json!({"cjkFeatures": null})).unwrap()["cjkFeatures"], Value::Null); - assert!(crate::cjk_features(&app), "follows the Japanese interface again"); - } - - #[test] - fn menu_button_fits_its_anchor_and_resets_scroll_on_reopen() { - // Workspace/panel menus may be in the middle; the status-bar zoom menu opens upwards. - for anchor_y in [0.0, 130.0, 260.0] { - let ctx = egui::Context::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); - let mut tick = 0; - let mut frame = |events: Vec| { - tick += 1; - let mut button = None; - let mut first = None; - let mut last = None; - let mut output = - ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { - ui.add_space(anchor_y); - let response = menu_button(ui, "Long menu", |ui| { - for i in 0..60 { - let response = ui.button(format!("Item {i}")); - if i == 0 { - first = Some((response.rect, ui.clip_rect())); - } - if i == 59 { - last = Some((response.rect, ui.clip_rect())); - } - } - }); - button = Some(response.response); - }); - output.textures_delta.clear(); - (button.expect("menu button"), first, last) - }; - let click = - |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(vec![]); - let (button, _, _) = frame(vec![]); - let anchor = button.rect; - for pressed in [true, false] { - frame(vec![egui::Event::PointerMoved(anchor.center()), click(anchor.center(), pressed)]); - } - for _ in 0..3 { - frame(vec![]); - } - let popup = ctx.memory(|memory| memory.area_rect(egui::Popup::default_response_id(&button))).expect("open menu"); - assert!(screen.contains_rect(popup), "menu at {anchor_y} fits in the viewport: {popup:?}"); - assert!( - popup.top() >= anchor.bottom() - 1.0 || popup.bottom() <= anchor.top() + 1.0, - "menu at {anchor_y} stays on one side of its button: {popup:?}, {anchor:?}" - ); - let (_, first, last) = frame(vec![]); - let (first, clip) = first.expect("first row"); - assert!(clip.contains_rect(first), "newly opened menu starts at the first row"); - assert!(!clip.intersects(last.expect("last row").0), "last row starts below the scroll area"); - - frame(vec![ - egui::Event::PointerMoved(popup.center()), - egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -5000.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }, - ]); - for _ in 0..60 { - frame(vec![]); - } - let (_, first, last) = frame(vec![]); - let (last, clip) = last.expect("scrolled last row"); - assert!(popup.contains_rect(last) && clip.contains_rect(last), "last row is reachable: {last:?}, {popup:?}, {clip:?}"); - assert!(!clip.intersects(first.expect("scrolled first row").0), "menu really scrolled away from its start"); - - let outside = egui::pos2(screen.right() - 10.0, screen.center().y); - for pressed in [true, false] { - frame(vec![egui::Event::PointerMoved(outside), click(outside, pressed)]); - } - assert!(!egui::Popup::is_any_open(&ctx), "outside click closes the menu"); - assert!(frame(vec![]).1.is_none(), "closed menu is no longer drawn"); - for pressed in [true, false] { - frame(vec![egui::Event::PointerMoved(anchor.center()), click(anchor.center(), pressed)]); - } - for _ in 0..3 { - frame(vec![]); - } - let (_, first, last) = frame(vec![]); - let (first, clip) = first.expect("reopened first row"); - assert!(popup.contains_rect(first) && clip.contains_rect(first), "reopening resets to the first row: {first:?}, {clip:?}"); - assert!(!clip.intersects(last.expect("reopened last row").0), "reopening discards the old scroll offset"); - } - } - - #[test] - fn tiny_menu_viewport_does_not_force_the_default_scroll_height() { - let ctx = egui::Context::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 100.0)); - let mut tick = 0; - let mut frame = |events: Vec| { - tick += 1; - let mut button = None; - let mut output = - ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { - ui.add_space(35.0); - let response = menu_button(ui, "Long menu", |ui| { - for i in 0..20 { - let _ = ui.button(format!("Item {i}")); - } - }); - button = Some(response.response); - }); - output.textures_delta.clear(); - button.expect("menu button") - }; - frame(vec![]); - let button = frame(vec![]); - let pos = button.rect.center(); - for pressed in [true, false] { - frame(vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ]); - } - for _ in 0..3 { - frame(vec![]); - } - let popup = ctx.memory(|memory| memory.area_rect(egui::Popup::default_response_id(&button))).expect("open menu"); - let space = (screen.bottom() - button.rect.bottom()).max(button.rect.top() - screen.top()); - assert!(space < 64.0, "fixture has less space than egui's default minimum scroll height"); - // A complete command row may not fit, but the scroll area's minimum must not make - // the popup exceed its height budget or cover the button that dismisses it. - assert!(popup.height() <= space, "tiny menu respects its available height: {popup:?}, {space}"); - assert!(screen.contains_rect(popup), "tiny menu remains inside the viewport: {popup:?}"); - assert!( - popup.top() >= button.rect.bottom() - 1.0 || popup.bottom() <= button.rect.top() + 1.0, - "tiny menu stays beside its anchor: {popup:?}, {:?}", - button.rect - ); - } - - #[test] - fn clipped_submenu_does_not_open_when_hovering_outside_menu() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 900.0)); - let entries = vec![Item::Sub("Hidden submenu".into(), vec![cmd_item("app.preferences", Value::Null)])]; - let mut tick = 0; - let mut frame = |spacing: f32, events: Vec| { - tick += 1; - let mut button_rect = egui::Rect::NOTHING; - let mut hidden_submenu = None; - let mut output = - ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { - egui::MenuBar::new().ui(ui, |ui| { - let response = ui.menu_button("Menu", |ui| { - egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| { - ui.add_space(spacing); - let button_id = ui.next_auto_id(); - menu_items(&mut app, ui, &entries, "Test"); - let response = ui.ctx().read_response(button_id).expect("submenu button response"); - let open = egui::containers::menu::MenuState::from_ui(ui, |state, _| state.open_item.is_some()); - hidden_submenu = Some((response.rect, ui.clip_rect(), open)); - }); - }); - button_rect = response.response.rect; - }); - }); - output.textures_delta.clear(); - (button_rect, hidden_submenu) - }; - frame(500.0, vec![]); - let button = frame(500.0, vec![]).0.center(); - for pressed in [true, false] { - frame( - 500.0, - vec![ - egui::Event::PointerMoved(button), - egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - for _ in 0..3 { - frame(500.0, vec![]); - } - let (_, Some((hidden, clip, open))) = frame(500.0, vec![]) else { panic!("test menu is open") }; - assert!(!open, "submenu starts closed"); - assert!(screen.contains_rect(hidden), "hidden row remains inside the screen: {hidden:?}"); - assert!(!clip.intersects(hidden), "submenu must be fully clipped: {hidden:?}, {clip:?}"); - let (_, Some((_, _, open))) = frame(500.0, vec![egui::Event::PointerMoved(hidden.center())]) else { panic!("test menu remains open") }; - assert!(!open, "hovering the clipped row's position outside the menu must not open its submenu"); - - let partial_spacing = 500.0 - (hidden.top() - clip.bottom()) - 6.0; - let (_, Some((partial, clip, open))) = frame(partial_spacing, vec![]) else { panic!("test menu remains open") }; - assert!(!open); - assert!(partial.top() < clip.bottom() && partial.bottom() > clip.bottom(), "row must be partially clipped: {partial:?}, {clip:?}"); - let outside = egui::pos2(partial.center().x, clip.bottom() + 1.0); - let (_, Some((_, _, open))) = frame(partial_spacing, vec![egui::Event::PointerMoved(outside)]) else { panic!("test menu remains open") }; - assert!(!open, "hovering the clipped portion of a partially visible row must not open its submenu"); - let visible = partial.intersect(clip).center(); - let (_, Some((_, _, open))) = frame(partial_spacing, vec![egui::Event::PointerMoved(visible)]) else { panic!("test menu remains open") }; - assert!(open, "hovering the visible portion still opens the submenu"); - let (_, Some((_, _, open))) = frame(500.0, vec![]) else { panic!("test menu remains open") }; - assert!(!open, "an open submenu closes when its row becomes fully clipped"); - } - - #[test] - fn native_labels_keep_their_ampersands() { - assert_eq!(native_label("Numbering & Section Options…"), "Numbering && Section Options…"); - assert_eq!(native_label("A&&B"), "A&&&&B"); - assert_eq!(native_label("Pages"), "Pages"); - } - - #[test] - fn the_mac_window_menu_minimizes_with_cmd_m() { - let window = native_menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, e)| e).unwrap_or_default(); - assert!(matches!(window.first(), Some(Item::Cmd { id, shortcut: Some("Cmd+M"), .. }) if id == "window.minimize"), "{:?}", window.first()); - assert!(matches!(window.get(1), Some(Item::Sep))); - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert!(run_ui(&mut app, "window.minimize", &Value::Null).is_some_and(|r| r.is_err()), "no host window controls"); - app.native_menu = true; - assert!(menu_enabled(&app, "window.minimize") && !menu_enabled(&app, "window.maximize")); - run_ui(&mut app, "window.minimize", &Value::Null).unwrap().unwrap(); - assert_eq!(app.pending_window_commands, [egui::ViewportCommand::Minimized(true)]); - } - - #[test] - fn mac_settings_follow_about_in_the_app_menu_and_leave_edit() { - let pos = |command: &str| MAC_APP_MENU.iter().position(|m| matches!(m, AppMenuItem::Cmd { command: c, .. } if *c == command)); - let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") }; - assert!(about < settings); - assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep)); - // Language follows Settings, as in the suite's other apps, titled in the interface language. - assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Language)); - assert_eq!(MAC_APP_MENU.get(settings + 2), Some(&AppMenuItem::Sep)); - let label = |command: &str| { - MAC_APP_MENU.iter().find_map(|m| match m { - AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label), - _ => None, - }) - }; - assert_eq!(label("app.preferences"), Some("Settings…")); - let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::>(); - assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}"); - - let edit = |tree: Vec<(&'static str, Vec)>| { - let mut out = Vec::new(); - walk(&tree.into_iter().find(|(t, _)| *t == "Edit").map(|(_, e)| e).unwrap_or_default(), &mut out); - out.into_iter().map(|(_, id, _)| id).collect::>() - }; - assert!(edit(menu_tree()).iter().any(|id| id == "app.preferences"), "the in-window Edit menu keeps Preferences"); - let native = native_menu_tree(); - let mut all = Vec::new(); - for (_, entries) in &native { - walk(entries, &mut all); - } - assert!(!all.iter().any(|(_, id, _)| id == "app.preferences"), "the macOS menu bar has Settings only in the app menu"); - assert!(edit(native_menu_tree()).iter().any(|id| id == "app.keyboardShortcuts")); - for (title, entries) in &native { - assert!(!matches!(entries.first(), Some(Item::Sep)) && !matches!(entries.last(), Some(Item::Sep)), "{title}: separator at an end"); - assert!(entries.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep])), "{title}: doubled separator"); - } - } - - /// Web save: a download that couldn't start is an error and leaves the document unsaved; one - /// that started marks it saved. - #[test] - fn web_save_marks_the_document_saved_only_after_the_download_starts() { - let dir = tempfile::tempdir().unwrap(); - // The title names a temporary path: on native, file.saveAs writes where the web build doesn't. - let title = dir.path().join("doc").to_string_lossy().to_string(); - let fails = std::rc::Rc::new(std::cell::Cell::new(true)); - let f = fails.clone(); - let services = crate::Services { - download: Some(Box::new(move |_: &str, _: &[u8]| if f.get() { Err("blocked".into()) } else { Ok(()) })), - ..Default::default() - }; - let mut app = DesignApp::new(designcraft_engine::Session::new(), services); - app.run("file.new", json!({"title": title})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 300, 200]})).unwrap(); - assert!(app.session.active().unwrap().is_dirty()); - - let e = app.run("app.save", json!({})).unwrap_err(); - assert!(e.contains("blocked"), "{e}"); - assert!(app.session.active().unwrap().is_dirty(), "a failed download leaves the document unsaved"); - - fails.set(false); - app.run("app.save", json!({})).unwrap(); - assert!(!app.session.active().unwrap().is_dirty()); - } - - fn start_screen_texts(app: &mut crate::DesignApp) -> Vec { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx, ""); - let mut shapes = Vec::new(); - for _ in 0..3 { - let input = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - shapes = out.shapes; - } - shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Text(t) => Some(t.galley.text().to_string()), - _ => None, - }) - .collect() - } - - /// File › Open Recent: the files first (`app.openRecent {index}`), then Clear Recent Files. - #[test] - fn open_recent_lists_the_files_then_clear() { - let tree = menu_tree(); - let file = &tree.iter().find(|(m, _)| *m == "File").unwrap().1; - let Some(Item::Sub(name, children)) = file.get(2) else { panic!("Open Recent after Open…: {:?}", file.get(2)) }; - assert_eq!(format!("File/{name}"), OPEN_RECENT); - assert!(matches!(children.as_slice(), [Item::Cmd { id, .. }] if id == "file.clearRecent")); - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert!(recent_items(&app).is_empty()); - assert!(!menu_enabled(&app, "file.clearRecent")); - app.session.prefs.note_recent_file("/work/a.designcraft"); - app.session.prefs.note_recent_file("/work/b.idml"); - let items = recent_items(&app); - let labels: Vec<_> = items - .iter() - .map(|i| match i { - Item::Cmd { label, id, params, .. } => format!("{label} {id} {params}"), - Item::Sep => "-".into(), - Item::Sub(..) => "sub".into(), - }) - .collect(); - assert_eq!(labels, ["b.idml app.openRecent {\"index\":0}", "a.designcraft app.openRecent {\"index\":1}", "-"]); - assert!(menu_enabled(&app, "file.clearRecent")); - assert!(menu_enabled(&app, "app.openRecent")); - } - - /// A recent file that is gone says so in an alert (and the start screen still lists it). - #[test] - fn open_recent_of_a_missing_file_alerts_and_the_start_screen_lists_recent_files() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert!(!start_screen_texts(&mut app).iter().any(|t| t == "Recent files"), "no section without recent files"); - app.session.prefs.note_recent_file("/nonexistent/dc-recent/gone.designcraft"); - assert!(app.run("app.openRecent", json!({"index": 0})).is_err()); - let d = app.ui.dialog.take().expect("an alert"); - assert_eq!(d.fields["title"], "Can't Open the File"); - assert_eq!(d.fields["file"], "gone.designcraft"); - assert!(d.fields["message"].as_str().unwrap().contains("can't be found")); - assert!(app.run("app.openRecent", json!({"index": 9})).is_err(), "out of range: an error, not a panic"); - app.ui.dialog = None; - let texts = start_screen_texts(&mut app); - assert!(texts.iter().any(|t| t == "Recent files"), "{texts:?}"); - assert!(texts.iter().any(|t| t == "gone"), "the card names it without `.designcraft`: {texts:?}"); - } - - /// On a short window (1366 x 768 laptops) the start screen is taller than the window; the part - /// below the fold has to be reachable by scrolling instead of being cut off. - #[test] - fn start_screen_scrolls_when_the_window_is_too_short() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx, ""); - let size = egui::vec2(1366.0, 300.0); - let mut tile_y = |events: Vec| { - let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - out.textures_delta.clear(); - out.shapes.iter().find_map(|s| match &s.shape { - // The preset tiles paint their names even when scrolled out of view (labels skip that). - egui::Shape::Text(t) if t.galley.text() == "Tabloid" => Some(t.pos.y), - _ => None, - }) - }; - let at = egui::pos2(600.0, 150.0); - let mut before = None; - for _ in 0..3 { - before = tile_y(vec![egui::Event::PointerMoved(at)]); - } - let before = before.expect("the Tabloid tile is laid out"); - let wheel = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -400.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }; - let mut after = tile_y(vec![egui::Event::PointerMoved(at), wheel]); - for _ in 0..30 { - after = tile_y(Vec::new()); - } - let after = after.expect("the Tabloid tile is laid out"); - assert!(after < before - 50.0, "the start screen should scroll: {before} -> {after}"); - } - - // Regression test for #329: on the start screen (no document) the Help menu's links were greyed out. - #[test] - fn help_links_are_enabled_without_a_document() { - let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - assert!(app.session.active().is_none()); - let ids: Vec<&str> = UI_COMMANDS.iter().map(|c| c.0).filter(|id| id.starts_with("help.")).collect(); - assert!(ids.contains(&"help.discord") && ids.contains(&"help.github"), "{ids:?}"); - for id in ids { - assert!(menu_enabled(&app, id), "{id} must work from the start screen"); - } - assert!(!menu_enabled(&app, "view.rulers"), "other UI commands still need a document"); - } - - // Regression test for #248: the start screen offered no A6 sheet (it listed only the first ten presets). - #[test] - fn start_screen_offers_every_print_preset_including_a6() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let texts = start_screen_texts(&mut app); - for p in designcraft_doc::build::PRESETS.iter().filter(|p| p.intent == designcraft_doc::Intent::Print) { - assert!(texts.iter().any(|t| t == p.name), "start screen lacks the {} card: {texts:?}", p.name); - } - assert!(texts.iter().any(|t| t == "A6"), "{texts:?}"); - let a6 = designcraft_doc::build::PRESETS.iter().find(|p| p.name == "A6").unwrap(); - assert!((a6.width - 105.0 * 72.0 / 25.4).abs() < 0.01 && (a6.height - 148.0 * 72.0 / 25.4).abs() < 0.01, "{a6:?}"); - let page = crate::panels::properties::PAGE_PRESETS.iter().find(|p| p.0 == "A6").expect("Properties page-size list has A6"); - assert!((page.1 - a6.width).abs() < 0.01 && (page.2 - a6.height).abs() < 0.01, "{page:?} vs {a6:?}"); - } - - // Regression test for #249: a menu row only reacted over its text, not across the whole row. - #[test] - fn menu_rows_are_selectable_across_the_full_width() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); - let entries = vec![cmd_item("app.preferences", Value::Null)]; - let mut tick = 0; - let mut frame = |app: &mut DesignApp, events: Vec| { - tick += 1; - let mut row = egui::Rect::NOTHING; - let mut output = - ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { - egui::Area::new(egui::Id::unique("menu_rows")).fixed_pos(egui::pos2(50.0, 50.0)).show(ui.ctx(), |ui| { - let before = ui.cursor().min; - menu_column(app, ui, &[("Test", entries.clone())]); - row = egui::Rect::from_min_max(before, ui.min_rect().max); - }); - }); - output.textures_delta.clear(); - row - }; - frame(&mut app, vec![]); - let row = frame(&mut app, vec![]); - assert!(row.width() >= 239.0, "the column is at least 240 wide: {row:?}"); - let far = egui::pos2(row.right() - 6.0, row.top() + 8.0); - for pressed in [true, false] { - frame( - &mut app, - vec![ - egui::Event::PointerMoved(far), - egui::Event::PointerButton { pos: far, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - assert!(app.ui.dialog.is_some(), "clicking the empty end of the Preferences… row must choose it"); - } - - /// Quick Apply and the menu search list no unavailable docking command and no label twice - /// among the UI commands. - #[test] - fn searched_ui_commands_are_available_and_named_once() { - let ui_ids: Vec<&str> = UI_COMMANDS.iter().map(|c| c.0).collect(); - let searched: Vec<(&str, &str)> = quick_commands().filter(|c| ui_ids.contains(&c.0)).map(|c| (c.0, c.1)).collect(); - assert!(!searched.iter().any(|c| matches!(c.0, "window.panel.window" | "window.workspace.lock" | "window.workspace")), "{searched:?}"); - assert!(searched.iter().any(|c| c.0 == "window.collapseToIcons"), "Collapse to Icons is searched"); - // Quick Apply runs an entry as `app.run(id, {})`, so each docking command it lists must - // work without params. - let docking = |id: &str| { - id.starts_with("window.panel") - || id.starts_with("window.workspace") - || id.starts_with("ui.dock") - || matches!(id, "window.floatPanel" | "window.dockPanel" | "window.collapseToIcons" | "window.resetWorkspace") - }; - let failing: Vec<(&str, String)> = searched - .iter() - .filter(|c| docking(c.0)) - .filter_map(|c| { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run(c.0, json!({})).err().map(|e| (c.0, e)) - }) - .collect(); - assert!(failing.is_empty(), "searched docking commands that fail with {{}}: {failing:?}"); - let mut labels: Vec<&str> = searched.iter().map(|c| c.1).collect(); - labels.sort_unstable(); - let before = labels.len(); - labels.dedup(); - assert_eq!(labels.len(), before, "a label twice: {searched:?}"); - } - - /// Keys a floating panel's own OS window left over run the main window's tool shortcuts, - /// Escape and the active tool's keys. - #[test] - fn forwarded_keys_run_shortcuts() { - use egui::{Event, Key, Modifiers}; - fn press(key: Key) -> Vec { - [true, false].map(|pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE }).to_vec() - } - let ctx = egui::Context::default(); - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", &json!({})).unwrap(); - let frame = app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); - app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap(); - forwarded_shortcuts(&mut app, &ctx, press(Key::P), Modifiers::NONE); - assert_ne!(app.session.tool_id(), "selection", "P picks a tool"); - forwarded_shortcuts(&mut app, &ctx, press(Key::Escape), Modifiers::NONE); - assert_eq!(app.session.tool_id(), "selection", "Escape goes back to the Selection tool"); - app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap(); - forwarded_shortcuts(&mut app, &ctx, press(Key::Delete), Modifiers::NONE); - assert!( - app.session.active().unwrap().doc.item(designcraft_doc::ItemId(frame["id"].as_u64().unwrap())).is_none(), - "Delete clears the selection" - ); - } -} +mod tests; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs new file mode 100644 index 000000000..29ad3404a --- /dev/null +++ b/crates/ui-egui/src/menus/tests.rs @@ -0,0 +1,2981 @@ +use super::*; + +/// The entries (command ids) of a menu bar menu, submenus included. +fn menu_ids(title: &str) -> Vec<&'static str> { + let items = MENUS.iter().find(|(t, _)| *t == title).map(|(_, items)| *items).unwrap_or_default(); + items.iter().filter_map(|e| e.split_once(':').map(|(_, rest)| rest.split('|').next().unwrap_or(rest))).collect() +} + +#[test] +fn view_items_are_in_the_view_menu_as_in_indesign() { + let (view, typ) = (menu_ids("View"), menu_ids("Type")); + for id in [ + "view.rotateSpread", + "view.proofSetup", + "view.proofColors", + "view.flattenerPreview", + "view.separations", + "view.taggedFrames", + "view.tagMarkers", + ] { + assert!(view.contains(&id), "{id} is in View"); + assert!(!typ.contains(&id), "{id} isn't in Type"); + } + // Screen Mode and Extras are View submenus; Show Hidden Characters stays in Type. + assert!(view.contains(&"view.screenMode") && view.contains(&"view.frameEdges")); + assert!(typ.contains(&"view.hiddenCharacters") && !view.contains(&"view.hiddenCharacters")); + // W still toggles Normal / Preview without a menu entry. + assert_eq!(ui_label("view.togglePreview").and_then(|c| c.1), Some("W")); +} + +/// The submenu paths of a menu bar menu ("View/Screen Mode"), as Edit › Menus keys them. +fn submenu_paths(title: &str) -> Vec { + let items = MENUS.iter().find(|(t, _)| *t == title).map(|(_, items)| *items).unwrap_or_default(); + let mut stack = vec![title.to_string()]; + let mut out = Vec::new(); + for e in items { + if let Some(name) = e.strip_prefix('>') { + let path = format!("{}/{name}", stack.last().map_or("", String::as_str)); + out.push(path.clone()); + stack.push(path); + } else if *e == "<" { + stack.pop(); + } + } + out +} + +/// A command's menu path names the menu entries that really hold it. +#[test] +fn define_lists_command_path_matches_the_type_menu() { + let spec = designcraft_engine::command_specs().iter().find(|c| c.id == "list.define").expect("list.define is a command"); + assert_eq!(spec.menu[0], "Type"); + assert!(submenu_paths("Type").contains(&spec.menu.join("/")), "{:?} is not a Type submenu", spec.menu); + assert!(menu_ids("Type").contains(&"list.define")); +} + +#[test] +fn screen_mode_shows_the_current_mode() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let mode = |app: &DesignApp, m: &str| checked(app, "view.screenMode", &json!({ "mode": m })); + assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(true), Some(false))); + app.ui.screen_mode = crate::ScreenMode::Preview; + assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(false), Some(true))); +} + +fn walk(items: &[Item], out: &mut Vec<(String, String, Value)>) { + for it in items { + match it { + Item::Sub(_, c) => walk(c, out), + Item::Cmd { label, id, params, .. } => out.push((label.clone(), id.clone(), params.clone())), + Item::Sep => {} + } + } +} + +/// Exercise the real dropdown, including clipping and wheel input, on a short viewport. +#[test] +fn oversized_edit_menu_scrolls_to_preferences() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 260.0)); + let mut tick = 0; + let mut frame = |app: &mut DesignApp, events: Vec| { + tick += 1; + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { + egui::MenuBar::new().ui(ui, |ui| menu_bar(app, ui)); + }); + output.textures_delta.clear(); + let mut labels = Vec::new(); + fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) { + match shape { + egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)), + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, clip, labels); + } + } + _ => {} + } + } + for shape in output.shapes { + collect(&shape.shape, shape.clip_rect, &mut labels); + } + labels + }; + frame(&mut app, vec![]); + let labels = frame(&mut app, vec![]); + let edit = labels.iter().find(|(text, _, _)| text == "Edit").unwrap().1.center(); + for pressed in [true, false] { + frame( + &mut app, + vec![ + egui::Event::PointerMoved(edit), + egui::Event::PointerButton { pos: edit, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + for _ in 0..3 { + frame(&mut app, vec![]); + } + let layer = ctx.layer_id_at(egui::pos2(edit.x + 80.0, 100.0)).expect("menu layer"); + let bounds = ctx.memory(|m| m.area_rect(layer.id)).expect("menu bounds"); + let track = egui::pos2(bounds.right() - 9.0, bounds.bottom() - 25.0); + for pressed in [true, false] { + frame( + &mut app, + vec![ + egui::Event::PointerMoved(track), + egui::Event::PointerButton { pos: track, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + assert!(egui::Popup::is_any_open(&ctx), "clicking the scroll track must not dismiss the menu"); + frame( + &mut app, + vec![ + egui::Event::PointerMoved(egui::pos2(edit.x + 80.0, 100.0)), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }, + ], + ); + let mut labels = Vec::new(); + for _ in 0..60 { + labels = frame(&mut app, vec![]); + } + let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == "Preferences…").expect("Preferences is rendered"); + assert!(screen.contains_rect(*rect) && clip.contains_rect(*rect), "Preferences must be visible after scrolling: {rect:?}, {clip:?}"); + let pos = rect.center(); + for pressed in [true, false] { + frame( + &mut app, + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); + assert!(!egui::Popup::is_any_open(&ctx), "choosing a command dismisses the menu"); +} + +#[test] +fn formatting_affects_text_sends_swatches_to_the_text() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + for (name, color) in [("Cyan", "#00ffff"), ("Magenta", "#ff00ff")] { + let created = app.run("swatch.create", json!({"name": name, "color": color})).unwrap(); + assert_eq!(created["name"], name); + } + let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap(); + let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap()); + app.run("selection.set", json!({"ids": [fid]})).unwrap(); + let text_fill = |app: &crate::DesignApp| { + let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone(); + st.char_format_at(2).over.fill.clone() + }; + let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone(); + assert!(!crate::panels::colors_affect_text(&app)); + crate::panels::apply_swatch(&mut app, false, "C=100 M=0 Y=0 K=0", None).unwrap(); + assert_eq!(frame_fill(&app), "C=100 M=0 Y=0 K=0"); + assert_eq!(text_fill(&app), None); + let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap(); + assert_eq!(r["on"], true, "toggles on"); + assert!(crate::panels::colors_affect_text(&app)); + crate::panels::apply_swatch(&mut app, false, "C=0 M=100 Y=0 K=0", Some(0.5)).unwrap(); + assert_eq!(frame_fill(&app), "C=100 M=0 Y=0 K=0", "the frame is left alone"); + assert_eq!(text_fill(&app).as_deref(), Some("C=0 M=100 Y=0 K=0")); + assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("C=0 M=100 Y=0 K=0".to_string(), 0.5))); +} + +#[test] +fn transform_menu_items_open_their_dialogs() { + for id in ["transform.move", "transform.scale", "transform.rotate", "transform.shear"] { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + activate(&mut app, id, &Value::Null); + let dialog = app.ui.dialog.as_ref().map(|d| d.id.clone()); + assert_eq!(dialog.as_deref(), Some(format!("cmd:{id}").as_str()), "{id} opens its dialog"); + } +} + +#[test] +fn pdf_export_menu_item_opens_the_dialog_or_exports() { + // No params: the menu item opens the options dialog. + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + activate(&mut app, "app.exportPdf", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfExport")); + // Explicit options: programmatic callers still export directly, opening no dialog. + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + activate(&mut app, "app.exportPdf", &json!({"path": "/tmp/x.pdf"})); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn snap_preferences_are_a_command() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let r = run_ui(&mut app, "view.snapPreferences", &json!({"smartSpacing": false, "zone": 8})).unwrap().unwrap(); + assert_eq!(r["smartSpacing"], false); + assert_eq!(r["alignEdges"], true, "unnamed switches keep their value"); + assert_eq!(r["zone"], 8.0); + assert!(!app.ui.smart_spacing && (app.ui.snap_zone - 8.0).abs() < 1e-9); + let r = run_ui(&mut app, "view.snapPreferences", &json!({"zone": -3})).unwrap().unwrap(); + assert_eq!(r["zone"], 0.0, "a negative zone turns snapping off"); +} + +/// Every command with a shortcut in effect: (command key, shortcut), in dispatch order. UI +/// commands come first: where one shares keys with an engine command (⌘N, ⌘O…) it's the one +/// with the dialog. +fn effective_shortcuts(app: &DesignApp) -> Vec<(String, String)> { + app.keymap.catalog().iter().filter_map(|b| crate::keys::shortcut(&app.keymap, &b.command).map(|s| (b.command.key(), s))).collect() +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn shortcut_edits_wait_for_the_dialog_and_the_menu_bar_owns_its_paste_chord() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + crate::shortcuts_dialog::open(&mut app, None); + for (id, p) in [ + ("window.setShortcut", json!({"id": "app.palette", "shortcut": "F2"})), + ("window.resetShortcuts", json!({})), + ("window.importShortcuts", json!({"text": ""})), + ] { + assert!(run_ui(&mut app, id, &p).unwrap().is_err(), "{id} while the dialog is open"); + } + crate::shortcuts_dialog::close(&mut app, false).unwrap(); + // A chord of the user's: the default one is the bar's from the start. + run_ui(&mut app, "window.setShortcut", &json!({"id": "edit.pasteInPlace", "shortcut": "Cmd+Alt+V", "steal": true})).unwrap().unwrap(); + let held = egui::Modifiers::COMMAND | egui::Modifiers::ALT; + app.native_menu = true; + assert_eq!(paste_chord_command(&app, held), Some("edit.pasteInPlace"), "before the bar carries it"); + app.native_shortcuts.insert("edit.pasteInPlace".into(), "Cmd+Alt+V".into()); + assert_eq!(paste_chord_command(&app, held), None, "the bar's key equivalent runs it, once"); +} + +#[test] +fn custom_shortcuts_override_defaults() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert_eq!(shortcut_of(&app, "app.preferences").as_deref(), Some("Cmd+K")); + let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "app.preferences", "shortcut": "Cmd+Alt+Shift+9"})).unwrap().unwrap(); + assert_eq!(r["shortcut"], "Cmd+Alt+Shift+9"); + assert!(effective_shortcuts(&app).contains(&("app.preferences".into(), "Cmd+Alt+Shift+9".into()))); + // Taking another command's keys reports the conflict. + let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Alt+Shift+9"})).unwrap().unwrap(); + assert_eq!(r["conflicts"], json!(["app.preferences"])); + run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": ""})).unwrap().unwrap(); + assert_eq!(shortcut_of(&app, "app.palette"), None); + assert!(run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Nope"})).unwrap().is_err()); + run_ui(&mut app, "window.resetShortcuts", &json!({})).unwrap().unwrap(); + // ⌘N is the New Document dialog, not a bare file.new. + let first_cmd_n = effective_shortcuts(&app).into_iter().find(|(_, s)| s == "Cmd+N").map(|(i, _)| i); + assert_eq!(first_cmd_n.as_deref(), Some("app.newDocumentDialog")); + assert_eq!(shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+Enter")); + assert_eq!( + crate::keys::chord_text(egui::Modifiers { command: true, shift: true, ..Default::default() }, egui::Key::K).as_deref(), + Some("Cmd+Shift+K") + ); + if cfg!(target_os = "macos") { + assert_eq!(shortcut_text("Cmd+Alt+3"), "⌥⌘3"); + assert_eq!(shortcut_text("Cmd+Shift+."), "⇧⌘."); + } else { + assert_eq!(shortcut_text("Cmd+Alt+3"), "Ctrl+Alt+3"); + } +} + +/// One frame of key presses through the shortcut dispatcher. +fn press_keys(app: &mut crate::DesignApp, ctx: &egui::Context, keys: &[(egui::Key, egui::Modifiers)]) { + let events = keys + .iter() + .flat_map(|&(key, modifiers)| [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers })) + .collect(); + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| shortcuts(app, &ui.ctx().clone())).textures_delta.clear(); +} + +#[test] +fn shortcuts_saved_as_a_map_by_older_versions_load_unchanged() { + let saved = br#"{"shortcuts": {"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": [""]}}"#; + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui = crate::UiState::from_preferences_json(saved).unwrap(); + app.sync_keymap(); + assert_eq!(shortcut_of(&app, "app.preferences").as_deref(), Some("Cmd+Alt+Shift+9")); + assert_eq!(shortcut_of(&app, "app.palette"), None, "a removed default stays removed"); + assert_eq!(shortcut_of(&app, "file.close"), None); + assert_eq!(shortcut_of(&app, "app.save").as_deref(), Some("Cmd+S")); + // Saved again it reads back the same, in the map form an older version reads. + let resaved = serde_json::to_vec(&app.ui).unwrap(); + assert_eq!(crate::UiState::from_preferences_json(&resaved).unwrap().shortcuts, app.ui.shortcuts); + let saved: Value = serde_json::from_slice(&resaved).unwrap(); + assert_eq!(saved["shortcuts"], json!({"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": ""})); +} + +#[test] +fn panel_shortcuts_open_their_panels() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let shown = |app: &crate::DesignApp, p: &str| crate::panel_docking::showing(app, p); + assert!(!shown(&app, "layers")); + press_keys(&mut app, &ctx, &[(egui::Key::F7, egui::Modifiers::NONE)]); + assert!(shown(&app, "layers"), "F7 opens Layers"); + // A panel without a default key takes one. + let r = run_ui(&mut app, "window.setShortcut", &json!({"id": "window.panel", "params": {"panel": "links"}, "shortcut": "Shift+F12"})) + .unwrap() + .unwrap(); + assert_eq!(r["shortcut"], "Shift+F12"); + press_keys(&mut app, &ctx, &[(egui::Key::F12, egui::Modifiers::SHIFT)]); + assert!(shown(&app, "links"), "the new key opens Links"); +} + +#[test] +fn a_reassigned_tool_key_selects_the_tool_and_the_old_key_does_not() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let none = egui::Modifiers::NONE; + run_ui(&mut app, "window.setShortcut", &json!({"id": "pen", "shortcut": "Y"})).unwrap().unwrap(); + press_keys(&mut app, &ctx, &[(egui::Key::P, none)]); + assert_eq!(app.session.tool_id(), "selection", "P no longer selects the Pen"); + press_keys(&mut app, &ctx, &[(egui::Key::Y, none)]); + assert_eq!(app.session.tool_id(), "pen"); + // Tools sharing a key take turns. + press_keys(&mut app, &ctx, &[(egui::Key::B, none)]); + assert_eq!(app.session.tool_id(), "contentCollector"); + press_keys(&mut app, &ctx, &[(egui::Key::B, none)]); + assert_eq!(app.session.tool_id(), "contentPlacer"); +} + +#[test] +fn split_window_panes_have_their_own_views() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp| { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app); + assert_eq!(run_ui(&mut app, "window.split", &json!({})).unwrap().unwrap(), json!(true)); + frame(&mut app); + frame(&mut app); + // Both panes have a canvas, each half as wide. + let r0 = app.canvas_rect.unwrap(); + let r1 = app.other_pane.as_ref().and_then(|o| o.1).unwrap(); + assert!(r0.width() < 800.0 && r1.width() < 800.0 && (r0.center().x - r1.center().x).abs() > 300.0, "{r0:?} {r1:?}"); + // Zooming the right pane leaves the left alone. + app.switch_pane(1); + let z0 = app.view().unwrap().zoom; + crate::canvas::set_zoom(&mut app, z0 * 3.0); + app.switch_pane(0); + assert!((app.view().unwrap().zoom - z0).abs() < 1e-9); + app.switch_pane(1); + assert!((app.view().unwrap().zoom - z0 * 3.0).abs() < 1e-6); + assert_eq!(run_ui(&mut app, "window.split", &json!({})).unwrap().unwrap(), json!(false)); + assert_eq!(app.pane, 0); + frame(&mut app); +} + +#[test] +fn split_window_dispatches_text_once_to_the_shared_document() { + for focus_pane in [0, 1] { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let made = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap(); + let story = made["story"].as_u64().unwrap(); + app.session.set_tool("type"); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + assert!(app.session.wants_text()); + app.run("window.split", json!({"on": true})).unwrap(); + app.focus_pane = focus_pane; + + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let undo_before = app.session.active().unwrap().history.undo.len(); + frame(&mut app, vec![egui::Event::Text("A".into())]); + let text = app.run("story.get", json!({"story": story})).unwrap(); + assert_eq!(text["text"], "A", "one key press with pane {focus_pane} focused"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.run("story.get", json!({"story": story})).unwrap()["text"], ""); + + // A press and key arriving together must use the newly focused pane, whichever + // canvas is drawn first. Middle-click changes pane focus without moving the caret. + let other = app.other_pane.as_ref().and_then(|p| p.1).unwrap().center(); + frame(&mut app, vec![egui::Event::PointerMoved(other)]); + frame( + &mut app, + vec![ + egui::Event::PointerButton { pos: other, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::Text("B".into()), + ], + ); + assert_eq!(app.focus_pane, 1 - focus_pane); + assert_eq!(app.run("story.get", json!({"story": story})).unwrap()["text"], "B", "a key in the pane-switch frame is dispatched once"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1); + } +} + +#[test] +fn split_window_click_focus_routes_menu_zoom_but_hover_scroll_stays_local() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("window.split", json!({"on": true})).unwrap(); + let ctx = egui::Context::default(); + let mut time = 0.0; + let mut frame = |app: &mut crate::DesignApp, events| { + time += 0.1; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + time: Some(time), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + for _ in 0..3 { + frame(&mut app, vec![]); + } + let left = app.canvas_rect.unwrap().center(); + let right = app.other_pane.as_ref().and_then(|p| p.1).unwrap().center(); + let cameras = |app: &mut crate::DesignApp| { + let current = app.pane; + app.switch_pane(0); + let left = *app.view().unwrap(); + app.switch_pane(1); + let right = *app.view().unwrap(); + app.switch_pane(current); + [left, right] + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![egui::Event::PointerMoved(right)]); + frame(&mut app, vec![button(right, true)]); + frame(&mut app, vec![button(right, false)]); + assert_eq!((app.pane, app.focus_pane), (1, 1)); + let before = cameras(&mut app); + app.run("view.zoom", json!({"zoom": 2.0})).unwrap(); + let zoomed = cameras(&mut app); + assert_eq!(zoomed[0], before[0], "menu zoom leaves the other camera alone"); + assert!((zoomed[1].zoom - 2.0).abs() < 1e-9); + + frame(&mut app, vec![egui::Event::PointerMoved(left)]); + frame( + &mut app, + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -40.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }], + ); + let scrolled = cameras(&mut app); + assert_eq!(scrolled[1], zoomed[1], "hover scroll leaves the focused camera alone"); + assert_ne!(scrolled[0].origin, zoomed[0].origin); + assert_eq!((app.pane, app.focus_pane), (1, 1), "hovering does not move menu focus"); + + frame(&mut app, vec![button(left, true)]); + frame(&mut app, vec![button(left, false)]); + assert_eq!((app.pane, app.focus_pane), (0, 0)); + app.run("view.zoom", json!({"zoom": 1.0})).unwrap(); + let final_views = cameras(&mut app); + assert!((final_views[0].zoom - 1.0).abs() < 1e-9); + assert_eq!(final_views[1], scrolled[1]); +} + +#[test] +fn split_window_contextual_bars_have_independent_widget_ids() { + fn id_warnings(shape: &egui::Shape, found: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| id_warnings(shape, found)), + egui::Shape::Text(text) if text.galley.text().contains("use of widget ID") => found.push(text.galley.text().to_string()), + _ => {} + } + } + + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + for rect in [[36, 36, 280, 180], [300, 36, 550, 180]] { + app.run("frame.create", json!({"rect": rect, "content": "unassigned"})).unwrap(); + } + app.run("edit.selectAll", json!({})).unwrap(); + app.run("window.split", json!({"on": true})).unwrap(); + let ctx = egui::Context::default(); + ctx.options_mut(|options| options.warn_on_id_clash = true); + let mut warnings = Vec::new(); + for _ in 0..4 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + warnings.clear(); + for shape in &output.shapes { + id_warnings(&shape.shape, &mut warnings); + } + output.textures_delta.clear(); + } + assert!(warnings.is_empty(), "both bars reused the same interactive widget IDs: {warnings:?}"); + let bars: Vec<_> = + (0_u8..2).map(|pane| ctx.memory(|memory| memory.area_rect(egui::Id::unique(("task_bar", egui::ViewportId::ROOT, pane)))).unwrap()).collect(); + assert!(!bars[0].intersects(bars[1]), "each pane keeps its own bar: {bars:?}"); +} + +#[test] +fn show_document_grid_toggles_from_the_grids_and_guides_menu() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let tree = menu_tree(); + let mut items = vec![]; + for (_, entries) in &tree { + walk(entries, &mut items); + } + assert!(items.iter().any(|(label, id, _)| id == "view.documentGrid" && label == "Show/Hide Document Grid")); + assert_eq!(shortcut_of(&app, "view.documentGrid").as_deref(), Some("Cmd+'")); + assert_eq!(checked(&app, "view.documentGrid", &json!({})), Some(false)); + assert_eq!(run_ui(&mut app, "view.documentGrid", &json!({})).unwrap().unwrap(), json!(true)); + assert!(app.ui.document_grid); + assert_eq!(checked(&app, "view.documentGrid", &json!({})), Some(true)); + run_ui(&mut app, "view.documentGrid", &json!({})).unwrap().unwrap(); + assert!(!app.ui.document_grid); +} + +#[test] +fn interface_language_switches_and_validates() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + run_ui(&mut app, "app.language", &json!({"lang": "de"})).unwrap().unwrap(); + assert_eq!(app.ui.language, "de"); + assert_eq!(checked(&app, "app.language", &json!({"lang": "de"})), Some(true)); + assert!(run_ui(&mut app, "app.language", &json!({"lang": "xx"})).unwrap().is_err()); + assert_eq!(app.ui.language, "de"); + // The language is set in Preferences, not from a menu; without `lang` the command opens it. + let mut items = Vec::new(); + for (_, entries) in menu_tree() { + walk(&entries, &mut items); + } + assert!(!items.iter().any(|(_, id, _)| id == "app.language"), "no menu item sets the language"); + run_ui(&mut app, "app.language", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); + assert_eq!(app.ui.language, "de"); +} + +#[test] +fn every_interface_language_is_selectable_persisted_and_keeps_document_data() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мої слова · Zażółć gęślą jaźń"})).unwrap(); + let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); + for (code, _) in crate::i18n::LANGUAGES { + run_ui(&mut app, "app.language", &json!({"lang": code})).unwrap().unwrap(); + assert_eq!(app.ui.language, *code); + assert_eq!(checked(&app, "app.language", &json!({"lang": code})), Some(true), "{code}"); + assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(), "{code}"); + let bytes = serde_json::to_vec(&app.ui).unwrap(); + let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(restored.language, *code); + } +} + +#[test] +fn arabic_dialog_and_language_switch_keep_finite_widget_geometry() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp| { + for _ in 0..4 { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0))), + max_texture_side: Some(8192), + ..Default::default() + }, + |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + ); + output.textures_delta.clear(); + } + }; + app.run("app.language", json!({"lang": "ar"})).unwrap(); + frame(&mut app); + app.run("app.newDocumentDialog", json!({})).unwrap(); + frame(&mut app); // egui asserts that all allocated rectangles are finite. + crate::dialogs::confirm(&mut app).unwrap(); + frame(&mut app); + assert_eq!(app.session.documents().len(), 1); + for lang in ["uk", "ru", "zh", "", "ar", "pt-br", "it", "cs", "pl", "ka"] { + app.run("app.language", json!({"lang": lang})).unwrap(); + frame(&mut app); + } +} + +#[test] +fn story_direction_is_checked() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 400], "content": "text", "text": "縦", "vertical": true})).unwrap(); + assert_eq!(checked(&app, "type.storyDirection", &json!({"vertical": true})), Some(true)); + assert_eq!(checked(&app, "type.storyDirection", &json!({"vertical": false})), Some(false)); +} + +#[test] +fn proof_setup_and_colors() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert_eq!(checked(&app, "view.proofColors", &Value::Null), Some(false)); + let r = run_ui(&mut app, "view.proofSetup", &json!({"target": "deuteranopia"})).unwrap().unwrap(); + assert_eq!(r["on"], true); + assert_eq!(checked(&app, "view.proofSetup", &json!({"target": "deuteranopia"})), Some(true)); + run_ui(&mut app, "view.proofSetup", &json!({"simulatePaper": "toggle"})).unwrap().unwrap(); + assert!(app.ui.proof_setup.simulate_paper); + run_ui(&mut app, "view.proofColors", &json!({})).unwrap().unwrap(); + assert!(!app.ui.proof_colors); + assert!(run_ui(&mut app, "view.proofSetup", &json!({"target": "nope"})).unwrap().is_err()); +} + +#[test] +fn lock_guides_and_lock_column_guides_are_checked_in_grids_and_guides() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let view = menu_ids("View"); + assert!(view.contains(&"view.lockGuides") && view.contains(&"view.lockColumnGuides")); + assert_eq!(ui_label("view.lockGuides").and_then(|c| c.1), Some("Cmd+Alt+;")); + // Lock Guides: off at first, toggles, and `on` sets it. + assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(false)); + assert_eq!(app.run("view.lockGuides", json!({})).unwrap(), json!(true)); + assert!(app.ui.guides_locked); + assert_eq!(app.run("view.lockGuides", json!({"on": true})).unwrap(), json!(true)); + assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(true)); + assert_eq!(app.run("view.lockGuides", json!({"on": false})).unwrap(), json!(false)); + // Lock Column Guides: the document's setting, on in new documents. + assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(true)); + app.run("view.lockColumnGuides", json!({})).unwrap(); + assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(false)); +} + +#[test] +fn fitting_has_indesigns_shortcuts() { + // LYH Studio episode 6 (7:00): "Fit Content to Frame (Ctrl + Shift + Alt + C)" fills the + // photo frames proportionally. + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png(); + let f = app.run("frame.create", json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].as_u64().unwrap(); + app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "a.png", "frame": f})).unwrap(); + app.run("selection.set", json!({"ids": [f]})).unwrap(); + let width = |app: &crate::DesignApp| { + let it = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone(); + let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("graphic") }; + it.xf.transform_rect_bbox(g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1))).width() + }; + for (id, keys) in [ + ("fit.fillFrameProportionally", "Cmd+Alt+Shift+C"), + ("fit.contentProportionally", "Cmd+Alt+Shift+E"), + ("fit.frameToContent", "Cmd+Alt+C"), + ("fit.contentToFrame", "Cmd+Alt+E"), + ("fit.centerContent", "Cmd+Shift+E"), + ] { + assert_eq!(shortcut_of(&app, id).as_deref(), Some(keys)); + } + let ctx = egui::Context::default(); + let press = |app: &mut crate::DesignApp, key: egui::Key| { + let modifiers = + egui::Modifiers { alt: true, ctrl: !cfg!(target_os = "macos"), shift: true, mac_cmd: cfg!(target_os = "macos"), command: true }; + let input = egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| shortcuts(app, &ui.ctx().clone())); + out.textures_delta.clear(); + }; + press(&mut app, egui::Key::C); + assert!((width(&app) - 400.0).abs() < 1e-6, "filled: {}", width(&app)); + press(&mut app, egui::Key::E); + assert!((width(&app) - 200.0).abs() < 1e-6, "fitted: {}", width(&app)); +} + +#[test] +fn tab_and_presentation_hide_floating_panels_too() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp| { + for _ in 0..2 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + } + }; + // The docked panel's tab and a floating panel group. + let tab = crate::panel_docking::tab_id("preflight"); + let docked = || ctx.read_response(tab).is_some(); + let group = crate::panel_docking::floating_layer("preflight"); + let shown = |layer: egui::LayerId| ctx.memory(|m| m.areas().is_visible(&layer)); + let toggles = [ + ("window.hidePanels", json!({}), json!({})), + ("window.hidePanelsExceptTools", json!({}), json!({})), + ("view.screenMode", json!({"mode": "presentation"}), json!({"mode": "normal"})), + ]; + app.run("window.panel", json!({"panel": "preflight"})).unwrap(); + frame(&mut app); + assert!(docked()); + for (id, hide, show) in &toggles { + app.run(id, hide.clone()).unwrap(); + frame(&mut app); + assert!(!docked(), "{id} hides the dock"); + app.run(id, show.clone()).unwrap(); + frame(&mut app); + assert!(docked(), "{id} again brings it back"); + } + app.run("window.floatPanel", json!({"panel": "preflight", "x": 400, "y": 200})).unwrap(); + frame(&mut app); + assert!(app.ui.docking.is_some() && shown(group)); + for (id, hide, show) in &toggles { + app.run(id, hide.clone()).unwrap(); + frame(&mut app); + assert!(!shown(group), "{id} hides the floating panel"); + app.run(id, show.clone()).unwrap(); + frame(&mut app); + assert!(shown(group), "{id} again brings it back"); + } +} + +#[test] +fn tab_hides_panels_and_documents_cycle() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert_eq!(shortcut_of(&app, "window.hidePanels").as_deref(), Some("Tab")); + run_ui(&mut app, "window.hidePanels", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.hidden_panels, 1); + run_ui(&mut app, "window.hidePanelsExceptTools", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.hidden_panels, 2); + run_ui(&mut app, "window.hidePanelsExceptTools", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.hidden_panels, 0); + for _ in 0..3 { + app.session.execute("file.new", &json!({})).unwrap(); + } + assert_eq!(app.session.active_index(), Some(2)); + run_ui(&mut app, "window.nextDocument", &json!({})).unwrap().unwrap(); + assert_eq!(app.session.active_index(), Some(0)); + run_ui(&mut app, "window.previousDocument", &json!({})).unwrap().unwrap(); + assert_eq!(app.session.active_index(), Some(2)); +} + +#[test] +fn rotate_spread_view() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 3})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp| { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app); + frame(&mut app); + assert_eq!(run_ui(&mut app, "view.rotateSpread", &json!({"angle": 90})).unwrap().unwrap(), json!(90)); + frame(&mut app); + // Only the spread in view turns: its canvas footprint swaps width and height. + let d = app.session.active().unwrap().doc.clone(); + let turned: Vec = d.spreads.iter().enumerate().filter(|(_, sp)| sp.pages[0].view_rotation == 1).map(|(i, _)| i).collect(); + assert_eq!(turned.len(), 1); + let layout = designcraft_tools::CanvasLayout::new(&d, false); + let slot = layout.slots[turned[0]]; + let b = d.spreads[turned[0]].bounds(); + assert!((slot.bounds.width() - b.height()).abs() < 1e-6 && (slot.bounds.height() - b.width()).abs() < 1e-6); + assert_eq!(checked(&app, "view.rotateSpread", &json!({"angle": 0})), Some(false)); + run_ui(&mut app, "view.rotateSpread", &json!({"angle": 0})).unwrap().unwrap(); + assert_eq!(checked(&app, "view.rotateSpread", &json!({"angle": 0})), Some(true)); + frame(&mut app); +} + +#[test] +fn hand_tool_hold_starts_power_zoom() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, t: f64, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + time: Some(t), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app, 0.0, vec![]); + frame(&mut app, 0.05, vec![]); + app.select_tool("hand"); + let r = app.canvas_rect.unwrap(); + let p = r.center(); + let z0 = app.view().unwrap().zoom; + frame(&mut app, 0.1, vec![egui::Event::PointerMoved(p)]); + frame( + &mut app, + 0.2, + vec![egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }], + ); + frame(&mut app, 0.4, vec![]); + assert!(app.power_zoom.is_none(), "not yet"); + frame(&mut app, 0.8, vec![]); + assert!(app.power_zoom.is_some(), "holding still starts Power Zoom"); + frame( + &mut app, + 0.9, + vec![egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }], + ); + assert!(app.power_zoom.is_none()); + assert!((app.view().unwrap().zoom - z0).abs() < 1e-9, "back at the zoom it started from"); +} + +#[test] +fn middle_drag_pans_with_any_tool() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // A drawing tool: a primary drag would make a frame, a middle drag must not. + app.select_tool("rectangleFrame"); + let p = app.canvas_rect.unwrap().center(); + let v0 = *app.view().unwrap(); + let items = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads.iter().map(|s| s.items.len()).sum::(); + let items0 = items(&app); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; + frame(&mut app, vec![egui::Event::PointerMoved(p), button(p, true)]); + for i in 1..=8 { + frame(&mut app, vec![egui::Event::PointerMoved(p + egui::vec2(10.0 * i as f32, 5.0 * i as f32))]); + } + frame(&mut app, vec![button(p + egui::vec2(80.0, 40.0), false)]); + let v = *app.view().unwrap(); + assert!((v.zoom - v0.zoom).abs() < 1e-9, "panning keeps the zoom"); + assert!(v.origin.x < v0.origin.x && v.origin.y < v0.origin.y, "dragging right/down moves the view: {v0:?} -> {v:?}"); + assert_eq!(items(&app), items0, "the tool saw nothing"); +} + +#[test] +fn layout_menu_goes_through_pages_and_spreads_with_their_shortcuts() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap(); + let spread = |app: &crate::DesignApp| { + let st = app.session.active().unwrap(); + crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // The Layout menu lists them, as InDesign's does, before Go to Page. + let layout = MENUS.iter().find(|m| m.0 == "Layout").unwrap().1; + let at = |id: &str| layout.iter().position(|e| e.starts_with(&format!("ui:{id}"))).unwrap(); + assert!(at("view.firstPage") < at("view.previousPage")); + assert!(at("view.previousPage") < at("view.nextPage")); + assert!(at("view.nextPage") < at("view.lastPage")); + assert!(at("view.lastPage") < at("view.nextSpread")); + assert!(at("view.nextSpread") < at("view.previousSpread")); + assert!(at("view.previousSpread") < at("view.goToPage")); + let shift = egui::Modifiers::SHIFT; + let cmd_shift = egui::Modifiers { shift: true, command: true, ctrl: true, ..Default::default() }; + let alt = egui::Modifiers::ALT; + // Pages 1 | 2-3 | 4-5 | 6-7. + frame(&mut app, key(egui::Key::PageDown, shift)); + assert_eq!(page(&app), 1, "Next Page"); + frame(&mut app, key(egui::Key::PageDown, shift)); + assert_eq!(page(&app), 2, "Next Page goes to the right page of the spread"); + frame(&mut app, key(egui::Key::PageUp, shift)); + assert_eq!(page(&app), 1, "Previous Page"); + frame(&mut app, key(egui::Key::PageDown, cmd_shift)); + assert_eq!(page(&app), 6, "Last Page"); + frame(&mut app, key(egui::Key::PageDown, shift)); + assert_eq!(page(&app), 6, "Next Page stops at the last page"); + frame(&mut app, key(egui::Key::PageUp, cmd_shift)); + assert_eq!(page(&app), 0, "First Page"); + frame(&mut app, key(egui::Key::PageUp, shift)); + assert_eq!(page(&app), 0, "Previous Page stops at the first page"); + frame(&mut app, key(egui::Key::PageDown, alt)); + assert_eq!(spread(&app), 1, "Next Spread"); + frame(&mut app, key(egui::Key::PageDown, alt)); + frame(&mut app, key(egui::Key::PageDown, alt)); + frame(&mut app, key(egui::Key::PageDown, alt)); + assert_eq!(spread(&app), 3, "Next Spread stops at the last spread"); + frame(&mut app, key(egui::Key::PageUp, alt)); + assert_eq!(spread(&app), 2, "Previous Spread"); + // The spread is centred, the zoom kept. + let zoom = app.view().unwrap().zoom; + app.run("view.previousSpread", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let slot = designcraft_tools::layout::CanvasLayout::new(&st.doc, false).slots[1]; + let (v, r) = (*app.view().unwrap(), app.canvas_rect.unwrap()); + let centre = (v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom); + assert!((centre.0 - slot.bounds.center().x).abs() < 1e-6 && (centre.1 - slot.bounds.center().y).abs() < 1e-6); + assert_eq!(v.zoom, zoom); +} + +#[test] +fn go_back_and_go_forward_retrace_the_pages_viewed() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap(); + let can = |app: &crate::DesignApp| (menu_enabled(app, "view.goBack"), menu_enabled(app, "view.goForward")); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // In the Layout menu after Go to Page. + let layout = MENUS.iter().find(|m| m.0 == "Layout").unwrap().1; + let at = |id: &str| layout.iter().position(|e| *e == format!("ui:{id}")).unwrap(); + assert_eq!(at("view.goBack"), at("view.goToPage") + 1); + assert_eq!(at("view.goForward"), at("view.goBack") + 1); + assert_eq!(can(&app), (false, false), "one page viewed: nowhere to go"); + let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; + let cmd_shift = egui::Modifiers { shift: true, ..cmd }; + let shift = egui::Modifiers::SHIFT; + // Pages viewed: 1, 5, 7. + app.run("view.goToPage", json!({"page": 5})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, key(egui::Key::PageDown, cmd_shift)); + assert_eq!(page(&app), 6); + frame(&mut app, vec![]); + assert_eq!(can(&app), (true, false)); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(page(&app), 4, "Go Back"); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(page(&app), 0, "Go Back again"); + frame(&mut app, vec![]); + assert_eq!(can(&app), (false, true), "back at the first page viewed"); + frame(&mut app, key(egui::Key::PageDown, cmd)); + assert_eq!(page(&app), 4, "Go Forward"); + frame(&mut app, key(egui::Key::PageDown, cmd)); + assert_eq!(page(&app), 6, "Go Forward again"); + frame(&mut app, vec![]); + assert_eq!(can(&app), (true, false)); + // After going back, viewing another page drops the pages ahead. + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(page(&app), 4); + frame(&mut app, key(egui::Key::PageDown, shift)); + assert_eq!(page(&app), 5, "Next Page"); + frame(&mut app, vec![]); + assert_eq!(can(&app), (true, false), "nothing ahead after a new page"); + frame(&mut app, key(egui::Key::PageDown, cmd)); + assert_eq!(page(&app), 5, "Go Forward does nothing"); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(page(&app), 4, "Go Back returns to the page before Next Page"); +} + +#[test] +fn go_back_waits_for_the_view_to_be_fitted() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp| { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app); + frame(&mut app); + app.run("view.goToPage", json!({"page": 5})).unwrap(); + frame(&mut app); + assert!(menu_enabled(&app, "view.goBack")); + // Leaving parent pages through the Pages panel: the canvas refits on the next frame. + app.view_mut().unwrap().fitted = false; + assert!(!menu_enabled(&app, "view.goBack"), "the refit would replace where Go Back went"); + crate::canvas::go_through_history(&mut app, -1); + frame(&mut app); + assert!(menu_enabled(&app, "view.goBack"), "the unfitted Go Back used no history entry"); +} + +#[test] +fn next_spread_at_the_last_spread_is_no_jump() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + let page = |app: &crate::DesignApp| crate::canvas::current_page(app).unwrap(); + let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; + let alt = egui::Modifiers::ALT; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Pages 1 | 2-3 | 4-5 | 6-7: page 6 is the left page of the last spread. + app.run("view.goToPage", json!({"page": 6})).unwrap(); + frame(&mut app, vec![]); + assert_eq!(page(&app), 5); + // Next Spread has no spread to go to; centring the last one moves the view to its fold. + frame(&mut app, key(egui::Key::PageDown, alt)); + frame(&mut app, key(egui::Key::PageDown, alt)); + assert_ne!(page(&app), 5, "the view moved to the right page"); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(page(&app), 0, "Go Back returns to the page before Go to Page"); + assert!(!menu_enabled(&app, "view.goBack")); +} + +#[test] +fn go_back_returns_to_the_view_a_jump_left_and_scrolling_adds_no_entry() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + let spread = |app: &crate::DesignApp| { + let st = app.session.active().unwrap(); + crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() + }; + let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; + let alt = egui::Modifiers::ALT; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Pages 1 | 2-3 | 4-5 | 6-7. Spread 2-3 fitted: the view centre is on the fold. + frame(&mut app, key(egui::Key::PageDown, alt)); + app.run("view.fitSpread", json!({})).unwrap(); + frame(&mut app, vec![]); + let before = *app.view().unwrap(); + frame(&mut app, key(egui::Key::PageDown, alt)); + assert_eq!(spread(&app), 2, "Next Spread"); + frame(&mut app, key(egui::Key::PageUp, cmd)); + let v = *app.view().unwrap(); + assert!((v.origin - before.origin).hypot() < 1e-6, "Go Back shows the spread as it was: {:?} vs {:?}", v.origin, before.origin); + assert_eq!(v.zoom, before.zoom); + // Zoomed in after the jump: Go Back keeps the magnification in use, as InDesign's does, and + // centres the same place. + let centre = |app: &crate::DesignApp| { + let (v, r) = (app.view().unwrap(), app.canvas_rect.unwrap()); + designcraft_geom::Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom) + }; + let place = centre(&app); + frame(&mut app, key(egui::Key::PageDown, alt)); + app.run("view.zoomIn", json!({})).unwrap(); + let zoomed = app.view().unwrap().zoom; + assert!(zoomed > before.zoom); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(app.view().unwrap().zoom, zoomed, "the zoom in use is kept"); + assert!((centre(&app) - place).hypot() < 1e-6, "the same place: {:?} vs {place:?}", centre(&app)); + // Scrolling down two spreads is not a jump: Go Forward keeps its page, and Go Back skips + // from where the scroll ended straight to the page before the first jump. + let slots = designcraft_tools::layout::CanvasLayout::new(&app.session.active().unwrap().doc, false).slots; + app.view_mut().unwrap().origin.y += slots[3].bounds.center().y - slots[1].bounds.center().y; + frame(&mut app, vec![]); + assert_eq!(spread(&app), 3); + assert!(menu_enabled(&app, "view.goForward"), "scrolling kept the page ahead"); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(spread(&app), 0, "Go Back"); + assert!(!menu_enabled(&app, "view.goBack"), "the scroll added no entry"); + frame(&mut app, key(egui::Key::PageDown, cmd)); + assert_eq!(spread(&app), 3, "Go Forward returns to where the scroll ended"); + frame(&mut app, key(egui::Key::PageDown, cmd)); + assert_eq!(spread(&app), 2); +} + +#[test] +fn go_back_after_presentation_returns_to_the_last_spread_presented() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + let spread = |app: &crate::DesignApp| { + let st = app.session.active().unwrap(); + crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() + }; + let cmd = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Scrolled off the page's centre, so the place Go Back returns to is not just the page. + let view = app.view_mut().unwrap(); + view.origin.x += 40.0; + view.origin.y += 60.0; + frame(&mut app, vec![]); + assert_eq!(spread(&app), 0); + let before = *app.view().unwrap(); + // Presentation goes on to spreads 1 and 2; leaving it puts spread 0 back as it was. + app.run("view.screenMode", json!({"mode": "presentation"})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, key(egui::Key::ArrowRight, egui::Modifiers::NONE)); + frame(&mut app, key(egui::Key::ArrowRight, egui::Modifiers::NONE)); + assert_eq!(spread(&app), 2); + app.run("view.screenMode", json!({"mode": "normal"})).unwrap(); + frame(&mut app, vec![]); + assert_eq!(spread(&app), 0); + assert!(!menu_enabled(&app, "view.goForward")); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(spread(&app), 2, "Go Back shows the last spread presented"); + frame(&mut app, key(egui::Key::PageUp, cmd)); + assert_eq!(spread(&app), 0, "Go Back again, the view Presentation was entered from"); + let v = *app.view().unwrap(); + assert!((v.origin - before.origin).hypot() < 1e-6, "where it was: {:?} vs {:?}", v.origin, before.origin); + assert!(!menu_enabled(&app, "view.goBack"), "the presentation is one jump: spread 1 isn't kept"); + frame(&mut app, key(egui::Key::PageDown, cmd)); + assert_eq!(spread(&app), 2, "Go Forward"); +} + +#[test] +fn presentation_shows_one_spread_and_goes_through_them_with_keys_and_clicks() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages": 7, "facingPages": true})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [100, 100, 300, 300]})).unwrap(); + let id = app.session.active().unwrap().selection.items[0]; + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }, + ] + }; + let click = |pos: egui::Pos2, modifiers: egui::Modifiers| { + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers }, + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers }, + ] + }; + let spread = |app: &crate::DesignApp| { + let st = app.session.active().unwrap(); + crate::canvas::current_slot(app, &designcraft_tools::layout::CanvasLayout::new(&st.doc, false)).unwrap() + }; + // The spread fills the screen: as wide or as tall as it, centred. + let fills = |app: &crate::DesignApp| { + let st = app.session.active().unwrap(); + let b = designcraft_tools::layout::CanvasLayout::new(&st.doc, false).slots[spread(app)].bounds; + let (v, r) = (*app.view().unwrap(), app.canvas_rect.unwrap()); + let (w, h) = (b.width() * v.zoom, b.height() * v.zoom); + let x0 = (b.x0 - v.origin.x) * v.zoom; + let y0 = (b.y0 - v.origin.y) * v.zoom; + ((w - r.width() as f64).abs() < 0.01 || (h - r.height() as f64).abs() < 0.01) + && w <= r.width() as f64 + 0.01 + && h <= r.height() as f64 + 0.01 + && (x0 * 2.0 + w - r.width() as f64).abs() < 0.01 + && (y0 * 2.0 + h - r.height() as f64).abs() < 0.01 + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // The user's own view (zoomed in, scrolled) comes back after Presentation. + let view = app.view_mut().unwrap(); + view.zoom = 2.0; + view.origin.x += 150.0; + view.origin.y += 300.0; + let before = *app.view().unwrap(); + app.run("view.screenMode", json!({"mode": "presentation"})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + assert_eq!(app.canvas_rect.unwrap().size(), egui::vec2(1400.0, 900.0), "the whole window"); + assert_eq!(spread(&app), 0); + assert!(fills(&app)); + let bounds = app.session.active().unwrap().doc.item(id).unwrap().bounds(); + frame(&mut app, key(egui::Key::ArrowRight)); + frame(&mut app, vec![]); + assert_eq!(spread(&app), 1, "Right Arrow shows the next spread"); + assert!(fills(&app)); + assert_eq!(app.session.active().unwrap().doc.item(id).unwrap().bounds(), bounds, "the arrow doesn't nudge the selection"); + frame(&mut app, key(egui::Key::PageDown)); + assert_eq!(spread(&app), 2, "Page Down"); + frame(&mut app, key(egui::Key::ArrowLeft)); + assert_eq!(spread(&app), 1, "Left Arrow"); + frame(&mut app, key(egui::Key::End)); + assert_eq!(spread(&app), 3, "End"); + frame(&mut app, key(egui::Key::ArrowRight)); + assert_eq!(spread(&app), 3, "the last spread stays"); + frame(&mut app, key(egui::Key::Home)); + assert_eq!(spread(&app), 0, "Home"); + frame(&mut app, key(egui::Key::PageUp)); + assert_eq!(spread(&app), 0, "the first spread stays"); + let c = app.canvas_rect.unwrap().center(); + frame(&mut app, click(c, egui::Modifiers::NONE)); + frame(&mut app, vec![]); + assert_eq!(spread(&app), 1, "a click shows the next spread"); + assert!(fills(&app)); + frame(&mut app, click(c, egui::Modifiers::SHIFT)); + frame(&mut app, vec![]); + assert_eq!(spread(&app), 0, "Shift-click the previous one"); + assert_eq!(app.session.active().unwrap().selection.items, vec![id], "clicks don't select"); + assert_eq!(app.session.tool_id(), "selection"); + // Out of Presentation, the view is the one it was entered from, and the arrow keys nudge + // again. + app.run("view.screenMode", json!({"mode": "normal"})).unwrap(); + assert_eq!(*app.view().unwrap(), before); + frame(&mut app, vec![]); + frame(&mut app, key(egui::Key::ArrowRight)); + assert_ne!(app.session.active().unwrap().doc.item(id).unwrap().bounds(), bounds); +} + +#[test] +fn tool_shortcuts_work_after_drawing_on_the_canvas() { + // Clicking the canvas gives it keyboard focus; single-key tool shortcuts must still switch + // tools without pressing Esc first (#1). + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }, + ] + }; + let button = |pos: egui::Pos2, pressed: bool| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + frame(&mut app, key(egui::Key::F)); + assert_eq!(app.session.tool_id(), "rectangleFrame"); + // Draw a frame. + let a = app.canvas_rect.unwrap().center(); + let b = a + egui::vec2(120.0, 80.0); + frame(&mut app, vec![egui::Event::PointerMoved(a), button(a, true)]); + for i in 1..=4 { + frame(&mut app, vec![egui::Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))]); + } + frame(&mut app, vec![button(b, false)]); + frame(&mut app, vec![]); + assert!(app.session.active().is_some_and(|d| !d.selection.items.is_empty()), "drew a frame"); + frame(&mut app, key(egui::Key::V)); + assert_eq!(app.session.tool_id(), "selection", "V switches tools straight after drawing"); + frame(&mut app, key(egui::Key::F)); + assert_eq!(app.session.tool_id(), "rectangleFrame"); +} + +#[test] +fn escape_and_shift_w_leave_presentation_for_the_previous_mode() { + // Presentation hides every control, so the keyboard must get out of it (#493). + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "graphic"})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + let selected = |app: &crate::DesignApp| app.session.active().map(|d| d.selection.items.len()).unwrap_or(0); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + app.run("view.screenMode", json!({"mode": "preview"})).unwrap(); + app.select_tool("rectangleFrame"); + assert_eq!(selected(&app), 1, "the new frame is selected"); + + frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT)); + assert_eq!(app.ui.screen_mode, ScreenMode::Presentation, "Shift+W enters Presentation"); + assert_eq!(app.session.tool_id(), "rectangleFrame", "Shift+W is not a tool shortcut"); + frame(&mut app, key(egui::Key::Escape, egui::Modifiers::NONE)); + assert_eq!(app.ui.screen_mode, ScreenMode::Preview, "Esc returns to the mode Presentation was entered from"); + assert_eq!(app.session.tool_id(), "rectangleFrame", "Esc only left Presentation"); + assert_eq!(selected(&app), 1, "Esc only left Presentation"); + + frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT)); + frame(&mut app, key(egui::Key::W, egui::Modifiers::SHIFT)); + assert_eq!(app.ui.screen_mode, ScreenMode::Preview, "Shift+W leaves Presentation for the previous mode"); + + app.run("view.screenMode", json!({"mode": "presentation"})).unwrap(); + frame(&mut app, key(egui::Key::W, egui::Modifiers::NONE)); + assert_eq!(app.ui.screen_mode, ScreenMode::Normal, "W from any mode but Normal goes to Normal"); + + // Outside Presentation, Esc keeps its usual meaning. + frame(&mut app, key(egui::Key::Escape, egui::Modifiers::NONE)); + assert_eq!(app.ui.screen_mode, ScreenMode::Normal); + assert_eq!(app.session.tool_id(), "selection"); +} + +#[test] +fn cmd_plus_zooms_the_canvas_not_the_window() { + // A German keyboard has its own + key, so Cmd+= arrives as Plus; it must zoom the canvas like + // Cmd+- does, not hand the key to egui's whole-window zoom. + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let key = |k: egui::Key, modifiers: egui::Modifiers| { + vec![ + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers }, + ] + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let scale = ctx.zoom_factor(); + for (k, m, zooms_in) in [ + (egui::Key::Plus, egui::Modifiers::COMMAND, true), + (egui::Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, true), + (egui::Key::Equals, egui::Modifiers::COMMAND, true), + (egui::Key::Minus, egui::Modifiers::COMMAND, false), + ] { + let z0 = app.view().unwrap().zoom; + frame(&mut app, key(k, m)); + frame(&mut app, vec![]); + let z = app.view().unwrap().zoom; + assert!(if zooms_in { z > z0 } else { z < z0 }, "{k:?} {m:?}: {z0} -> {z}"); + assert_eq!(ctx.zoom_factor(), scale, "{k:?} {m:?} leaves the UI scale alone"); + } + // With a native menu (macOS) its accelerator takes Cmd+= itself, but never sees the Plus key + // standing in for = (#781). + app.native_shortcuts.insert("view.zoomIn".to_string(), shortcut_of(&app, "view.zoomIn").unwrap()); + for (k, m, zooms_in) in [ + (egui::Key::Plus, egui::Modifiers::COMMAND, true), + (egui::Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, true), + (egui::Key::Equals, egui::Modifiers::COMMAND, false), + ] { + let z0 = app.view().unwrap().zoom; + frame(&mut app, key(k, m)); + frame(&mut app, vec![]); + let z = app.view().unwrap().zoom; + assert_eq!(z > z0, zooms_in, "native menu, {k:?} {m:?}: {z0} -> {z}"); + } + // A shortcut the user set runs here until the native menu bar carries it as its key + // equivalent; then only the bar runs it, once. + run_ui(&mut app, "window.setShortcut", &json!({"id": "view.zoomOut", "shortcut": "Cmd+9"})).unwrap().unwrap(); + let zooms_out = |app: &mut crate::DesignApp, k: egui::Key| { + let z0 = app.view().unwrap().zoom; + frame(app, key(k, egui::Modifiers::COMMAND)); + frame(app, vec![]); + app.view().unwrap().zoom < z0 + }; + assert!(zooms_out(&mut app, egui::Key::Num9), "no native bar: the app runs it"); + app.native_shortcuts.insert("view.zoomOut".to_string(), "Cmd+9".to_string()); + assert!(!zooms_out(&mut app, egui::Key::Num9), "the bar's key equivalent runs only there"); + // A second binding of a command whose first the bar holds runs here. + let cmd = craft_keymap::CommandRef::new("view.zoomOut"); + let bindings = ["Cmd+F11", "Cmd+9"].map(|s| craft_keymap::Binding::parse(s).unwrap()).to_vec(); + app.keymap.set_bindings(&cmd, bindings, craft_keymap::Policy::Steal).unwrap(); + app.ui.shortcuts = app.keymap.overrides().clone(); + app.native_shortcuts.insert("view.zoomOut".to_string(), "Cmd+F11".to_string()); + assert!(!zooms_out(&mut app, egui::Key::F11), "the bar runs its own key"); + assert!(zooms_out(&mut app, egui::Key::Num9), "the second binding runs in the app"); +} + +#[test] +fn the_quick_apply_shortcut_opens_it_without_running_an_entry() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let cmd_return = + |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + frame(&mut app, vec![cmd_return(true), cmd_return(false)]); + frame(&mut app, vec![]); + assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open"); + assert_eq!(app.session.documents().len(), 1, "the first entry (New Document) didn't run"); + // Pressing the shortcut again, or holding it until it repeats, doesn't run it either. + frame(&mut app, vec![cmd_return(true), cmd_return(false)]); + let repeat = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::COMMAND }; + frame(&mut app, vec![repeat, cmd_return(false)]); + assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open"); + assert_eq!(app.session.documents().len(), 1, "a second ⌘Return or a repeat doesn't run the first entry"); + // A plain Return still does. + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![enter(true), enter(false)]); + assert_eq!(app.ui.palette, None, "Return runs the first entry and closes Quick Apply"); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn quick_apply_rows_are_left_aligned() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.ui.palette = Some(String::new()); + let ctx = egui::Context::default(); + let mut shapes = Vec::new(); + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + shapes = out.shapes; + } + let label_x = |label: &str| { + // The palette is painted last, over anything else with the same text. + shapes.iter().rev().find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos.x), + _ => None, + }) + }; + // Rows that show a shortcut or a style kind, and rows that show neither, among the first visible ones. + let items = quick_apply_items(&app.session, "", false); + let first = items.iter().take(10); + let plain = first.clone().find(|it| it.shortcut.is_none() && it.kind.is_empty()).expect("a row without a shortcut"); + let with_sc = first.clone().find(|it| it.shortcut.is_some()).expect("a row with a shortcut"); + let (a, b) = (label_x(&plain.label).expect("plain row drawn"), label_x(&with_sc.label).expect("shortcut row drawn")); + assert!((a - b).abs() < 0.5, "{:?} at x {a}, {:?} at x {b}", plain.label, with_sc.label); +} + +#[test] +fn copy_and_paste_keys_work_for_objects_without_a_native_menu() { + // Without a native menu the paste key arrives only as a paste event, which needs text on + // the system clipboard (#164, #185). + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + out.platform_output.commands + }; + let count = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads[0].items.len(); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone(); + app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); + let n = count(&app); + let copied = frame(&mut app, vec![egui::Event::Copy]) + .into_iter() + .find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t), + _ => None, + }) + .expect("copying objects puts text on the system clipboard"); + assert!(!copied.is_empty()); + frame(&mut app, vec![egui::Event::Paste(copied.clone())]); + assert_eq!(count(&app), n + 1, "the paste key pastes the copied rectangle"); + + // Pasting into text anchors the copied object; the clipboard placeholder isn't typed. + let r = app.session.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Hello"})).unwrap(); + let story = r["story"].as_u64().unwrap(); + app.session.execute("tool.select", &json!({"tool": "type"})).unwrap(); + app.session.execute("text.select", &json!({"story": story, "anchor": 5, "focus": 5})).unwrap(); + frame(&mut app, vec![egui::Event::Paste(copied.clone())]); + // Shift pastes without formatting. + frame(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), egui::Event::Paste(copied)]); + let text = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(story)).unwrap().text.clone(); + assert!(text.starts_with("Hello") && !text.contains('\u{FFFC}'), "{text:?}"); + assert!(text.contains(designcraft_doc::OBJECT_MARK), "{text:?}"); +} + +#[test] +fn paste_with_no_insertion_point_makes_a_text_frame_from_other_apps_text() { + // #518: text copied in another app pastes as a new, selected text frame; the text an + // object copy stands for still pastes the objects. One paste each way, with and without + // a native menu. + let selected_text = |app: &crate::DesignApp| { + let d = app.session.active().unwrap(); + let it = d.doc.item(*d.selection.items.first()?)?; + Some(d.doc.story(it.text_frame()?.story)?.text.clone()) + }; + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], None); + // The paste keys without a native menu: a paste event. + native_frame(&mut app, &ctx, vec![egui::Event::Paste("From elsewhere".into())], None); + assert_eq!(document_items(&app), (1, 1), "pasted once"); + assert_eq!(selected_text(&app).as_deref(), Some("From elsewhere")); + let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone(); + app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); + let copied = native_frame(&mut app, &ctx, vec![egui::Event::Copy], None) + .platform_output + .commands + .into_iter() + .find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t), + _ => None, + }) + .expect("copying objects puts text on the system clipboard"); + native_frame(&mut app, &ctx, vec![egui::Event::Paste(copied)], None); + assert_eq!(document_items(&app), (3, 1)); + assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame"); + + // A native menu: Paste reads the system clipboard. + let clip = std::rc::Rc::new(std::cell::RefCell::new(Some("Menu text".to_string()))); + let read = clip.clone(); + let services = crate::Services { clipboard_text: Some(Box::new(move || read.borrow().clone())), ..Default::default() }; + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.session.execute("file.new", &json!({})).unwrap(); + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], Some("edit.paste")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(document_items(&app), (1, 1), "pasted once"); + assert_eq!(selected_text(&app).as_deref(), Some("Menu text")); + // Objects copied since that text was copied paste as objects. + let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone(); + app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); + native_frame(&mut app, &ctx, vec![], Some("edit.copy")); + native_frame(&mut app, &ctx, vec![], Some("edit.paste")); + assert_eq!(document_items(&app), (3, 1)); + assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame"); + // Newer text from another app wins. + *clip.borrow_mut() = Some("Newer".into()); + native_frame(&mut app, &ctx, vec![], Some("edit.paste")); + assert_eq!(document_items(&app), (4, 1)); + assert_eq!(selected_text(&app).as_deref(), Some("Newer")); +} + +#[test] +fn sample_scripts_run() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + for (name, text) in app.ui.scripts.clone() { + let r = app.session.execute("script.run", &json!({"text": text})); + assert!(r.is_ok(), "{name}: {r:?}"); + } +} + +#[test] +fn new_window_shows_a_second_view() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp| { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + frame(&mut app); + assert_eq!(run_ui(&mut app, "window.newWindow", &json!({})).unwrap().unwrap(), json!(true)); + assert!(!app.split); + frame(&mut app); + frame(&mut app); + // Pane 1 was drawn (its rect is held for it) and has its own view. + assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some() || app.pane == 1); + app.switch_pane(1); + assert!(app.view().is_some(), "the second window has a view"); + app.switch_pane(0); + assert_eq!(checked(&app, "window.newWindow", &Value::Null), Some(true)); + run_ui(&mut app, "window.newWindow", &json!({"on": false})).unwrap().unwrap(); + frame(&mut app); +} + +#[test] +fn panels_float_and_dock() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "swatches", "x": 50, "y": 60})).unwrap().unwrap(); + assert_eq!(r["floating"], json!(["swatches"])); + let window = &app.ui.docking.as_ref().unwrap().floating[0]; + assert_eq!([window.rect[0], window.rect[1]], [50.0, 60.0]); + // Showing a floating panel leaves it where it is. + run_ui(&mut app, "window.panel", &json!({"panel": "swatches"})).unwrap().unwrap(); + assert_eq!(app.ui.open_panel, None); + let r = run_ui(&mut app, "window.dockPanel", &json!({"panel": "swatches"})).unwrap().unwrap(); + assert_eq!(r["floating"], json!([])); + assert!(app.ui.docking.as_ref().unwrap().floating.is_empty()); + assert!(run_ui(&mut app, "window.floatPanel", &json!({"panel": "nope"})).unwrap().is_err()); + // Float-only panels (Type › Tabs) have their own windows outside the layout. + let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "tabs", "x": 10, "y": 20})).unwrap().unwrap(); + assert_eq!(r["floating"], json!(["tabs"])); + assert_eq!(app.ui.floating, [("tabs".to_string(), [10.0, 20.0])]); + run_ui(&mut app, "window.dockPanel", &json!({"panel": "tabs"})).unwrap().unwrap(); + assert!(app.ui.floating.is_empty()); +} + +/// One frame as the desktop app runs it: queued synthetic input, then the native menu item +/// chosen during the frame (`menu`), then the app's logic and ui. +fn native_frame(app: &mut crate::DesignApp, ctx: &egui::Context, events: Vec, menu: Option<&str>) -> egui::FullOutput { + let mut input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), events, ..Default::default() }; + app.raw_input_hook(ctx, &mut input); + let mut menu = menu; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx().clone(); + if let Some(id) = menu.take() { + activate_native(app, &ctx, id, &Value::Null); + } + app.logic(&ctx); + app.ui(ui); + }); + out.textures_delta.clear(); + out +} + +/// A document with two frames, nothing selected, and Quick Apply's search field focused +/// holding `text`. +fn app_with_focused_field(ctx: &egui::Context, text: &str) -> crate::DesignApp { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [236, 36, 400, 200]})).unwrap(); + app.session.execute("edit.deselectAll", &json!({})).unwrap(); + app.ui.palette = Some(text.into()); + for _ in 0..3 { + native_frame(&mut app, ctx, vec![], None); + } + assert!(ctx.text_edit_focused()); + app +} + +fn field_selection(ctx: &egui::Context) -> Option<(usize, usize)> { + let id = ctx.memory(|m| m.focused())?; + let r = egui::TextEdit::load_state(ctx, id)?.cursor.char_range()?; + Some((r.primary.index.min(r.secondary.index).into(), r.primary.index.max(r.secondary.index).into())) +} + +fn document_items(app: &crate::DesignApp) -> (usize, usize) { + let d = app.session.active().unwrap(); + (d.doc.spreads.iter().flat_map(|sp| &sp.items).count(), d.selection.items.len()) +} + +#[test] +fn native_select_all_selects_the_focused_fields_text() { + // The Mac menu bar takes ⌘A before the window sees it (#30). + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(field_selection(&ctx), Some((0, 5)), "the field's whole text is selected"); + assert_eq!(document_items(&app), (2, 0), "the document selection is unchanged"); +} + +#[test] +fn native_paste_and_copy_act_on_the_focused_field() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); + native_frame(&mut app, &ctx, vec![], None); + // Copy puts the field's selected text on the clipboard. + native_frame(&mut app, &ctx, vec![], Some("edit.copy")); + let out = native_frame(&mut app, &ctx, vec![], None); + assert!(out.platform_output.commands.contains(&egui::OutputCommand::CopyText("frame".into())), "{:?}", out.platform_output.commands); + // Paste asks the integration for the clipboard, which it hands to the field as a paste. + let out = native_frame(&mut app, &ctx, vec![], Some("edit.paste")); + let commands = &out.viewport_output[&egui::ViewportId::ROOT].commands; + assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}"); + native_frame(&mut app, &ctx, vec![egui::Event::Paste("text".into())], None); + assert_eq!(app.ui.palette.as_deref(), Some("text")); + assert_eq!(document_items(&app), (2, 0), "nothing was pasted into the document"); +} + +#[test] +fn native_copy_and_paste_use_the_system_clipboard_for_canvas_text() { + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200], "content": "text", "text": "hello"})).unwrap(); + let story = *app.session.active().unwrap().doc.stories.keys().next().unwrap(); + app.select_tool("type"); + app.run("text.select", json!({"story": story.0, "anchor": 0, "focus": 5})).unwrap(); + for _ in 0..3 { + native_frame(&mut app, &ctx, vec![], None); + } + assert!(app.session.wants_text()); + + native_frame(&mut app, &ctx, vec![], Some("edit.copy")); + let copied = native_frame(&mut app, &ctx, vec![], None); + assert!(copied.platform_output.commands.contains(&egui::OutputCommand::CopyText("hello".into()))); + + let paste = native_frame(&mut app, &ctx, vec![], Some("edit.paste")); + let commands = &paste.viewport_output[&egui::ViewportId::ROOT].commands; + assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}"); + native_frame(&mut app, &ctx, vec![egui::Event::Paste("world".into())], None); + assert_eq!(app.session.active().unwrap().doc.story(story).unwrap().text, "world"); +} + +#[test] +fn native_undo_and_redo_act_on_the_focused_field() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, ""); + native_frame(&mut app, &ctx, vec![egui::Event::Text("abc".into())], None); + assert_eq!(app.ui.palette.as_deref(), Some("abc")); + native_frame(&mut app, &ctx, vec![], Some("edit.undo")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(app.ui.palette.as_deref(), Some(""), "the field's typing is undone"); + assert_eq!(document_items(&app), (2, 0), "the document's last frame is still there"); + native_frame(&mut app, &ctx, vec![], Some("edit.redo")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(app.ui.palette.as_deref(), Some("abc")); + assert_eq!(document_items(&app), (2, 0)); +} + +#[test] +fn native_editing_items_are_enabled_for_a_focused_field() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + // Nothing is selected in the document, so its Copy and Cut are off; the field's are on. + assert!(!menu_enabled(&app, "edit.copy") && !menu_enabled(&app, "edit.cut")); + for id in ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"] { + assert!(native_menu_enabled(&app, &ctx, id), "{id}"); + } + assert!(!native_menu_enabled(&app, &ctx, "edit.duplicate"), "other items follow the document"); + app.ui.palette = None; + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], None); + assert!(!native_menu_enabled(&app, &ctx, "edit.copy"), "without a focused field, as the document says"); +} + +#[test] +fn native_select_all_without_a_focused_field_selects_the_documents_items() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + app.ui.palette = None; + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], None); + assert!(!ctx.text_edit_focused()); + native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); + assert_eq!(document_items(&app), (2, 2)); +} + +#[test] +fn command_search_matches_labels_in_the_interface_language() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.language = "de".into(); + let label = crate::i18n::tr("de", "Group"); + let items = command_search(&app, &label.to_lowercase()); + let group = items.iter().find(|i| i.id == "object.group").unwrap(); + assert_eq!(group.label, label); + assert_eq!(group.shortcut.as_deref(), Some("Cmd+G")); + assert!(command_search(&app, "group").iter().any(|i| i.id == "object.group"), "English labels match too"); + assert!(command_search(&app, " ").is_empty()); + assert!(command_search(&app, "e").len() <= 14); +} + +#[test] +fn quick_apply_lists_styles_then_commands() { + let mut s = designcraft_engine::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Body Copy"})).unwrap(); + let items = quick_apply_items(&s, "body", false); + assert_eq!(items[0].id, "style.paragraph.apply"); + assert_eq!(items[0].params, json!({"name": "Body Copy"})); + assert_eq!(items[0].kind, "Paragraph Style"); + assert!(quick_apply_items(&s, "", false).iter().all(|i| i.kind.is_empty())); + assert!(quick_apply_items(&s, "preferences", false).iter().any(|i| i.id == "app.preferences")); +} + +#[test] +fn searched_ui_commands_run_without_parameters_and_keep_preferences() { + // Without a value these reset a setting or need a place the test host always has. + let searched: Vec<&str> = quick_commands().map(|c| c.0).collect(); + for id in ["app.flattener", "view.screenMode", "view.zoom", "window.taskBarPin"] { + assert!(!searched.contains(&id), "{id} is searched"); + } + // A placed PDF: a graphic with layers. + let mut scratch = designcraft_engine::Session::new(); + scratch.execute("file.new", &json!({})).unwrap(); + let pdf = scratch.execute("file.exportPdf", &json!({})).unwrap()["base64"].clone(); + let contexts = ["nothing selected", "text insertion point", "text frame selected", "table cell", "placed PDF selected"]; + // A two-page document, a saved workspace and non-default preferences, a host with window + // controls, and file dialogs that are dismissed. + let setup = |context: usize| { + let services = crate::Services { + pick_open: Some(Box::new(|_| None)), + pick_save: Some(Box::new(|_| None)), + clipboard_text: Some(Box::new(|| None)), + ..Default::default() + }; + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.custom_titlebar = true; + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))); + app.run("file.new", json!({"pages": 2})).unwrap(); + app.session.prefs.recent_files.push("/nowhere/recent.dcraft".into()); + app.ui.shortcuts.insert("view.rulers", vec!["Ctrl+Alt+R".into()]); + app.ui.hidden_menu_items.push("view.guides".into()); + app.ui.ui_scale = 1.25; + app.ui.brightness = crate::theme::Brightness::Light; + app.ui.task_bar_at = Some([200.0, 200.0]); + run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); + match context { + 1 => { + app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": "One", "caret": true})).unwrap(); + } + 2 => { + let f = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": "One"})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [f]})).unwrap(); + } + 3 => { + app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap(); + app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); + } + 4 => { + let f = app.run("frame.create", json!({"rect": [72, 72, 400, 400]})).unwrap()["id"].clone(); + app.run("file.place", json!({"base64": pdf, "name": "a.pdf", "frame": f})).unwrap(); + app.run("selection.set", json!({"ids": [f]})).unwrap(); + } + _ => {} + } + app.ui.dialog = None; + app + }; + let prefs = |app: &DesignApp| { + let u = &app.ui; + json!({ + "shortcuts": u.shortcuts, "hiddenMenuItems": u.hidden_menu_items, "uiScale": u.ui_scale, + "brightness": u.brightness, "workspace": u.workspace, "customWorkspaces": u.custom_workspaces, + "docking": u.docking, "dockingHidden": u.docking_hidden, "floating": u.floating, + }) + }; + let quick = quick_apply_items(&setup(0).session, "workspace", false); + assert!(quick.iter().any(|i| i.id == "window.newWorkspace")); + // Deleting needs a workspace name: the application bar's workspace menu lists them. + assert!(!quick.iter().any(|i| i.id == "window.deleteWorkspace")); + // Each command runs as Quick Apply runs an entry. One that needs a selection may fail + // without it, but runs in one of the contexts; none changes a preference it wasn't asked to. + // Opening a panel or collapsing the dock to icons changes where the panels are, as it should. + let opens_a_panel = [ + "app.tabsPanel", + "app.characterStylesPanel", + "app.paragraphStylesPanel", + "app.characterPanel", + "app.paragraphPanel", + "app.glyphsPanel", + "app.tablePanel", + "window.collapseToIcons", + ]; + let arrangement = ["docking", "dockingHidden", "floating"]; + let mut failed = Vec::new(); + for (id, ..) in quick_commands().filter(|(id, ..)| UI_COMMANDS.iter().any(|c| c.0 == *id)) { + let mut errors = Vec::new(); + for (i, context) in contexts.iter().enumerate() { + let mut app = setup(i); + let before = prefs(&app); + match app.run(id, json!({})) { + Err(e) => errors.push(format!("{context}: {e}")), + Ok(_) => { + let after = prefs(&app); + let changed: Vec<&String> = + before.as_object().unwrap().iter().filter(|(k, v)| after.get(k.as_str()) != Some(*v)).map(|(k, _)| k).collect(); + let changed: Vec<&String> = + changed.into_iter().filter(|k| !(opens_a_panel.contains(&id) && arrangement.contains(&k.as_str()))).collect(); + if !changed.is_empty() { + failed.push(format!("{id} ({context}): changed {changed:?}")); + } + } + } + } + if errors.len() == contexts.len() { + failed.push(format!("{id}: {errors:?}")); + } + } + assert!(failed.is_empty(), "{failed:#?}"); +} + +#[test] +fn distribute_rows_menu_dispatches_an_undoable_edit() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap(); + app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); + app.run("table.setRowHeight", json!({"row": 0, "height": 40, "mode": "exactly"})).unwrap(); + app.run("table.setRowHeight", json!({"row": 1, "height": 80, "mode": "exactly"})).unwrap(); + app.run("table.selectTable", json!({})).unwrap(); + activate(&mut app, "table.distributeRows", &Value::Null); + assert!(app.ui.dialog.is_none()); + let info = app.run("table.get", json!({})).unwrap(); + assert_eq!(info["rows"][0]["height"], 60.0); + assert_eq!(info["rows"][1]["height"], 60.0); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.run("table.get", json!({})).unwrap()["rows"][0]["height"], 40.0); +} + +#[test] +fn every_menu_entry_is_a_command() { + let mut all = Vec::new(); + for (_, items) in menu_tree() { + walk(&items, &mut all); + } + assert!(all.len() > 80, "{}", all.len()); + assert!(all.iter().any(|(label, id, _)| label == "Distribute Rows Evenly" && id == "table.distributeRows")); + for (label, id, params) in &all { + assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "menu entry {label}: unknown command {id}"); + assert!(!label.is_empty() && label != id, "menu entry {id} has no label"); + if let Some(o) = params.as_object() { + assert!(!o.is_empty(), "{id}: empty fixed params"); + } + } + // Nested submenus parse (Type › Insert Special Character › Symbols › …). + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let special = ty.iter().find_map(|i| match i { + Item::Sub(n, c) if n == "Insert Special Character" => Some(c.clone()), + _ => None, + }); + assert!(special.is_some_and(|c| c.iter().any(|i| matches!(i, Item::Sub(n, _) if n == "Symbols")))); + // Fixed-parameter variants keep their own labels. + assert!(all.iter().any(|(l, id, _)| l == "Fill Frame Proportionally" && id == "fit.fillFrameProportionally")); +} + +#[test] +fn context_menus_hold_commands_and_menu_bar_submenus() { + let tree = menu_tree(); + for entries in [CONTEXT_OBJECT, CONTEXT_GRAPHIC_FRAME, CONTEXT_OBJECT_TAIL, CONTEXT_TEXT_FRAME, CONTEXT_TEXT, CONTEXT_CANVAS] { + for path in entries.iter().filter_map(|e| e.strip_prefix("menu:")) { + assert!(menu_bar_submenu(&tree, path).is_some(), "no menu bar submenu {path}"); + } + let mut all = Vec::new(); + for (_, items) in context_parse(entries) { + walk(&items, &mut all); + } + for (label, id, _) in &all { + assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "context entry {label}: unknown command {id}"); + } + } +} + +#[test] +fn the_type_menu_follows_indesigns_order() { + // InDesign's Type menu, as Chris Nielsen opens it in "Numbering Page Sections" (2:09). + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let labels: Vec = ty + .iter() + .map(|i| match i { + Item::Sep => "-".to_string(), + Item::Sub(n, _) => format!("{n} >"), + Item::Cmd { label, .. } => label.clone(), + }) + .collect(); + let expected = [ + "Size >", + "-", + "Character", + "Paragraph", + "Tabs", + "Glyphs", + "-", + "Character Styles", + "Paragraph Styles", + "-", + "Create Outlines", + "Find/Replace Font…", + "Reload Fonts", + "Change Case >", + "-", + "Type on a Path >", + "-", + "Notes >", + "Track Changes >", + "-", + "Insert Footnote", + "Document Footnote Options…", + "Insert Endnote", + ]; + assert_eq!(&labels[..expected.len()], expected, "{labels:?}"); + let pos = |l: &str| labels.iter().position(|x| x == l).unwrap_or_else(|| panic!("{l} in {labels:?}")); + assert!(pos("Hyperlinks & Cross-References >") < pos("Text Variables >")); + assert!(pos("Text Variables >") < pos("Bulleted & Numbered Lists >")); + assert!(pos("Bulleted & Numbered Lists >") < pos("Insert Special Character >")); + assert!(pos("Insert Special Character >") < pos("Insert White Space >")); + assert!(pos("Insert Break Character >") < pos("Fill with Placeholder Text")); + assert!(pos("Fill with Placeholder Text") < pos("Show Hidden Characters")); + // Alignment, styles and point sizes keep their shortcuts, out of the menu as in InDesign. + for gone in ["Align Left", "Bold", "Increase Point Size", "Paragraph Rules…"] { + assert!(!labels.iter().any(|l| l == gone), "{gone}"); + } + let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let all = effective_shortcuts(&app); + for (id, sc) in [ + ("type.alignLeft", "Cmd+Shift+L"), + ("app.characterPanel", "Cmd+T"), + ("app.paragraphPanel", "Cmd+Alt+T"), + ("app.insertCurrentPageNumber", "Cmd+Alt+Shift+N"), + ] { + assert_eq!(all.iter().find(|(i, _)| i == id).map(|(_, s)| s.as_str()), Some(sc), "{id}"); + } + // Markers › Current Page Number carries ⌥⇧⌘N. + let markers = ty + .iter() + .find_map(|i| match i { + Item::Sub(n, c) if n == "Insert Special Character" => { + c.iter().find_map(|i| if let Item::Sub(n, c) = i { (n == "Markers").then(|| c.clone()) } else { None }) + } + _ => None, + }) + .unwrap(); + assert!(matches!(&markers[0], Item::Cmd { label, shortcut: Some("Cmd+Alt+Shift+N"), .. } if label == "Current Page Number")); +} + +#[test] +fn type_panel_items_open_their_panels_and_the_marker_shortcut_inserts_a_page_number() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + activate(&mut app, "app.characterPanel", &Value::Null); + assert!(crate::panel_docking::showing(&app, "character")); + // Paragraph Styles opens floating, grouped with Character Styles, as in InDesign. + activate(&mut app, "app.paragraphStylesPanel", &Value::Null); + let layout = app.ui.docking.as_ref().unwrap(); + assert!( + layout + .floating + .iter() + .flat_map(crate::panel_docking::window_groups) + .any(|g| g.panels == ["characterStyles", "paragraphStyles"] && g.active == 1) + ); + let story = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "Page "})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 5, "focus": 5})).unwrap(); + activate(&mut app, "app.insertCurrentPageNumber", &Value::Null); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text, "Page \u{e000}"); +} + +#[test] +fn custom_workspaces_save_apply_and_delete() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.dock_tab = "swatches".into(); + app.ui.control_bar = true; + run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); + run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); + app.ui.dock_tab = "properties".into(); + run_ui(&mut app, "window.workspace", &json!({"name": "Mine"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.control_bar, app.ui.workspace.as_str()), ("swatches", true, "Mine")); + app.ui.dock_tab = "layers".into(); + run_ui(&mut app, "window.resetWorkspace", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.dock_tab, "swatches", "reset to the saved arrangement"); + run_ui(&mut app, "window.deleteWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); + assert!(app.ui.custom_workspaces.is_empty()); + assert_eq!(app.ui.workspace, "Essentials"); +} + +/// New Workspace › Capture (Learn Skills Daily's InDesign course, 11:40): Panel Locations and +/// Menu Customization, both on by default. +#[test] +fn new_workspace_captures_panel_locations_and_menu_customization() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + // The dialog offers both, checked. + run_ui(&mut app, "window.newWorkspace", &json!({})).unwrap().unwrap(); + let d = app.ui.dialog.take().unwrap(); + assert_eq!( + (d.id.as_str(), d.fields["panelLocations"].clone(), d.fields["menuCustomization"].clone()), + ("newWorkspace", json!(true), json!(true)) + ); + // Both captured. + app.ui.dock_tab = "swatches".into(); + app.ui.hidden_menu_items = vec!["Type/Glyphs".into()]; + run_ui(&mut app, "window.newWorkspace", &json!({"name": "All"})).unwrap().unwrap(); + // Menus only: choosing it leaves the panels where they are. + app.ui.hidden_menu_items = vec!["Layout/Pages".into()]; + run_ui(&mut app, "window.newWorkspace", &json!({"name": "Menus", "panelLocations": false})).unwrap().unwrap(); + // Panels only: the menus stay as they are. + app.ui.dock_tab = "layers".into(); + run_ui(&mut app, "window.newWorkspace", &json!({"name": "Panels", "menuCustomization": false})).unwrap().unwrap(); + app.ui.dock_tab = "properties".into(); + app.ui.hidden_menu_items.clear(); + run_ui(&mut app, "window.workspace", &json!({"name": "Menus"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("properties", vec!["Layout/Pages".to_string()])); + run_ui(&mut app, "window.workspace", &json!({"name": "Panels"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("layers", vec!["Layout/Pages".to_string()])); + run_ui(&mut app, "window.workspace", &json!({"name": "All"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.hidden_menu_items.clone()), ("swatches", vec!["Type/Glyphs".to_string()])); + // A workspace saved before the options existed restores its panels. + let old: crate::SavedWorkspace = serde_json::from_value(json!({"name": "Old", "dockTab": "pages"})).unwrap(); + assert!(!old.keep_panels && old.hidden_menu_items.is_none()); +} + +#[test] +fn essentials_classic_is_the_control_panel_and_iconic_groups() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + run_ui(&mut app, "window.workspace", &json!({"name": "Essentials Classic"})).unwrap().unwrap(); + assert!(app.ui.control_bar && !app.ui.dock_expanded); + let groups = app.ui.icon_groups.clone().unwrap(); + assert_eq!(groups[0], ["pages", "layers", "links"]); + assert_eq!(groups.last().unwrap(), &["gradient"]); + assert_eq!(checked(&app, "window.workspace", &json!({"name": "Essentials Classic"})), Some(true)); + assert_eq!(checked(&app, "window.workspace", &json!({"name": "Essentials"})), Some(false)); + // Window › Pages opens Pages from its icon group, not the Properties stack. + run_ui(&mut app, "window.panel", &json!({"panel": "pages"})).unwrap().unwrap(); + assert!(crate::panel_docking::showing(&app, "pages")); + let layout = app.ui.docking.clone().unwrap(); + assert!(!layout.contains(&"properties".to_string())); + assert_eq!(crate::panel_docking::tab_group(&layout, "pages"), ["pages", "layers", "links"]); + // A workspace saved from it keeps the groups. + run_ui(&mut app, "window.newWorkspace", &json!({"name": "Mine"})).unwrap().unwrap(); + run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); + assert_eq!((app.ui.icon_groups.as_ref(), app.ui.dock_expanded, app.ui.control_bar), (None, true, false)); + run_ui(&mut app, "window.workspace", &json!({"name": "Mine"})).unwrap().unwrap(); + assert_eq!(app.ui.icon_groups, Some(groups)); +} + +#[test] +fn typography_workspace_opens_its_panels_from_named_icon_groups_and_resets() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + run_ui(&mut app, "window.workspace", &json!({"name":"Typography"})).unwrap().unwrap(); + assert!(app.ui.control_bar); + assert!(!app.ui.dock_expanded); + assert!(app.ui.open_panel.is_none()); + let groups = app.ui.icon_groups.clone().unwrap(); + assert_eq!(groups[0], ["pages", "layers", "swatches"]); + assert_eq!(groups[4], ["paragraph", "paragraphStyles"]); + assert_eq!(groups[5], ["character", "characterStyles"]); + for panel in ["pages", "paragraphStyles", "characterStyles"] { + run_ui(&mut app, "window.panel", &json!({"panel":panel})).unwrap().unwrap(); + assert!(crate::panel_docking::showing(&app, panel), "{panel}"); + assert!(app.ui.docking.as_ref().unwrap().floating.is_empty(), "{panel} opens from its icon group"); + } + run_ui(&mut app, "window.resetWorkspace", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.icon_groups, Some(groups)); + assert!(app.ui.open_panel.is_none()); + assert!(!app.ui.dock_expanded); + run_ui(&mut app, "window.workspace", &json!({"name":"Essentials"})).unwrap().unwrap(); + assert!(app.ui.icon_groups.is_none()); + assert!(app.ui.dock_expanded); +} + +#[test] +fn the_window_menu_is_in_indesigns_order_and_reaches_every_panel() { + let window = menu_tree().into_iter().find(|(m, _)| *m == "Window").unwrap().1; + let names: Vec<&str> = window + .iter() + .filter_map(|i| match i { + Item::Sub(n, _) => Some(n.as_str()), + Item::Cmd { label, .. } => Some(label.as_str()), + Item::Sep => None, + }) + .collect(); + assert_eq!(&names[..4], ["Arrange", "Workspace", "Articles", "Color"]); + let sub = |name: &str| { + window + .iter() + .find_map(|i| match i { + Item::Sub(n, c) if n == name => Some(c.clone()), + _ => None, + }) + .unwrap() + }; + // Window › Workspace › Essentials Classic, Window › Color › Gradient & Swatches. + assert!( + sub("Workspace") + .iter() + .any(|i| matches!(i, Item::Cmd { id, params, .. } if id == "window.workspace" && params["name"] == "Essentials Classic")) + ); + let color: Vec = sub("Color").iter().filter_map(|i| if let Item::Cmd { label, .. } = i { Some(label.clone()) } else { None }).collect(); + assert_eq!(color, ["Color", "Gradient", "Swatches"]); + // Every panel is in the menu. + fn panels(items: &[Item], out: &mut Vec) { + for i in items { + match i { + Item::Sub(_, c) => panels(c, out), + Item::Cmd { id, params, .. } if id == "window.panel" => out.extend(params["panel"].as_str().map(str::to_string)), + _ => {} + } + } + } + let mut found = Vec::new(); + panels(&window, &mut found); + for (id, _, _) in crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS) { + assert!(found.iter().any(|p| p == id), "Window menu misses the {id} panel"); + } +} + +#[test] +fn interactive_workspaces_show_their_panels() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.dock_expanded = false; + run_ui(&mut app, "window.workspace", &json!({"name": "Interactive for PDF"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.dock_expanded, app.ui.open_panel.as_deref()), ("pages", true, Some("buttons"))); + run_ui(&mut app, "window.workspace", &json!({"name": "Digital Publishing"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.open_panel.as_deref()), ("pages", Some("liquid"))); + run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); + assert_eq!(app.ui.open_panel, None); +} + +#[test] +fn hide_and_show_menu_items() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let items = all_menu_items(); + let (menu, label) = items.iter().find(|(m, _)| m == "Edit").cloned().expect("Edit items"); + let key = menu_key(&menu, &label); + run_ui(&mut app, "window.hideMenuItem", &json!({"item": key})).unwrap().unwrap(); + assert!(app.ui.hidden_menu_items.contains(&key)); + run_ui(&mut app, "window.hideMenuItem", &json!({"item": key, "hidden": false})).unwrap().unwrap(); + assert!(app.ui.hidden_menu_items.is_empty()); + assert!(items.len() > 100, "every menu's items are listed: {}", items.len()); +} + +/// The Type menu as drawn: every item label. +fn drawn_type_menu(app: &mut DesignApp) -> Vec { + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 4000.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + menu_items(app, ui, &ty, "Type"); + }); + out.textures_delta.clear(); + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.job.text.trim().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut labels = Vec::new(); + out.shapes.iter().for_each(|s| collect(&s.shape, &mut labels)); + labels +} + +/// Tate-Chu-Yoko, Ruby, Kenten and Warichu are in the Type menu of InDesign's Japanese edition +/// only: they show while Show CJK Features is on, which follows the interface language until +/// the user sets it. Hidden, they still run. +#[test] +fn cjk_menu_items_follow_show_cjk_features() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let cjk: Vec = ty + .iter() + .filter_map(|i| match i { + Item::Cmd { label, id, .. } if CJK_ONLY.contains(&id.as_str()) => Some(label.clone()), + _ => None, + }) + .collect(); + assert_eq!(cjk.len(), 4, "{cjk:?}"); + let drawn = |app: &mut DesignApp| { + let labels = drawn_type_menu(app); + assert!(labels.iter().any(|l| l == crate::i18n::tr(&app.ui.language, "Story Direction")), "in both editions: {labels:?}"); + let shown: Vec = cjk.iter().map(|l| labels.iter().any(|d| d == crate::i18n::tr(&app.ui.language, l))).collect(); + assert!(shown.iter().all(|s| *s == shown[0]), "{shown:?}"); + shown[0] + }; + for (lang, on) in [("", false), ("de", false), ("ja", true), ("zh", true), ("ko", true)] { + app.ui.language = lang.into(); + assert_eq!(crate::cjk_features(&app), on, "{lang}"); + assert_eq!(drawn(&mut app), on, "{lang}"); + } + app.run("prefs.set", json!({"cjkFeatures": false})).unwrap(); + assert!(!drawn(&mut app), "off in a Korean interface"); + app.ui.language = String::new(); + app.run("prefs.set", json!({"cjkFeatures": true})).unwrap(); + assert!(drawn(&mut app), "on in an English interface"); + assert!(quick_apply_items(&app.session, "ruby", crate::cjk_features(&app)).iter().any(|i| i.id == "app.rubyDialog")); + app.run("prefs.set", json!({"cjkFeatures": false})).unwrap(); + assert!(!drawn(&mut app)); + assert!(!quick_apply_items(&app.session, "ruby", crate::cjk_features(&app)).iter().any(|i| i.id == "app.rubyDialog")); + app.run("app.rubyDialog", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("ruby"), "hidden, not removed"); +} + +/// Preferences › Type › Show CJK Features: left as it is, it keeps following the interface +/// language; changed, it is kept in prefs.json. +#[test] +fn show_cjk_features_is_a_persisted_preference() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.language = "ja".into(); + run_ui(&mut app, "app.preferences", &json!({})).unwrap().unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cjkFeatures"], true); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.prefs.cjk_features, None, "untouched: follows the language"); + run_ui(&mut app, "app.preferences", &json!({})).unwrap().unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("cjkFeatures".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.prefs.cjk_features, Some(false)); + assert!(!crate::cjk_features(&app)); + // prefs.json round trip; a file from before the setting follows the language. + let saved = serde_json::to_vec(&app.session.prefs).unwrap(); + assert_eq!(serde_json::from_slice::(&saved).unwrap().cjk_features, Some(false)); + assert_eq!(serde_json::from_str::(r#"{"scaleStrokes": false}"#).unwrap().cjk_features, None); + assert_eq!(app.run("prefs.set", json!({"cjkFeatures": null})).unwrap()["cjkFeatures"], Value::Null); + assert!(crate::cjk_features(&app), "follows the Japanese interface again"); +} + +#[test] +fn menu_button_fits_its_anchor_and_resets_scroll_on_reopen() { + // Workspace/panel menus may be in the middle; the status-bar zoom menu opens upwards. + for anchor_y in [0.0, 130.0, 260.0] { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let mut tick = 0; + let mut frame = |events: Vec| { + tick += 1; + let mut button = None; + let mut first = None; + let mut last = None; + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { + ui.add_space(anchor_y); + let response = menu_button(ui, "Long menu", |ui| { + for i in 0..60 { + let response = ui.button(format!("Item {i}")); + if i == 0 { + first = Some((response.rect, ui.clip_rect())); + } + if i == 59 { + last = Some((response.rect, ui.clip_rect())); + } + } + }); + button = Some(response.response); + }); + output.textures_delta.clear(); + (button.expect("menu button"), first, last) + }; + let click = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(vec![]); + let (button, _, _) = frame(vec![]); + let anchor = button.rect; + for pressed in [true, false] { + frame(vec![egui::Event::PointerMoved(anchor.center()), click(anchor.center(), pressed)]); + } + for _ in 0..3 { + frame(vec![]); + } + let popup = ctx.memory(|memory| memory.area_rect(egui::Popup::default_response_id(&button))).expect("open menu"); + assert!(screen.contains_rect(popup), "menu at {anchor_y} fits in the viewport: {popup:?}"); + assert!( + popup.top() >= anchor.bottom() - 1.0 || popup.bottom() <= anchor.top() + 1.0, + "menu at {anchor_y} stays on one side of its button: {popup:?}, {anchor:?}" + ); + let (_, first, last) = frame(vec![]); + let (first, clip) = first.expect("first row"); + assert!(clip.contains_rect(first), "newly opened menu starts at the first row"); + assert!(!clip.intersects(last.expect("last row").0), "last row starts below the scroll area"); + + frame(vec![ + egui::Event::PointerMoved(popup.center()), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -5000.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }, + ]); + for _ in 0..60 { + frame(vec![]); + } + let (_, first, last) = frame(vec![]); + let (last, clip) = last.expect("scrolled last row"); + assert!(popup.contains_rect(last) && clip.contains_rect(last), "last row is reachable: {last:?}, {popup:?}, {clip:?}"); + assert!(!clip.intersects(first.expect("scrolled first row").0), "menu really scrolled away from its start"); + + let outside = egui::pos2(screen.right() - 10.0, screen.center().y); + for pressed in [true, false] { + frame(vec![egui::Event::PointerMoved(outside), click(outside, pressed)]); + } + assert!(!egui::Popup::is_any_open(&ctx), "outside click closes the menu"); + assert!(frame(vec![]).1.is_none(), "closed menu is no longer drawn"); + for pressed in [true, false] { + frame(vec![egui::Event::PointerMoved(anchor.center()), click(anchor.center(), pressed)]); + } + for _ in 0..3 { + frame(vec![]); + } + let (_, first, last) = frame(vec![]); + let (first, clip) = first.expect("reopened first row"); + assert!(popup.contains_rect(first) && clip.contains_rect(first), "reopening resets to the first row: {first:?}, {clip:?}"); + assert!(!clip.intersects(last.expect("reopened last row").0), "reopening discards the old scroll offset"); + } +} + +#[test] +fn tiny_menu_viewport_does_not_force_the_default_scroll_height() { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 100.0)); + let mut tick = 0; + let mut frame = |events: Vec| { + tick += 1; + let mut button = None; + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { + ui.add_space(35.0); + let response = menu_button(ui, "Long menu", |ui| { + for i in 0..20 { + let _ = ui.button(format!("Item {i}")); + } + }); + button = Some(response.response); + }); + output.textures_delta.clear(); + button.expect("menu button") + }; + frame(vec![]); + let button = frame(vec![]); + let pos = button.rect.center(); + for pressed in [true, false] { + frame(vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ]); + } + for _ in 0..3 { + frame(vec![]); + } + let popup = ctx.memory(|memory| memory.area_rect(egui::Popup::default_response_id(&button))).expect("open menu"); + let space = (screen.bottom() - button.rect.bottom()).max(button.rect.top() - screen.top()); + assert!(space < 64.0, "fixture has less space than egui's default minimum scroll height"); + // A complete command row may not fit, but the scroll area's minimum must not make + // the popup exceed its height budget or cover the button that dismisses it. + assert!(popup.height() <= space, "tiny menu respects its available height: {popup:?}, {space}"); + assert!(screen.contains_rect(popup), "tiny menu remains inside the viewport: {popup:?}"); + assert!( + popup.top() >= button.rect.bottom() - 1.0 || popup.bottom() <= button.rect.top() + 1.0, + "tiny menu stays beside its anchor: {popup:?}, {:?}", + button.rect + ); +} + +#[test] +fn clipped_submenu_does_not_open_when_hovering_outside_menu() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 900.0)); + let entries = vec![Item::Sub("Hidden submenu".into(), vec![cmd_item("app.preferences", Value::Null)])]; + let mut tick = 0; + let mut frame = |spacing: f32, events: Vec| { + tick += 1; + let mut button_rect = egui::Rect::NOTHING; + let mut hidden_submenu = None; + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { + egui::MenuBar::new().ui(ui, |ui| { + let response = ui.menu_button("Menu", |ui| { + egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| { + ui.add_space(spacing); + let button_id = ui.next_auto_id(); + menu_items(&mut app, ui, &entries, "Test"); + let response = ui.ctx().read_response(button_id).expect("submenu button response"); + let open = egui::containers::menu::MenuState::from_ui(ui, |state, _| state.open_item.is_some()); + hidden_submenu = Some((response.rect, ui.clip_rect(), open)); + }); + }); + button_rect = response.response.rect; + }); + }); + output.textures_delta.clear(); + (button_rect, hidden_submenu) + }; + frame(500.0, vec![]); + let button = frame(500.0, vec![]).0.center(); + for pressed in [true, false] { + frame( + 500.0, + vec![ + egui::Event::PointerMoved(button), + egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + for _ in 0..3 { + frame(500.0, vec![]); + } + let (_, Some((hidden, clip, open))) = frame(500.0, vec![]) else { panic!("test menu is open") }; + assert!(!open, "submenu starts closed"); + assert!(screen.contains_rect(hidden), "hidden row remains inside the screen: {hidden:?}"); + assert!(!clip.intersects(hidden), "submenu must be fully clipped: {hidden:?}, {clip:?}"); + let (_, Some((_, _, open))) = frame(500.0, vec![egui::Event::PointerMoved(hidden.center())]) else { panic!("test menu remains open") }; + assert!(!open, "hovering the clipped row's position outside the menu must not open its submenu"); + + let partial_spacing = 500.0 - (hidden.top() - clip.bottom()) - 6.0; + let (_, Some((partial, clip, open))) = frame(partial_spacing, vec![]) else { panic!("test menu remains open") }; + assert!(!open); + assert!(partial.top() < clip.bottom() && partial.bottom() > clip.bottom(), "row must be partially clipped: {partial:?}, {clip:?}"); + let outside = egui::pos2(partial.center().x, clip.bottom() + 1.0); + let (_, Some((_, _, open))) = frame(partial_spacing, vec![egui::Event::PointerMoved(outside)]) else { panic!("test menu remains open") }; + assert!(!open, "hovering the clipped portion of a partially visible row must not open its submenu"); + let visible = partial.intersect(clip).center(); + let (_, Some((_, _, open))) = frame(partial_spacing, vec![egui::Event::PointerMoved(visible)]) else { panic!("test menu remains open") }; + assert!(open, "hovering the visible portion still opens the submenu"); + let (_, Some((_, _, open))) = frame(500.0, vec![]) else { panic!("test menu remains open") }; + assert!(!open, "an open submenu closes when its row becomes fully clipped"); +} + +#[test] +fn native_labels_keep_their_ampersands() { + assert_eq!(native_label("Numbering & Section Options…"), "Numbering && Section Options…"); + assert_eq!(native_label("A&&B"), "A&&&&B"); + assert_eq!(native_label("Pages"), "Pages"); +} + +#[test] +fn the_mac_window_menu_minimizes_with_cmd_m() { + let window = native_menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, e)| e).unwrap_or_default(); + assert!(matches!(window.first(), Some(Item::Cmd { id, shortcut: Some("Cmd+M"), .. }) if id == "window.minimize"), "{:?}", window.first()); + assert!(matches!(window.get(1), Some(Item::Sep))); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert!(run_ui(&mut app, "window.minimize", &Value::Null).is_some_and(|r| r.is_err()), "no host window controls"); + app.native_menu = true; + assert!(menu_enabled(&app, "window.minimize") && !menu_enabled(&app, "window.maximize")); + run_ui(&mut app, "window.minimize", &Value::Null).unwrap().unwrap(); + assert_eq!(app.pending_window_commands, [egui::ViewportCommand::Minimized(true)]); +} + +#[test] +fn mac_settings_follow_about_in_the_app_menu_and_leave_edit() { + let pos = |command: &str| MAC_APP_MENU.iter().position(|m| matches!(m, AppMenuItem::Cmd { command: c, .. } if *c == command)); + let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") }; + assert!(about < settings); + assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep)); + // Language follows Settings, as in the suite's other apps, titled in the interface language. + assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Language)); + assert_eq!(MAC_APP_MENU.get(settings + 2), Some(&AppMenuItem::Sep)); + let label = |command: &str| { + MAC_APP_MENU.iter().find_map(|m| match m { + AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label), + _ => None, + }) + }; + assert_eq!(label("app.preferences"), Some("Settings…")); + let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::>(); + assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}"); + + let edit = |tree: Vec<(&'static str, Vec)>| { + let mut out = Vec::new(); + walk(&tree.into_iter().find(|(t, _)| *t == "Edit").map(|(_, e)| e).unwrap_or_default(), &mut out); + out.into_iter().map(|(_, id, _)| id).collect::>() + }; + assert!(edit(menu_tree()).iter().any(|id| id == "app.preferences"), "the in-window Edit menu keeps Preferences"); + let native = native_menu_tree(); + let mut all = Vec::new(); + for (_, entries) in &native { + walk(entries, &mut all); + } + assert!(!all.iter().any(|(_, id, _)| id == "app.preferences"), "the macOS menu bar has Settings only in the app menu"); + assert!(edit(native_menu_tree()).iter().any(|id| id == "app.keyboardShortcuts")); + for (title, entries) in &native { + assert!(!matches!(entries.first(), Some(Item::Sep)) && !matches!(entries.last(), Some(Item::Sep)), "{title}: separator at an end"); + assert!(entries.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep])), "{title}: doubled separator"); + } +} + +/// Web save: a download that couldn't start is an error and leaves the document unsaved; one +/// that started marks it saved. +#[test] +fn web_save_marks_the_document_saved_only_after_the_download_starts() { + let dir = tempfile::tempdir().unwrap(); + // The title names a temporary path: on native, file.saveAs writes where the web build doesn't. + let title = dir.path().join("doc").to_string_lossy().to_string(); + let fails = std::rc::Rc::new(std::cell::Cell::new(true)); + let f = fails.clone(); + let services = crate::Services { + download: Some(Box::new(move |_: &str, _: &[u8]| if f.get() { Err("blocked".into()) } else { Ok(()) })), + ..Default::default() + }; + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.run("file.new", json!({"title": title})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 300, 200]})).unwrap(); + assert!(app.session.active().unwrap().is_dirty()); + + let e = app.run("app.save", json!({})).unwrap_err(); + assert!(e.contains("blocked"), "{e}"); + assert!(app.session.active().unwrap().is_dirty(), "a failed download leaves the document unsaved"); + + fails.set(false); + app.run("app.save", json!({})).unwrap(); + assert!(!app.session.active().unwrap().is_dirty()); +} + +fn start_screen_texts(app: &mut crate::DesignApp) -> Vec { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, ""); + let mut shapes = Vec::new(); + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + shapes = out.shapes; + } + shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_string()), + _ => None, + }) + .collect() +} + +/// File › Open Recent: the files first (`app.openRecent {index}`), then Clear Recent Files. +#[test] +fn open_recent_lists_the_files_then_clear() { + let tree = menu_tree(); + let file = &tree.iter().find(|(m, _)| *m == "File").unwrap().1; + let Some(Item::Sub(name, children)) = file.get(2) else { panic!("Open Recent after Open…: {:?}", file.get(2)) }; + assert_eq!(format!("File/{name}"), OPEN_RECENT); + assert!(matches!(children.as_slice(), [Item::Cmd { id, .. }] if id == "file.clearRecent")); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert!(recent_items(&app).is_empty()); + assert!(!menu_enabled(&app, "file.clearRecent")); + app.session.prefs.note_recent_file("/work/a.designcraft"); + app.session.prefs.note_recent_file("/work/b.idml"); + let items = recent_items(&app); + let labels: Vec<_> = items + .iter() + .map(|i| match i { + Item::Cmd { label, id, params, .. } => format!("{label} {id} {params}"), + Item::Sep => "-".into(), + Item::Sub(..) => "sub".into(), + }) + .collect(); + assert_eq!(labels, ["b.idml app.openRecent {\"index\":0}", "a.designcraft app.openRecent {\"index\":1}", "-"]); + assert!(menu_enabled(&app, "file.clearRecent")); + assert!(menu_enabled(&app, "app.openRecent")); +} + +/// A recent file that is gone says so in an alert (and the start screen still lists it). +#[test] +fn open_recent_of_a_missing_file_alerts_and_the_start_screen_lists_recent_files() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert!(!start_screen_texts(&mut app).iter().any(|t| t == "Recent files"), "no section without recent files"); + app.session.prefs.note_recent_file("/nonexistent/dc-recent/gone.designcraft"); + assert!(app.run("app.openRecent", json!({"index": 0})).is_err()); + let d = app.ui.dialog.take().expect("an alert"); + assert_eq!(d.fields["title"], "Can't Open the File"); + assert_eq!(d.fields["file"], "gone.designcraft"); + assert!(d.fields["message"].as_str().unwrap().contains("can't be found")); + assert!(app.run("app.openRecent", json!({"index": 9})).is_err(), "out of range: an error, not a panic"); + app.ui.dialog = None; + let texts = start_screen_texts(&mut app); + assert!(texts.iter().any(|t| t == "Recent files"), "{texts:?}"); + assert!(texts.iter().any(|t| t == "gone"), "the card names it without `.designcraft`: {texts:?}"); +} + +/// On a short window (1366 x 768 laptops) the start screen is taller than the window; the part +/// below the fold has to be reachable by scrolling instead of being cut off. +#[test] +fn start_screen_scrolls_when_the_window_is_too_short() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, ""); + let size = egui::vec2(1366.0, 300.0); + let mut tile_y = |events: Vec| { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + out.shapes.iter().find_map(|s| match &s.shape { + // The preset tiles paint their names even when scrolled out of view (labels skip that). + egui::Shape::Text(t) if t.galley.text() == "Tabloid" => Some(t.pos.y), + _ => None, + }) + }; + let at = egui::pos2(600.0, 150.0); + let mut before = None; + for _ in 0..3 { + before = tile_y(vec![egui::Event::PointerMoved(at)]); + } + let before = before.expect("the Tabloid tile is laid out"); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -400.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }; + let mut after = tile_y(vec![egui::Event::PointerMoved(at), wheel]); + for _ in 0..30 { + after = tile_y(Vec::new()); + } + let after = after.expect("the Tabloid tile is laid out"); + assert!(after < before - 50.0, "the start screen should scroll: {before} -> {after}"); +} + +// Regression test for #329: on the start screen (no document) the Help menu's links were greyed out. +#[test] +fn help_links_are_enabled_without_a_document() { + let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + assert!(app.session.active().is_none()); + let ids: Vec<&str> = UI_COMMANDS.iter().map(|c| c.0).filter(|id| id.starts_with("help.")).collect(); + assert!(ids.contains(&"help.discord") && ids.contains(&"help.github"), "{ids:?}"); + for id in ids { + assert!(menu_enabled(&app, id), "{id} must work from the start screen"); + } + assert!(!menu_enabled(&app, "view.rulers"), "other UI commands still need a document"); +} + +// Regression test for #248: the start screen offered no A6 sheet (it listed only the first ten presets). +#[test] +fn start_screen_offers_every_print_preset_including_a6() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let texts = start_screen_texts(&mut app); + for p in designcraft_doc::build::PRESETS.iter().filter(|p| p.intent == designcraft_doc::Intent::Print) { + assert!(texts.iter().any(|t| t == p.name), "start screen lacks the {} card: {texts:?}", p.name); + } + assert!(texts.iter().any(|t| t == "A6"), "{texts:?}"); + let a6 = designcraft_doc::build::PRESETS.iter().find(|p| p.name == "A6").unwrap(); + assert!((a6.width - 105.0 * 72.0 / 25.4).abs() < 0.01 && (a6.height - 148.0 * 72.0 / 25.4).abs() < 0.01, "{a6:?}"); + let page = crate::panels::properties::PAGE_PRESETS.iter().find(|p| p.0 == "A6").expect("Properties page-size list has A6"); + assert!((page.1 - a6.width).abs() < 0.01 && (page.2 - a6.height).abs() < 0.01, "{page:?} vs {a6:?}"); +} + +// Regression test for #249: a menu row only reacted over its text, not across the whole row. +#[test] +fn menu_rows_are_selectable_across_the_full_width() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let entries = vec![cmd_item("app.preferences", Value::Null)]; + let mut tick = 0; + let mut frame = |app: &mut DesignApp, events: Vec| { + tick += 1; + let mut row = egui::Rect::NOTHING; + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| { + egui::Area::new(egui::Id::unique("menu_rows")).fixed_pos(egui::pos2(50.0, 50.0)).show(ui.ctx(), |ui| { + let before = ui.cursor().min; + menu_column(app, ui, &[("Test", entries.clone())]); + row = egui::Rect::from_min_max(before, ui.min_rect().max); + }); + }); + output.textures_delta.clear(); + row + }; + frame(&mut app, vec![]); + let row = frame(&mut app, vec![]); + assert!(row.width() >= 239.0, "the column is at least 240 wide: {row:?}"); + let far = egui::pos2(row.right() - 6.0, row.top() + 8.0); + for pressed in [true, false] { + frame( + &mut app, + vec![ + egui::Event::PointerMoved(far), + egui::Event::PointerButton { pos: far, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + assert!(app.ui.dialog.is_some(), "clicking the empty end of the Preferences… row must choose it"); +} + +/// Quick Apply and the menu search list no unavailable docking command and no label twice +/// among the UI commands. +#[test] +fn searched_ui_commands_are_available_and_named_once() { + let ui_ids: Vec<&str> = UI_COMMANDS.iter().map(|c| c.0).collect(); + let searched: Vec<(&str, &str)> = quick_commands().filter(|c| ui_ids.contains(&c.0)).map(|c| (c.0, c.1)).collect(); + assert!(!searched.iter().any(|c| matches!(c.0, "window.panel.window" | "window.workspace.lock" | "window.workspace")), "{searched:?}"); + assert!(searched.iter().any(|c| c.0 == "window.collapseToIcons"), "Collapse to Icons is searched"); + // Quick Apply runs an entry as `app.run(id, {})`, so each docking command it lists must + // work without params. + let docking = |id: &str| { + id.starts_with("window.panel") + || id.starts_with("window.workspace") + || id.starts_with("ui.dock") + || matches!(id, "window.floatPanel" | "window.dockPanel" | "window.collapseToIcons" | "window.resetWorkspace") + }; + let failing: Vec<(&str, String)> = searched + .iter() + .filter(|c| docking(c.0)) + .filter_map(|c| { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run(c.0, json!({})).err().map(|e| (c.0, e)) + }) + .collect(); + assert!(failing.is_empty(), "searched docking commands that fail with {{}}: {failing:?}"); + let mut labels: Vec<&str> = searched.iter().map(|c| c.1).collect(); + labels.sort_unstable(); + let before = labels.len(); + labels.dedup(); + assert_eq!(labels.len(), before, "a label twice: {searched:?}"); +} + +/// Keys a floating panel's own OS window left over run the main window's tool shortcuts, +/// Escape and the active tool's keys. +#[test] +fn forwarded_keys_run_shortcuts() { + use egui::{Event, Key, Modifiers}; + fn press(key: Key) -> Vec { + [true, false].map(|pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE }).to_vec() + } + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let frame = app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); + app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap(); + forwarded_shortcuts(&mut app, &ctx, press(Key::P), Modifiers::NONE); + assert_ne!(app.session.tool_id(), "selection", "P picks a tool"); + forwarded_shortcuts(&mut app, &ctx, press(Key::Escape), Modifiers::NONE); + assert_eq!(app.session.tool_id(), "selection", "Escape goes back to the Selection tool"); + app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap(); + forwarded_shortcuts(&mut app, &ctx, press(Key::Delete), Modifiers::NONE); + assert!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(frame["id"].as_u64().unwrap())).is_none(), "Delete clears the selection"); +} From 4abd7aea8c7f3b6326219dad11c8b745f16d453f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:17 +0000 Subject: [PATCH 08/70] refactor(ui-egui): move the tests module of canvas.rs to canvas/tests.rs --- crates/ui-egui/src/canvas.rs | 2854 +--------------------------- crates/ui-egui/src/canvas/tests.rs | 2839 +++++++++++++++++++++++++++ 2 files changed, 2840 insertions(+), 2853 deletions(-) create mode 100644 crates/ui-egui/src/canvas/tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 64bed51d8..9690ba36e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4157,2859 +4157,7 @@ mod parent_canvas_tests; mod guide_selection_tests; #[cfg(test)] -mod tests { - use designcraft_geom::Unit; - use egui_kittest::{Harness, kittest::Queryable}; - - use super::*; - - #[test] - fn a_press_after_a_drag_is_not_a_double_click() { - let (delay, dist) = (0.3, 6.0); - let press = |last, x: f32, now| press_count(last, pos2(x, 0.0), now, delay, dist); - // Click, click: a double click. - let n = press(None, 0.0, 0.0); - let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n }, pos2(0.0, 0.0), 0.1, dist); - assert_eq!(press(Some(up), 1.0, 0.2), 2); - // A drag from 0 to 100, then a fast press where it started or where it ended: a single click. - let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n: 1 }, pos2(100.0, 0.0), 0.1, dist); - assert_eq!(press(Some(up), 0.0, 0.2), 1); - assert_eq!(press(Some(up), 100.0, 0.2), 1); - // Too slow: a single click. - let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n: 1 }, pos2(0.0, 0.0), 0.1, dist); - assert_eq!(press(Some(up), 0.0, 1.0), 1); - } - - /// While a page's render is on its way the page shows paper, not the black of its shadow. - #[test] - fn pages_show_paper_under_their_render() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let mut shapes = Vec::new(); - for _ in 0..2 { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); - out.textures_delta.clear(); - shapes = out.shapes; - } - let st = app.session.active().unwrap(); - let layout = CanvasLayout::new(&st.doc, false); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - // The paper swatch on screen (white, as the colour settings show it). - let [r, g, b, _] = st.doc.resolve_color(designcraft_color::swatch::PAPER, 1.0).unwrap().to_rgba8(1.0); - let paper: Vec = shapes - .iter() - .filter_map(|c| match &c.shape { - egui::Shape::Rect(s) if s.fill == Color32::from_rgb(r, g, b) => Some(s.rect), - _ => None, - }) - .collect(); - // Each page on its own (a spread's pages may differ in size). - assert_eq!(paper.len(), st.doc.page_count()); - for abs in 0..st.doc.page_count() { - let want = xf.rect(layout.page_rect(&st.doc, abs).unwrap()); - assert!(paper.iter().any(|r| (r.min - want.min).length() < 0.01 && (r.max - want.max).length() < 0.01), "page {abs}"); - } - } - - /// Bleed and Slug are preview modes: like Preview they hide the guides, and what the page - /// shows widens to the bleed or the slug box. The slug guide is drawn in Normal, in its own - /// colour, beside the bleed guide. - #[test] - fn bleed_and_slug_are_preview_modes_that_show_their_area() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", serde_json::json!({"bleed": 9, "slug": 18})).unwrap(); - let strokes = |app: &mut DesignApp, want: [u8; 3]| -> usize { - let ctx = egui::Context::default(); - let mut shapes = Vec::new(); - for _ in 0..2 { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(app, ui)); - out.textures_delta.clear(); - shapes = out.shapes; - } - let want = c32(want); - shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(s) if s.stroke.color == want)).count() - }; - let s = app.session.active().unwrap().doc.settings.clone(); - // Normal draws every guide, the slug's among them. - app.ui.screen_mode = ScreenMode::Normal; - assert!(strokes(&mut app, s.margin_color) > 0, "Normal draws the margin guide"); - assert!(strokes(&mut app, s.bleed_color) > 0, "Normal draws the bleed guide"); - assert!(strokes(&mut app, s.slug_color) > 0, "Normal draws the slug guide"); - // Every preview mode hides them. - for mode in [ScreenMode::Preview, ScreenMode::Bleed, ScreenMode::Slug, ScreenMode::Presentation] { - app.ui.screen_mode = mode; - assert_eq!(strokes(&mut app, s.margin_color), 0, "{mode:?} hides the margin guide"); - assert_eq!(strokes(&mut app, s.slug_color), 0, "{mode:?} hides the slug guide"); - } - } - - /// Each preview mode's shown area: Preview stops at the trim, Bleed reaches the bleed box and - /// Slug the slug box. A slug narrower than the bleed never pulls the edge back in. - #[test] - fn shown_area_widens_to_the_bleed_and_slug_boxes() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", serde_json::json!({"bleed": 9, "slug": 18})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - let layout = CanvasLayout::new(&doc, false); - let xf = Xf::new(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)), &View::default()); - let slot = &layout.slots[0]; - let area = |app: &mut DesignApp, mode| { - app.ui.screen_mode = mode; - shown_area(app, &doc, &xf, slot) - }; - let trim = xf.rect(slot.bounds); - assert_eq!(area(&mut app, ScreenMode::Preview), trim, "Preview stops at the trim"); - assert_eq!(area(&mut app, ScreenMode::Presentation), trim, "Presentation stops at the trim"); - let bleed = area(&mut app, ScreenMode::Bleed); - let slug = area(&mut app, ScreenMode::Slug); - assert!(bleed.contains_rect(trim) && bleed != trim, "Bleed reaches past the trim"); - assert!(slug.contains_rect(bleed) && slug != bleed, "Slug reaches past the bleed"); - // 9 pt of bleed and 18 pt of slug at this zoom, on every edge. - let grew = |r: Rect, pt: f64| { - let d = (pt * xf.zoom) as f32; - (r.min - trim.min + vec2(d, d)).length() < 0.01 && (r.max - trim.max - vec2(d, d)).length() < 0.01 - }; - assert!(grew(bleed, 9.0), "Bleed grows by the bleed: {bleed:?}"); - assert!(grew(slug, 18.0), "Slug grows by the slug: {slug:?}"); - // A slug inside the bleed: Slug still shows every printing element, so the bleed too. - app.run("file.new", serde_json::json!({"bleed": 18, "slug": 9})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - app.ui.screen_mode = ScreenMode::Slug; - assert!(grew(shown_area(&app, &doc, &xf, slot), 18.0), "the wider of the two boxes wins"); - // No bleed and no slug: nothing to widen to. - app.run("file.new", serde_json::json!({})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - for mode in [ScreenMode::Bleed, ScreenMode::Slug] { - app.ui.screen_mode = mode; - assert_eq!(shown_area(&app, &doc, &xf, slot), trim, "{mode:?} without a bleed or slug"); - } - } - - /// Build the four-fps app harness used by canvas tests. - fn harness(app: DesignApp) -> Harness<'static, DesignApp> { - harness_with_step(app, 1.0 / 4.0) - } - - /// A window whose frames last `step_dt` seconds. Wheel motion is tested at a realistic frame - /// rate: egui ends a scroll action after 150 ms without wheel events, so quarter-second - /// frames would split every motion into separate actions. - fn harness_with_step(app: DesignApp, step_dt: f32) -> Harness<'static, DesignApp> { - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(step_dt).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(4); - h - } - - #[test] - fn display_option_change_drops_the_render_in_flight() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let shown = crate::Shown { doc: (1, 2, 3, false), origin: Point::new(0.0, 0.0), zoom: 1.0, size: (10.0, 10.0), editing_parents: false }; - invalidate_on_display_change(&mut app); - app.canvas.shown = Some(shown); - app.canvas.pending = Some((7, shown)); - // Nothing changed: the texture and the request stay. - invalidate_on_display_change(&mut app); - assert!(app.canvas.shown.is_some() && app.canvas.pending.is_some()); - // A display option changed while the render ran: its result must not be accepted. - app.ui.display_quality = designcraft_render::DisplayQuality::Fast; - invalidate_on_display_change(&mut app); - assert!(app.canvas.shown.is_none() && app.canvas.pending.is_none() && app.canvas.pending_doc.is_none()); - // The document grid is drawn into the texture too. - app.canvas.shown = Some(shown); - app.ui.document_grid = !app.ui.document_grid; - invalidate_on_display_change(&mut app); - assert!(app.canvas.shown.is_none()); - } - - /// A primary-button drag from `a` to `b` over a few frames. - fn drag(h: &mut Harness<'_, DesignApp>, a: Pos2, b: Pos2) { - h.hover_at(a); - h.step(); - h.event(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); - h.step(); - for k in 1..=4 { - h.hover_at(a + (b - a) * (k as f32 / 4.0)); - h.step(); - } - h.event(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); - h.run_steps(3); - } - - #[test] - fn the_page_tool_draws_liquid_guides_from_the_rulers() { - // Chris Cicchino's Page Tool and Liquid Layout video (11:00): with the Page tool, a guide - // dragged from the ruler is a liquid guide (dashed). - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.session.set_tool("page"); - let mut h = harness(app); - let r = h.state().canvas_rect.unwrap(); - let guides = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].guides.clone(); - drag(&mut h, pos2(r.center().x, r.min.y - 8.0), r.center()); - let g = guides(&h); - assert_eq!(g.len(), 1, "{g:?}"); - assert!(g[0].liquid && g[0].orientation == designcraft_doc::Orientation::Horizontal); - // With the Selection tool it's a ruler guide. - h.state_mut().session.set_tool("selection"); - drag(&mut h, pos2(r.center().x, r.min.y - 8.0), r.center() + vec2(0.0, 40.0)); - let g = guides(&h); - assert_eq!(g.len(), 2); - assert!(!g[1].liquid); - } - - /// Dragging a column guide with the Selection tool moves its gutter (one undo step); with - /// column guides locked the same drag leaves the columns alone. - #[test] - fn the_selection_tool_drags_a_column_guide() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - // Two columns across the 540 pt margin box: the gutter's left edge is at x = 300. - app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap(); - let mut h = harness(app); - let page = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].clone(); - let screen = |h: &Harness<'_, DesignApp>, x: f64| { - let app = h.state(); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); - let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap(); - (xf.to_screen(slot.xf * Point::new(x, 400.0)), xf.zoom as f32) - }; - let (at, zoom) = screen(&h, 300.0); - drag(&mut h, at, at + vec2(72.0 * zoom, 0.0)); - assert_eq!(page(&h).columns.positions, None, "column guides are locked in a new document"); - h.hover_at(at); - h.run_steps(2); - assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); - - h.state_mut().run("view.lockColumnGuides", json!({"on": false})).unwrap(); - h.run_steps(2); - let (at, zoom) = screen(&h, 300.0); - drag(&mut h, at, at + vec2(72.0 * zoom, 0.0)); - let pg = page(&h); - let cols = pg.column_rects(); - assert!((cols[0].x1 - 372.0).abs() < 1.0 && (cols[1].x0 - cols[0].x1 - 12.0).abs() < 1e-9, "{cols:?}"); - assert!(pg.local_margins, "the dragged page's columns are its own"); - // Over the moved guide: a resize cursor. - h.hover_at(screen(&h, 372.0).0); - h.run_steps(2); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(page(&h).columns.positions, None, "one undo step"); - - // Escape during the drag puts the gutter back. - h.hover_at(at); - h.step(); - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); - h.step(); - h.hover_at(at + vec2(40.0, 0.0)); - h.step(); - assert!(page(&h).columns.positions.is_some(), "the drag previews"); - h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); - h.step(); - h.event(egui::Event::PointerButton { - pos: at + vec2(40.0, 0.0), - button: egui::PointerButton::Primary, - pressed: false, - modifiers: Default::default(), - }); - h.run_steps(3); - assert_eq!(page(&h).columns.positions, None); - assert!(!page(&h).local_margins); - - // Space pressed during the drag and the button released under it: the drag ends with the - // release and the gutter stops following the pointer. - let key = |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - h.hover_at(at); - h.step(); - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); - h.step(); - h.hover_at(at + vec2(40.0, 0.0)); - h.step(); - h.event(key(true)); - h.step(); - h.event(egui::Event::PointerButton { - pos: at + vec2(40.0, 0.0), - button: egui::PointerButton::Primary, - pressed: false, - modifiers: Default::default(), - }); - h.step(); - h.event(key(false)); - h.run_steps(2); - let moved = page(&h).columns.positions; - assert!(moved.is_some()); - h.hover_at(at + vec2(120.0, 0.0)); - h.run_steps(3); - assert_eq!(page(&h).columns.positions, moved, "the gutter stays where the drag ended"); - assert!(h.state().session.active().unwrap().interaction.is_none()); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(page(&h).columns.positions, None, "the drag was one undo step"); - } - - /// A column guide is not picked where the screen mode hides guides, where an object on the - /// parent being edited lies over it, or where its columns cannot move. - #[test] - fn column_guides_are_picked_only_where_a_drag_can_move_them() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 1})).unwrap(); - app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap(); - app.run("view.lockColumnGuides", json!({"on": false})).unwrap(); - let mut h = harness(app); - let hit = |h: &Harness<'_, DesignApp>, r: SpreadRef, x: f64| { - let app = h.state(); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - let st = app.session.active().unwrap(); - let layout = CanvasLayout::new(&st.doc, st.editing_parents); - let slot = layout.slots.iter().find(|s| s.spread == r).unwrap(); - column_guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(x, 400.0))) - }; - assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_some()); - h.state_mut().ui.screen_mode = ScreenMode::Preview; - assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_none(), "Preview hides the guides"); - h.state_mut().ui.screen_mode = ScreenMode::Normal; - - // Editing parent A: its right page (the one page 0 follows) and a frame over its gutter. - h.state_mut().run("layout.parents.edit", json!({"on": true, "parent": "A-Parent"})).unwrap(); - h.run_steps(2); - let parent = SpreadRef::Parent(0); - let x = h.state().session.active().unwrap().doc.parents[0].pages[1].column_rects()[0].x1; - assert!(hit(&h, parent, x).is_some()); - h.state_mut() - .run("frame.create", json!({"spread": {"kind": "parent", "index": 0}, "rect": [x - 20.0, 300.0, x + 20.0, 500.0], "content": "text"})) - .unwrap(); - h.run_steps(2); - assert!(hit(&h, parent, x).is_none(), "the parent's frame takes the press"); - h.state_mut().run("layout.parents.edit", json!({"on": false})).unwrap(); - h.run_steps(2); - - // Gutters wider than the margin box: the even split cannot be moved. - h.state_mut().run("layout.marginsAndColumns", json!({"pages": [0], "columns": 2, "gutter": 1000})).unwrap(); - h.run_steps(2); - let x = h.state().session.active().unwrap().doc.spreads[0].pages[0].column_rects()[0].x1; - assert!(hit(&h, SpreadRef::Doc(0), x).is_none()); - } - - fn right_click(h: &mut Harness<'_, DesignApp>, p: Pos2) { - h.hover_at(p); - h.step(); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }); - } - h.run_steps(3); - } - - fn new_document() -> Harness<'static, DesignApp> { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - harness(app) - } - - /// [`new_document`] at 60 frames a second, the cadence a wheel motion really arrives at. - fn new_document_60fps() -> Harness<'static, DesignApp> { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - harness_with_step(app, 1.0 / 60.0) - } - - fn held(modifiers: egui::Modifiers) -> egui::Event { - egui::Event::ModifiersChanged(modifiers) - } - - /// Construct a point-unit vertical mouse-wheel event with an unknown source. - fn wheel(phase: egui::TouchPhase, up: f32, modifiers: egui::Modifiers) -> egui::Event { - egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, up), phase, modifiers, source: egui::MouseWheelSource::Unknown } - } - - // Plays `events` with the pointer at `at`, a frame each, and lets the motion settle. - fn play(h: &mut Harness<'_, DesignApp>, at: Pos2, events: &[egui::Event]) -> View { - h.hover_at(at); - for event in events { - h.event(event.clone()); - h.step(); - } - h.run_steps(30); - *h.state().view().unwrap() - } - - /// Alt + wheel scrolled the view like the plain wheel; it zooms at the pointer (#470). - #[test] - fn alt_wheel_zooms_at_the_pointer() { - use egui::{Modifiers, TouchPhase::Move}; - let mut h = new_document(); - let rect = h.state().canvas_rect.unwrap(); - let at = rect.center() + vec2(150.0, 90.0); - let before = *h.state().view().unwrap(); - let under = Xf::new(rect, &before).to_canvas(at); - let zoomed = play(&mut h, at, &[held(Modifiers::ALT), wheel(Move, 100.0, Modifiers::ALT)]); - assert!(zoomed.zoom > before.zoom * 1.2, "wheel up zooms in: {} -> {}", before.zoom, zoomed.zoom); - let still = Xf::new(rect, &zoomed).to_canvas(at); - assert!((still.x - under.x).abs() < 0.01 && (still.y - under.y).abs() < 0.01, "the point under the pointer stays: {under:?} -> {still:?}"); - let back = play(&mut h, at, &[held(Modifiers::ALT), wheel(Move, -100.0, Modifiers::ALT)]); - assert!((back.zoom - before.zoom).abs() < 1e-6, "wheel down zooms out: {} -> {}", zoomed.zoom, back.zoom); - // The plain wheel still scrolls. - let scrolled = play(&mut h, at, &[held(Modifiers::NONE), wheel(Move, 100.0, Modifiers::NONE)]); - assert!(scrolled.zoom == back.zoom && scrolled.origin.y < back.origin.y, "{back:?} -> {scrolled:?}"); - } - - /// Alt zooms exactly as Ctrl/Cmd does, also when the key is let go while the wheel's motion is - /// still arriving: the rest of it zooms too and does not scroll the page. - #[test] - fn alt_wheel_zooms_like_ctrl_wheel_to_the_end_of_the_motion() { - use egui::{ - Modifiers, - TouchPhase::{End, Move, Start}, - }; - const NONE: Modifiers = Modifiers::NONE; - // Each motion in steps; the views are compared after every step. - let motions: [fn(Modifiers) -> Vec>; 4] = [ - |key| vec![vec![held(key), wheel(Move, 100.0, key)]], - // A wheel turned fast, the key let go a frame later. - |key| vec![vec![held(key), wheel(Move, 400.0, key), held(NONE)]], - // A trackpad swipe that coasts on after the key is let go; once it has ended, the wheel scrolls. - |key| { - vec![ - vec![held(key), wheel(Start, 0.0, key), wheel(Move, 50.0, key), held(NONE), wheel(Move, 200.0, NONE)], - vec![wheel(End, 0.0, NONE), wheel(Move, 100.0, NONE)], - ] - }, - |key| vec![vec![held(key | Modifiers::SHIFT), wheel(Move, 100.0, key | Modifiers::SHIFT)]], - ]; - for (i, motion) in motions.iter().enumerate() { - let (mut with_alt, mut with_command) = (new_document_60fps(), new_document_60fps()); - let at = with_alt.state().canvas_rect.unwrap().center() + vec2(150.0, 90.0); - let start = *with_alt.state().view().unwrap(); - for (alt, command) in motion(Modifiers::ALT).iter().zip(motion(Modifiers::COMMAND)) { - let (alt, command) = (play(&mut with_alt, at, alt), play(&mut with_command, at, &command)); - assert!(command.zoom > start.zoom, "motion {i} zooms"); - assert_eq!(alt, command, "motion {i}"); - } - } - } - - fn units(h: &Harness<'_, DesignApp>) -> (Unit, Unit) { - let s = &h.state().session.doc().unwrap().doc.settings; - (s.horizontal_units, s.vertical_units) - } - - fn zoom_app(tool: &str) -> DesignApp { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.select_tool(tool); - app.ui.rulers = false; - app - } - - /// Run one app frame with the supplied modifiers, install fonts, draw the canvas when ready and return the cursor icon. - fn canvas_frame(app: &mut DesignApp, ctx: &egui::Context, m: egui::Modifiers, mut events: Vec) -> egui::CursorIcon { - events.insert(0, egui::Event::ModifiersChanged(m)); - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }, - |ui| { - app.logic(ui.ctx()); - // Fonts are installed by the first real UI pass, just as in the full application. - app.ui_setup(ui.ctx()); - if app.fonts_ready { - show(app, ui); - } - }, - ); - output.textures_delta.clear(); - output.platform_output.cursor_icon - } - - /// The cursor icon the canvas sets for `c` on this platform (bitmap and painted cursors - /// report their own icon). - fn shown(c: Cursor) -> egui::CursorIcon { - crate::cursors::show(&egui::Context::default(), &mut crate::cursors::Images::default(), c, Pos2::ZERO) - } - - fn space_key(pressed: bool, modifiers: egui::Modifiers) -> egui::Event { - egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers } - } - - fn press(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } - } - - fn hover(app: &mut DesignApp, ctx: &egui::Context, p: Pos2) { - for _ in 0..3 { - canvas_frame(app, ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p)]); - } - } - - const CMD: egui::Modifiers = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; - - #[test] - fn spring_zoom_click_is_anchored_view_only_and_release_restores_previous_tool() { - for tool in ["rectangleFrame", "directSelection", "type", "hand", "zoom"] { - let mut app = zoom_app(tool); - if tool == "rectangleFrame" { - let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap(); - app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap(); - } - let ctx = egui::Context::default(); - let p = pos2(300.0, 250.0); - hover(&mut app, &ctx, p); - let before = *app.view().unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - let selection = app.session.doc().unwrap().selection.clone(); - let history = app.run("document.history", json!({})).unwrap(); - let cursor = canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]); - assert_eq!(cursor, shown(Cursor::ZoomIn), "{tool}"); - canvas_frame(&mut app, &ctx, CMD, vec![press(p, true, CMD)]); - canvas_frame(&mut app, &ctx, CMD, vec![press(p, false, CMD)]); - let after = *app.view().unwrap(); - assert_eq!(after.zoom, before.zoom * 2.0, "{tool}"); - let anchor = Xf::new(app.canvas_rect.unwrap(), &before).to_canvas(p); - assert!((Xf::new(app.canvas_rect.unwrap(), &after).to_canvas(p) - anchor).hypot() < 1e-9); - let cursor = canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]); - assert_eq!(app.session.tool_id(), tool); - let expected = app.session.cursor(anchor, Mods::default(), app.view_info()); - assert_eq!(cursor, shown(expected), "{tool}"); - assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); - assert_eq!(selection, app.session.doc().unwrap().selection); - assert_eq!(history, app.run("document.history", json!({})).unwrap()); - } - } - - #[test] - fn spring_zoom_alt_clicks_out_and_modifier_release_switches_back_to_hand() { - let mut app = zoom_app("rectangleFrame"); - let ctx = egui::Context::default(); - let p = pos2(300.0, 250.0); - hover(&mut app, &ctx, p); - let z = app.view().unwrap().zoom; - let alt = egui::Modifiers { alt: true, ..CMD }; - assert_eq!(canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]), shown(Cursor::ZoomIn)); - assert_eq!(canvas_frame(&mut app, &ctx, alt, vec![]), shown(Cursor::ZoomOut)); - canvas_frame(&mut app, &ctx, alt, vec![press(p, true, alt)]); - canvas_frame(&mut app, &ctx, alt, vec![press(p, false, alt)]); - assert_eq!(app.view().unwrap().zoom, z * 0.5); - assert_eq!(canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![]), shown(Cursor::Hand)); - let before = *app.view().unwrap(); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p + vec2(80.0, 0.0))]); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p + vec2(80.0, 0.0), false, egui::Modifiers::NONE)]); - assert_eq!(app.view().unwrap().zoom, before.zoom); - assert!(app.view().unwrap().origin.x < before.origin.x); - assert_eq!(app.session.tool_id(), "rectangleFrame"); - } - - #[test] - fn spring_zoom_scrubs_and_owns_pointer_release_after_shortcut_release() { - let mut app = zoom_app("rectangleFrame"); - let ctx = egui::Context::default(); - let p = pos2(300.0, 250.0); - hover(&mut app, &ctx, p); - let z = app.view().unwrap().zoom; - let doc = app.session.doc().unwrap().doc.clone(); - // Ctrl is the platform command modifier on Windows/Linux, using the same input path. - let cmd = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - canvas_frame(&mut app, &ctx, cmd, vec![space_key(true, cmd), press(p, true, cmd)]); - let end = p + vec2(150.0, 0.0); - canvas_frame(&mut app, &ctx, cmd, vec![egui::Event::PointerMoved(end)]); - assert!((app.view().unwrap().zoom - z * std::f64::consts::E).abs() < 1e-9); - let scrubbed = app.view().unwrap().zoom; - assert_eq!(canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]), shown(Cursor::Crosshair)); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(end, false, egui::Modifiers::NONE)]); - assert_eq!(app.view().unwrap().zoom, scrubbed, "no extra click zoom at the end of a scrub"); - assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); - // The original tool still draws after the temporary gesture. - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p + vec2(50.0, 50.0))]); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p + vec2(50.0, 50.0), false, egui::Modifiers::NONE)]); - assert!(!std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); - assert_eq!(app.session.tool_id(), "rectangleFrame"); - } - - #[test] - fn spring_zoom_is_suppressed_while_typing_in_a_text_frame() { - let mut app = zoom_app("type"); - let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap(); - app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap(); - assert!(app.session.wants_text()); - let ctx = egui::Context::default(); - let p = pos2(300.0, 250.0); - hover(&mut app, &ctx, p); - let before = *app.view().unwrap(); - let alt = egui::Modifiers { alt: true, ..CMD }; - for m in [CMD, alt] { - app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap(); - assert!(app.session.wants_text()); - assert!(!matches!(canvas_frame(&mut app, &ctx, m, vec![space_key(true, m)]), egui::CursorIcon::ZoomIn | egui::CursorIcon::ZoomOut)); - canvas_frame(&mut app, &ctx, m, vec![press(p, true, m)]); - canvas_frame(&mut app, &ctx, m, vec![press(p, false, m)]); - assert_eq!(app.view().unwrap().zoom, before.zoom); - assert_eq!(app.view().unwrap().origin, before.origin); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]); - } - } - - #[test] - fn spring_zoom_is_suppressed_while_a_text_field_has_focus() { - let mut app = zoom_app("rectangleFrame"); - let ctx = egui::Context::default(); - let mut text = String::new(); - let p = pos2(300.0, 250.0); - hover(&mut app, &ctx, p); - let before = *app.view().unwrap(); - for m in [egui::Modifiers::NONE, CMD, egui::Modifiers { alt: true, ..CMD }] { - let mut output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), - events: vec![egui::Event::ModifiersChanged(m), space_key(true, m), egui::Event::Text("x".into()), egui::Event::PointerMoved(p)], - ..Default::default() - }, - |ui| { - ui.text_edit_singleline(&mut text).request_focus(); - show(&mut app, ui); - }, - ); - output.textures_delta.clear(); - assert!(ctx.text_edit_focused()); - assert!(!matches!(output.platform_output.cursor_icon, egui::CursorIcon::ZoomIn | egui::CursorIcon::ZoomOut | egui::CursorIcon::Grab)); - assert_eq!(app.view().unwrap().zoom, before.zoom); - assert_eq!(app.session.tool_id(), "rectangleFrame"); - } - assert!(!text.is_empty(), "typing still reaches the field"); - } - - #[test] - fn spring_zoom_does_not_interrupt_an_existing_tool_drag() { - let mut app = zoom_app("rectangleFrame"); - let ctx = egui::Context::default(); - let p = pos2(300.0, 250.0); - hover(&mut app, &ctx, p); - let before = *app.view().unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]); - let end = p + vec2(100.0, 100.0); - canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD), egui::Event::PointerMoved(end)]); - canvas_frame(&mut app, &ctx, CMD, vec![press(end, false, CMD)]); - assert_eq!(app.view().unwrap().zoom, before.zoom); - assert_eq!(app.view().unwrap().origin, before.origin); - assert!(!std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); - } - - #[test] - fn spring_zoom_does_not_zoom_on_the_rulers() { - let mut app = zoom_app("rectangleFrame"); - app.ui.rulers = true; - let ctx = egui::Context::default(); - hover(&mut app, &ctx, pos2(300.0, 250.0)); - let rect = app.canvas_rect.unwrap(); - let p = pos2(rect.min.x - RULER / 2.0, rect.center().y); - hover(&mut app, &ctx, p); - let before = *app.view().unwrap(); - canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]); - canvas_frame(&mut app, &ctx, CMD, vec![press(p, true, CMD)]); - canvas_frame(&mut app, &ctx, CMD, vec![press(p, false, CMD)]); - assert_eq!(app.view().unwrap().zoom, before.zoom); - assert_eq!(app.view().unwrap().origin, before.origin); - } - - #[test] - fn parent_guides_on_a_page_are_not_picked_there() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - // 100 pt into A's right page, which page 1 (a right page at x = 0) shows. - let parent_guide = json!({"spread": {"kind": "parent", "index": 0}, "page": 1, "orientation": "vertical", "position": 712}); - app.run("guide.add", parent_guide).unwrap(); - let mut h = harness(app); - let at = |app: &DesignApp| { - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); - let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap(); - guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(100.0, 300.0))) - }; - assert_eq!(at(h.state()), None, "the parent's guide is edited on the parent"); - h.state_mut().run("guide.add", json!({"orientation": "vertical", "position": 100})).unwrap(); - h.run_steps(2); - assert!(matches!(at(h.state()), Some((SpreadRef::Doc(0), 0, 0, _))), "the page's own guide is"); - } - - #[test] - fn mouse_double_clicking_a_frame_handle_fits_with_one_undo_step() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = designcraft_doc::ItemId( - app.run("frame.create", json!({"rect": [100, 100, 400, 300], "content": "text", "text": "Fit this text"})).unwrap()["id"] - .as_u64() - .unwrap(), - ); - app.run("selection.set", json!({"ids": [id.0]})).unwrap(); - let original = app.session.doc().unwrap().doc.item(id).unwrap().bounds(); - // 60 frames a second: the default 0.25 s step puts two clicks past egui's double-click delay. - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(4); - let app = h.state(); - let st = app.session.doc().unwrap(); - let layout = CanvasLayout::new(&st.doc, false); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - let p = xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(original.x1, original.y1)); - h.hover_at(p); - h.step(); - // Separate frames model the actual mouse, including egui's release-time double click. - for _ in 0..2 { - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - h.step(); - } - } - h.run_steps(2); - let fitted = h.state().session.doc().unwrap().doc.item(id).unwrap().bounds(); - assert!(fitted.width() < original.width() && fitted.height() < original.height(), "{fitted:?}"); - assert_eq!(h.state().session.tool_id(), "selection"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(h.state().session.doc().unwrap().doc.item(id).unwrap().bounds(), original); - } - - const ART: &str = r##""##; - - #[test] - fn pasting_svg_from_another_app_places_editable_paths_in_the_middle_of_the_view() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let mut h = harness(app); - h.run_steps(2); - let undo = h.state().session.doc().unwrap().history.undo.len(); - h.event(egui::Event::Paste(ART.into())); - h.run_steps(2); - let app = h.state(); - let st = app.session.doc().unwrap(); - assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); - let id = *st.selection.items.first().expect("the pasted path is selected"); - let it = st.doc.item(id).unwrap(); - assert_eq!(it.shape, designcraft_doc::Shape::Path); - assert_eq!(it.path.subpaths[0].anchors.len(), 2); - assert!((it.stroke.weight - 2.0).abs() < 1e-9); - // Centred where text from another app would go: the middle of the view. - let (_, centre) = view_centre(app).unwrap(); - assert!((it.bounds().center() - centre).hypot() < 0.01, "{:?} vs {centre:?}", it.bounds()); - } - - #[test] - fn the_paste_in_place_shortcut_pastes_in_place_and_plain_paste_offsets() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - let original = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds(); - app.run("edit.copy", json!({})).unwrap(); - let clip = app.object_clip_text.clone().expect("the copy's placeholder text"); - let mut h = harness(app); - let paste = |h: &mut Harness<'static, DesignApp>, modifiers: egui::Modifiers| { - // As egui-winit delivers ⌃⌥⇧V: the chord's paste and the V release, no V press; here the - // modifiers are released within the same frame. - let release = egui::Event::Key { key: egui::Key::V, physical_key: None, pressed: false, repeat: false, modifiers }; - let none = egui::Event::ModifiersChanged(egui::Modifiers::NONE); - h.input_mut().events.extend([egui::Event::ModifiersChanged(modifiers), egui::Event::Paste(clip.clone()), release, none]); - h.run_steps(2); - let st = h.state().session.doc().unwrap(); - let pasted = *st.selection.items.first().expect("the copy is selected"); - assert_ne!(pasted.0, id); - st.doc.item(pasted).unwrap().bounds() - }; - let linux = egui::Modifiers { alt: true, ctrl: true, shift: true, mac_cmd: false, command: true }; - assert_eq!(paste(&mut h, linux), original, "Paste in Place"); - let moved = paste(&mut h, egui::Modifiers::COMMAND); - assert!((moved.x0 - original.x0 - 12.0).abs() < 1e-9 && (moved.y0 - original.y0 - 12.0).abs() < 1e-9, "{moved:?}"); - // The modifiers went down in an earlier frame than the paste. - h.event_modifiers(egui::Event::Paste(clip.clone()), linux); - h.run_steps(2); - let st = h.state().session.doc().unwrap(); - let pasted = *st.selection.items.first().expect("the copy is selected"); - assert_eq!(st.doc.item(pasted).unwrap().bounds(), original); - } - - #[test] - fn edit_paste_from_the_menu_pastes_svg_on_the_system_clipboard_as_paths() { - let services = crate::Services { clipboard_text: Some(Box::new(|| Some(ART.to_string()))), ..Default::default() }; - let mut app = DesignApp::new(designcraft_engine::Session::new(), services); - app.native_menu = true; - app.run("file.new", json!({})).unwrap(); - crate::menus::activate(&mut app, "edit.paste", &Value::Null); - let st = app.session.doc().unwrap(); - let id = *st.selection.items.first().expect("the pasted path is selected"); - assert_eq!(st.doc.item(id).unwrap().shape, designcraft_doc::Shape::Path); - assert!(st.selection.text.is_none(), "paths, not a text frame of markup"); - // With an insertion point, the markup is text like any other. - let story = app.run("frame.create", json!({"rect": [10, 10, 300, 300], "content": "text"})).unwrap()["story"].clone(); - app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); - let items = app.session.doc().unwrap().doc.spreads[0].items.len(); - crate::menus::activate(&mut app, "edit.paste", &Value::Null); - assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items, "no paths added"); - } - - #[test] - fn selected_merged_owners_paint_the_same_row_and_column_targets() { - for column in [true, false] { - for merged in [false, true] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 1})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text"})).unwrap(); - app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); - if merged { - let range = if column { json!({"rows": [0, 0], "cols": [0, 1]}) } else { json!({"rows": [0, 1], "cols": [0, 0]}) }; - app.run("table.select", range).unwrap(); - app.run("table.merge", json!({})).unwrap(); - } - app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap(); - app.run(if column { "table.selectColumn" } else { "table.selectRow" }, json!({})).unwrap(); - let st = app.session.doc().unwrap(); - let selection = st.selection.clone(); - let ts = selection.text.unwrap(); - let selected = selection.cells.unwrap(); - assert_eq!( - selected.range, - if column { designcraft_doc::CellRange::new(0, 1, 1, 1) } else { designcraft_doc::CellRange::new(1, 0, 1, 1) } - ); - let layout = CanvasLayout::new(&st.doc, st.editing_parents); - let cs = app.session.cache.get(&st.doc, ts.story, None); - let ft = &cs.frames[0]; - let table = ft.tables.iter().find(|t| t.table == selected.table).unwrap(); - let (a, _) = item_canvas_xf(&st.doc, &layout, ft.frame).unwrap(); - let m = a * st.doc.text_xf(st.doc.item(ft.frame).unwrap()); - let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) }; - let owners = if merged { - [(0, 0), (1, 1)] - } else if column { - [(0, 1), (1, 1)] - } else { - [(1, 0), (1, 1)] - }; - let expected: Vec<_> = owners - .into_iter() - .map(|(r, c)| { - let rect = table.cells.iter().find(|cell| cell.row == r && cell.col == c).unwrap().rect; - vec![ - xf.to_screen(m * Point::new(rect.x0, rect.y0)), - xf.to_screen(m * Point::new(rect.x1, rect.y0)), - xf.to_screen(m * Point::new(rect.x1, rect.y1)), - xf.to_screen(m * Point::new(rect.x0, rect.y1)), - ] - }) - .collect(); - let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - draw_text_selection(&app, ui.painter(), &xf, &st.doc, &layout, ts, Some(selected)); - }); - output.textures_delta.clear(); - let tint = Color32::from_rgba_unmultiplied(80, 140, 255, 90); - let painted: Vec<_> = output - .shapes - .into_iter() - .filter_map(|s| match s.shape { - egui::Shape::Path(path) if path.fill == tint => { - assert!(path.closed); - assert_eq!(path.stroke, egui::epaint::PathStroke::NONE); - Some(path.points) - } - _ => None, - }) - .collect(); - assert_eq!(painted, expected, "only the two touched owners are tinted; column={column}, merged={merged}"); - assert_eq!(app.session.doc().unwrap().selection, selection); - } - } - } - - /// A selected group lists the text frames inside it for ports. - #[test] - fn grouped_text_frames_get_ports() { - let mut s = designcraft_engine::Session::new(); - s.execute("file.new", &json!({})).unwrap(); - let a = s.execute("frame.create", &json!({"rect": [10, 10, 110, 60], "content": "text"})).unwrap()["id"].as_u64().unwrap(); - let b = s.execute("frame.create", &json!({"rect": [10, 80, 110, 130]})).unwrap()["id"].as_u64().unwrap(); - s.execute("selection.set", &json!({"ids": [a, b]})).unwrap(); - let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); - let doc = &s.doc().unwrap().doc; - let group = doc.item(designcraft_doc::ItemId(g)).unwrap(); - let mut out = Vec::new(); - text_frames_in(group, 0, &mut out); - assert_eq!(out.iter().map(|(it, _)| it.id.0).collect::>(), vec![a], "one text frame in the group"); - // A plain text frame lists itself. - out.clear(); - text_frames_in(out_frame(doc, a), 0, &mut out); - assert_eq!(out.len(), 1); - } - - /// A selected group paints both ports of the overset text frame inside it, on top of the - /// group's own selection marks. - #[test] - fn a_selected_group_paints_both_ports_of_its_text_frame() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let s = &mut app.session; - let text = "far too much text for a frame this small, over and over again ".repeat(8); - let a = s.execute("frame.create", &json!({"rect": [100, 100, 200, 140], "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap(); - let b = s.execute("frame.create", &json!({"rect": [100, 200, 200, 260]})).unwrap()["id"].as_u64().unwrap(); - s.execute("selection.set", &json!({"ids": [a, b]})).unwrap(); - let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); - s.execute("transform.rotate", &json!({"angle": 30, "ids": [g]})).unwrap(); - s.execute("selection.set", &json!({"ids": [g]})).unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - let layout = CanvasLayout::new(&doc, false); - let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) }; - let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - draw_selection(&app, ui.painter(), &xf, &doc, &layout); - }); - output.textures_delta.clear(); - let white: Vec = output - .shapes - .into_iter() - .filter_map(|s| match s.shape { - egui::Shape::Rect(r) if r.fill == Color32::WHITE => Some(r.rect), - _ => None, - }) - .collect(); - for out in [false, true] { - let c = xf.to_screen(designcraft_tools::thread::port_center(&doc, &layout, designcraft_doc::ItemId(a), out, xf.zoom).unwrap()); - let port = white.iter().position(|r| (r.center() - c).length() < 0.01).unwrap_or_else(|| panic!("port (out: {out}) at {c:?}")); - assert!(!white[port + 1..].iter().any(|r| r.contains(c)), "nothing painted later covers the port (out: {out})"); - } - } - - fn out_frame(doc: &Document, id: u64) -> &Item { - doc.item(designcraft_doc::ItemId(id)).unwrap() - } - - /// An overset frame inside a group is listed for the red mark even when nothing is - /// selected; a frame with room, or a hidden one, is not. - #[test] - fn overset_frames_are_found_inside_groups() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let s = &mut app.session; - let frame_with = |s: &mut designcraft_engine::Session, rect: [f64; 4], text: &str| { - s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap() - }; - let tiny = frame_with(s, [10.0, 10.0, 40.0, 16.0], "far too much text for a frame this small, over and over again"); - let roomy = frame_with(s, [10.0, 100.0, 300.0, 300.0], "fits"); - s.execute("selection.set", &json!({"ids": [tiny, roomy]})).unwrap(); - s.execute("object.group", &json!({})).unwrap(); - s.execute("selection.set", &json!({"ids": []})).unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - let mut out = Vec::new(); - overset_frames(&app, &doc, &doc.spreads[0].items, 0, &mut out); - assert_eq!(out.iter().map(|it| it.id.0).collect::>(), vec![tiny]); - // Hidden: no mark. - app.session.execute("object.hide", &json!({"ids": [tiny]})).unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - out.clear(); - overset_frames(&app, &doc, &doc.spreads[0].items, 0, &mut out); - assert!(out.is_empty()); - } - - /// The always-on overset mark sits at the frame's out port, a step along its own right edge - /// (so a rotated frame gets it inside its edge, not straight up from the corner), and a - /// selected overset frame gets only the mark its ports draw. - #[test] - fn overset_mark_sits_on_the_out_port_once() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let s = &mut app.session; - let id = s - .execute("frame.create", &json!({"rect": [100, 100, 200, 160], "content": "text", "text": "far too much text for a frame this small, over and over again ".repeat(8)})) - .unwrap()["id"] - .as_u64() - .unwrap(); - s.execute("transform.rotate", &json!({"angle": 90, "ids": [id]})).unwrap(); - s.execute("selection.set", &json!({"ids": []})).unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - let layout = CanvasLayout::new(&doc, false); - let zoom = 1.0; - let marks = overset_marks(&app, &doc, &layout, &doc.spreads[0].items, zoom, &ported_frames(&app, &doc)); - assert_eq!(marks.len(), 1); - let it = out_frame(&doc, id); - let (a, _) = item_canvas_xf(&doc, &layout, it.id).unwrap(); - let m = a * it.xf; - let r = it.inner_bounds(); - let corner = m * Point::new(r.x1, r.y1); - let edge = (m * Point::new(r.x1, r.y0)) - corner; - let d = marks[0].1 - corner; - assert!((d.x * edge.y - d.y * edge.x).abs() < 1e-6, "the mark lies on the frame's right edge: {d:?} along {edge:?}"); - assert!((d.hypot() - 12.0 / zoom).abs() < 1e-6, "12 screen px from the corner: {d:?}"); - // Selected: the ports draw the mark, so no always-on mark is added. - app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); - let marks = overset_marks(&app, &doc, &layout, &doc.spreads[0].items, zoom, &ported_frames(&app, &doc)); - assert!(marks.is_empty()); - } - - #[test] - fn right_clicking_a_ruler_sets_that_rulers_units() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let mut h = harness(app); - let rect = h.state().canvas_rect.unwrap(); - assert_eq!(units(&h), (Unit::Picas, Unit::Picas)); - // Vertical ruler: the current unit is checked; picking one sets only the vertical units. - right_click(&mut h, pos2(rect.min.x - RULER / 2.0, rect.center().y)); - h.get_by_label("✓ Picas"); - h.get_by_label(" Millimeters").click(); - h.run_steps(3); - assert_eq!(units(&h), (Unit::Picas, Unit::Millimeters)); - // Horizontal ruler. - right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); - h.get_by_label("✓ Picas"); - h.get_by_label(" Inches").click(); - h.run_steps(3); - assert_eq!(units(&h), (Unit::Inches, Unit::Millimeters)); - // The corner where the rulers meet sets both, as InDesign's: nothing is checked while - // they differ. - let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0); - right_click(&mut h, corner); - assert!(h.query_by_label("✓ Inches").is_none() && h.query_by_label("✓ Millimeters").is_none()); - let _ = h.get_by_label_contains("Hide Rulers"); - let _ = h.get_by_label(" Lock Zero Point"); - assert!(h.query_by_label(" Delete All Guides on Spread").is_none(), "only on the horizontal ruler"); - h.get_by_label(" Points").click(); - h.run_steps(3); - assert_eq!(units(&h), (Unit::Points, Unit::Points)); - // InDesign's list: no Q or Ha. - right_click(&mut h, corner); - h.get_by_label("✓ Points"); - assert!(h.query_by_label(" Q").is_none() && h.query_by_label(" Ha").is_none()); - let _ = h.get_by_label(" Inches Decimal"); - // The horizontal ruler's menu also deletes the spread's guides; Hide Rulers hides them. - right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); - let _ = h.get_by_label(" Delete All Guides on Spread"); - h.get_by_label_contains("Hide Rulers").click(); - h.run_steps(3); - assert!(!h.state().ui.rulers); - // The page opens no units menu. - right_click(&mut h, rect.center()); - assert!(h.query_by_label(" Points").is_none()); - } - - /// The live-corner widget draws on a selected rectangle frame; clicking it draws the diamonds. - #[test] - fn live_corner_widget_and_diamonds_draw() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap(); - let id = app.session.doc().unwrap().doc.spreads[0].items[0].id; - app.run("selection.set", json!({"ids": [id.0]})).unwrap(); - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(1.0).wgpu().build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(4); - let screen = |h: &Harness<'_, DesignApp>, x: f64, y: f64| { - let app = h.state(); - let layout = CanvasLayout::new(&app.session.doc().unwrap().doc, false); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - xf.to_screen(layout.to_canvas(SpreadRef::Doc(0), Point::new(x, y))) - }; - let widget = screen(&h, 300.0, 100.0) + vec2(0.0, 11.5); - let diamond = screen(&h, 100.0, 100.0) + vec2(12.0, 0.0); - let yellow = |h: &mut Harness<'_, DesignApp>, p: Pos2| -> Option { - let img = match h.render() { - Ok(img) => img, - Err(e) => { - eprintln!("skipped: no offscreen renderer ({e})"); - return None; - } - }; - let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32).0; - Some(px[0] > 200 && px[1] > 180 && px[2] < 100) - }; - let Some(w) = yellow(&mut h, widget) else { return }; - assert!(w, "no widget at {widget:?}"); - assert_eq!(yellow(&mut h, diamond), Some(false)); - h.hover_at(widget); - h.step(); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: widget, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - h.step(); - } - h.run_steps(3); - assert_eq!(yellow(&mut h, diamond), Some(true), "no diamond at {diamond:?}"); - assert_eq!(yellow(&mut h, widget), Some(false)); - } - - /// A harness whose frames are 1 ms apart, so two clicks make a double-click. - fn fast_harness(app: DesignApp) -> Harness<'static, DesignApp> { - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(0.001).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(4); - h - } - - fn primary(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool) { - h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - h.run_steps(2); - } - - fn corner_drag(h: &mut Harness<'_, DesignApp>, from: Pos2, to: Pos2) { - h.hover_at(from); - h.step(); - primary(h, from, true); - h.event(egui::Event::PointerMoved(from + (to - from) / 2.0)); - h.run_steps(2); - h.event(egui::Event::PointerMoved(to)); - h.run_steps(2); - primary(h, to, false); - } - - fn corner_click(h: &mut Harness<'_, DesignApp>, p: Pos2) { - h.hover_at(p); - h.step(); - primary(h, p, true); - primary(h, p, false); - } - - /// Where the rulers measure from (canvas coordinates): the document's zero point on the - /// spread in view (its first page, for a page origin). - fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option { - ruler_pieces(app, doc, layout, doc.zero_point()).first().map(|p| p.2) - } - - fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] { - h.state().session.doc().unwrap().doc.settings.zero_point - } - - #[test] - fn the_ruler_corner_drags_resets_and_locks_the_zero_point() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 3})).unwrap(); - let mut h = fast_harness(app); - let rect = h.state().canvas_rect.unwrap(); - let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0); - // A click that stays in the corner leaves the zero point. - corner_click(&mut h, corner); - assert_eq!(zero_point(&h), [0.0, 0.0]); - // Dragged out, it lands where released, measured from the spread in view. - let dest = rect.min + vec2(80.0, 50.0); - let expected = { - let app = h.state(); - let st = app.session.active().unwrap(); - let layout = CanvasLayout::new(&st.doc, false); - let slot = layout.slots[current_slot(app, &layout).unwrap()]; - let sp = slot.to_spread(Xf::new(rect, app.view().unwrap()).to_canvas(dest)); - let b = st.doc.spread(slot.spread).unwrap().bounds(); - [sp.x - b.x0, sp.y - b.y0] - }; - corner_drag(&mut h, corner, dest); - let zp = zero_point(&h); - assert!((zp[0] - expected[0]).abs() < 0.5 && (zp[1] - expected[1]).abs() < 0.5, "{zp:?} vs {expected:?}"); - assert!(zp[0].abs() > 1.0 && zp[1].abs() > 1.0, "moved: {zp:?}"); - // The rulers measure from the point it was dropped on. - { - let app = h.state(); - let st = app.session.active().unwrap(); - let layout = CanvasLayout::new(&st.doc, false); - let o = ruler_zero(app, &st.doc, &layout).unwrap(); - let on_screen = Xf::new(rect, app.view().unwrap()).to_screen(o); - assert!((on_screen - dest).length() < 0.5, "{on_screen:?} vs {dest:?}"); - } - // A double-click resets it. - corner_click(&mut h, corner); - corner_click(&mut h, corner); - assert_eq!(zero_point(&h), [0.0, 0.0]); - // Locked from the corner's context menu, the corner ignores drags and double-clicks. - right_click(&mut h, corner); - h.get_by_label(" Lock Zero Point").click(); - h.run_steps(3); - assert!(h.state().session.doc().unwrap().doc.settings.zero_point_locked); - corner_drag(&mut h, corner, dest); - assert_eq!(zero_point(&h), [0.0, 0.0]); - // Unlocked again from the same menu. - right_click(&mut h, corner); - h.get_by_label(" Unlock Zero Point").click(); - h.run_steps(3); - corner_drag(&mut h, corner, dest); - assert_ne!(zero_point(&h), [0.0, 0.0]); - h.state_mut().run("view.lockZeroPoint", json!({"on": true})).unwrap(); - corner_click(&mut h, corner); - corner_click(&mut h, corner); - assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset"); - } - - #[test] - fn cmd_dragging_the_ruler_corner_makes_a_guide_each_way() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let mut h = harness(app); - let rect = h.state().canvas_rect.unwrap(); - let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0); - let dest = rect.min + vec2(120.0, 90.0); - let (r, at) = { - let app = h.state(); - let st = app.session.active().unwrap(); - CanvasLayout::new(&st.doc, false).spread_at(Xf::new(rect, app.view().unwrap()).to_canvas(dest)).unwrap() - }; - h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND)); - h.step(); - corner_drag(&mut h, corner, dest); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); - h.step(); - let doc = h.state().session.doc().unwrap().doc.clone(); - let guides: Vec<_> = doc.spread(r).unwrap().pages.iter().flat_map(|p| p.guides.clone()).collect(); - assert_eq!(guides.len(), 2, "{guides:?}"); - let pos = |o: designcraft_doc::Orientation| guides.iter().find(|g| g.orientation == o).map(|g| g.position).unwrap(); - assert!((pos(designcraft_doc::Orientation::Horizontal) - at.y).abs() < 0.5); - assert!((pos(designcraft_doc::Orientation::Vertical) - at.x).abs() < 0.5); - assert!(guides.iter().all(|g| g.spread)); - assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays"); - } - - /// A guide being dragged out of a ruler says where it is, as the rulers measure it (#1282): - /// from the zero point, in the ruler units, and the label follows the pointer while it moves. - #[test] - fn a_dragged_guide_shows_where_it_is() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); - let mut h = harness(app); - let rect = h.state().canvas_rect.unwrap(); - let dest = rect.min + vec2(160.0, 110.0); - let (xf, at) = { - let app = h.state(); - let xf = Xf::new(rect, app.view().unwrap()); - let st = app.session.active().unwrap(); - (xf, CanvasLayout::new(&st.doc, false).spread_at(xf.to_canvas(dest)).unwrap().1) - }; - let units = h.state().session.doc().unwrap().doc.settings.horizontal_units; - for (orientation, label, want) in - [(designcraft_doc::Orientation::Vertical, "X", at.x - 100.0), (designcraft_doc::Orientation::Horizontal, "Y", at.y - 50.0)] - { - let g = GuideDrag { orientation, from: None, at: Some(dest), mods: egui::Modifiers::NONE }; - let (l, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); - assert_eq!(l, label); - assert!((v - want).abs() < 1e-6, "{label}: {v} vs {want}"); - let text = guide_readout(h.state(), &xf, &g).unwrap(); - assert_eq!(text, format!("{label}: {}", designcraft_geom::units::format_measure(v, units))); - } - // While a guide is actually being dragged out of the top ruler, the readout is there. - let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0); - h.hover_at(ruler); - h.step(); - primary(&mut h, ruler, true); - h.event(egui::Event::PointerMoved(dest)); - h.run_steps(2); - let g = h.ctx.data(|d| d.get_temp::(egui::Id::unique(GUIDE_DRAG))).expect("dragging"); - assert_eq!(g.orientation, designcraft_doc::Orientation::Horizontal); - assert!(guide_readout(h.state(), &xf, &g).is_some_and(|t| t.starts_with("Y: "))); - primary(&mut h, dest, false); - } - - /// Over a spread other than the one in the middle of the view, the readout measures that - /// spread, the one the guide is dropped on: it reads the position the guide gets. - #[test] - fn the_guide_readout_measures_the_spread_under_the_pointer() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 5})).unwrap(); - app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); - let h = harness(app); - let rect = h.state().canvas_rect.unwrap(); - let xf = Xf::new(rect, h.state().view().unwrap()); - let st = h.state().session.active().unwrap(); - let layout = CanvasLayout::new(&st.doc, false); - let current = current_slot(h.state(), &layout).unwrap(); - // A point inside the last spread, well away from the one in view. - let last = layout.slots.last().unwrap(); - assert_ne!(layout.slots.iter().position(|s| s.spread == last.spread), Some(current), "the last spread isn't the one in view"); - let inside = Point::new(last.bounds.center().x, last.bounds.y0 + (last.bounds.y1 - last.bounds.y0) * 0.3); - let (r, sp) = layout.spread_at(inside).unwrap(); - assert_eq!(r, last.spread); - let g = GuideDrag { - orientation: designcraft_doc::Orientation::Horizontal, - from: None, - at: Some(xf.to_screen(inside)), - mods: egui::Modifiers::NONE, - }; - let (label, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); - assert_eq!(label, "Y"); - // The guide would be stored at `sp.y` on that spread, which its ruler reads from the zero point. - // (To screen and back in f32: a few hundred-thousandths of a point.) - assert!((v - (sp.y - 50.0)).abs() < 1e-3, "{v} vs {}", sp.y - 50.0); - // An existing guide of another spread can't be dropped there (it only moves on its own - // spread): no readout over this one, a readout over its own. - let first = layout.slots[current].spread; - let moving = GuideDrag { - orientation: designcraft_doc::Orientation::Horizontal, - from: Some((first, 0, 0)), - at: Some(xf.to_screen(inside)), - mods: egui::Modifiers::NONE, - }; - assert!(guide_measure(h.state(), &xf, &moving).is_none(), "an existing guide over another spread"); - let own = layout.slots[current].bounds; - let over_own = Point::new(own.center().x, own.y0 + (own.y1 - own.y0) * 0.3); - let moving_here = GuideDrag { at: Some(xf.to_screen(over_own)), ..moving }; - assert!(guide_measure(h.state(), &xf, &moving_here).is_some(), "over its own spread"); - } - - /// The guide readout stays on the canvas: below right of the pointer in the open, flipped - /// left or up near the right or bottom edge, and inside the canvas in every corner. - #[test] - fn the_guide_readout_stays_inside_the_canvas() { - let area = Rect::from_min_max(pos2(50.0, 40.0), pos2(850.0, 640.0)); - let size = vec2(80.0, 14.0); - let inside = |at: Pos2| { - let r = Rect::from_min_size(at, size).expand(3.0); - r.min.x >= area.min.x - 1e-3 && r.min.y >= area.min.y - 1e-3 && r.max.x <= area.max.x + 1e-3 && r.max.y <= area.max.y + 1e-3 - }; - assert_eq!(readout_at(pos2(400.0, 300.0), size, area), pos2(412.0, 312.0), "in the open: below right"); - let right = readout_at(pos2(845.0, 300.0), size, area); - assert!(right.x + size.x < 845.0 && inside(right), "near the right edge: left of the pointer, {right:?}"); - let bottom = readout_at(pos2(400.0, 636.0), size, area); - assert!(bottom.y + size.y < 636.0 && inside(bottom), "near the bottom: above it, {bottom:?}"); - for p in [area.min, pos2(area.max.x, area.min.y), area.max, pos2(area.min.x, area.max.y), pos2(-500.0, 2000.0)] { - assert!(inside(readout_at(p, size, area)), "{p:?}"); - } - // A canvas narrower than the label: pinned to its top left, not past it. - let tiny = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 10.0)); - assert_eq!(readout_at(pos2(20.0, 5.0), size, tiny), pos2(3.0, 3.0)); - } - - #[test] - fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - // Spread 0: page 1; spread 1: pages 2 and 3. - app.run("file.new", json!({"pages": 3})).unwrap(); - app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); - app.session.prefs.dimensions_include_stroke = false; - let mut h = harness(app); - let rect = h.state().canvas_rect.unwrap(); - for (spread, x0) in [(0usize, 136.0), (1, 736.0)] { - let app = h.state_mut(); - let id = app.run("frame.create", json!({"spread": spread, "rect": [x0, 70, x0 + 50.0, 120]})).unwrap()["id"].clone(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - // X/Y (Control, Properties and Info panels). - let r = crate::panels::sel_info(app).unwrap().page_rect; - assert!((r.x0 - (x0 - 100.0)).abs() < 1e-6 && (r.y0 - 20.0).abs() < 1e-6, "spread {spread}: {r:?}"); - // The rulers, with that spread in view. - let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); - let slot = layout.slots[spread]; - let v = app.view_mut().unwrap(); - let zoom = v.zoom; - let c = slot.bounds.center(); - v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / zoom, c.y - rect.height() as f64 / 2.0 / zoom); - h.run_steps(2); - let app = h.state(); - let doc = app.session.active().unwrap().doc.clone(); - assert_eq!(current_slot(app, &layout), Some(spread)); - let o = ruler_zero(app, &doc, &layout).unwrap(); - assert!((o.x - slot.bounds.x0 - 100.0).abs() < 1e-6 && (o.y - slot.bounds.y0 - 50.0).abs() < 1e-6, "spread {spread}: {o:?}"); - } - } - - /// Screen position of spread 0's point (x, y). - fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 { - let app = h.state(); - let st = app.session.active().unwrap(); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y)) - } - - /// A menu row: a button that isn't a toggle, named by its label, then its shortcut if it has - /// one. Toggle buttons with the same name (the Task Bar's icons) don't match, nor do buttons - /// right of the canvas (the Properties panel's Arrange). - fn menu_row<'h>(h: &'h Harness<'_, DesignApp>, label: &'h str) -> Option> { - let right = f64::from(h.state().canvas_rect.map_or(f32::INFINITY, |r| r.max.x)); - h.query_by(move |n| { - n.role() == egui::accesskit::Role::Button - && n.toggled().is_none() - && n.bounding_box().is_none_or(|b| b.x0 < right) - && n.label().is_some_and(|l| l == label || l.strip_prefix(label).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.contains(' '))) - }) - } - - fn enabled(h: &Harness<'_, DesignApp>, label: &str) -> bool { - use egui_kittest::kittest::NodeT; - !menu_row(h, label).unwrap_or_else(|| panic!("no menu row {label}")).accesskit_node().is_disabled() - } - - fn spread_items(h: &Harness<'_, DesignApp>) -> Vec { - h.state().session.doc().unwrap().doc.spreads[0].items.iter().map(|i| i.id.0).collect() - } - - fn selected(h: &Harness<'_, DesignApp>) -> Vec { - h.state().session.doc().unwrap().selection.items.iter().map(|i| i.0).collect() - } - - #[test] - fn right_clicking_an_object_selects_it_and_its_menu_arranges_it() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - let b = app.run("frame.create", json!({"rect": [150, 150, 300, 300]})).unwrap()["id"].as_u64().unwrap(); - let mut h = harness(app); - assert_eq!(selected(&h), [b]); - let on_a = screen_of(&h, 60.0, 60.0); - right_click(&mut h, on_a); - assert_eq!(selected(&h), [a], "the object under the pointer is selected first"); - // An empty frame's menu: Content, but no Fitting (nothing to fit) and no text frame entries. - assert!(menu_row(&h, "Content").is_some()); - assert!(menu_row(&h, "Fitting").is_none() && menu_row(&h, "Text Frame Options…").is_none()); - // Paste is available with nothing copied here: the system clipboard may hold another app's text. - assert!(enabled(&h, "Copy") && enabled(&h, "Paste")); - menu_row(&h, "Arrange").unwrap().click(); - h.run_steps(3); - menu_row(&h, "Bring to Front").unwrap().click(); - h.run_steps(3); - assert_eq!(spread_items(&h), [b, a]); - assert!(menu_row(&h, "Arrange").is_none(), "choosing an entry closes the menu"); - } - - #[test] - fn right_clicking_empty_canvas_offers_paste_after_a_copy() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - app.run("edit.copy", json!({})).unwrap(); - app.select_tool("rectangleFrame"); - let mut h = harness(app); - let empty = screen_of(&h, 400.0, 500.0); - right_click(&mut h, empty); - assert_eq!(selected(&h), [a], "a right-click on nothing keeps the selection"); - assert!(menu_row(&h, "Arrange").is_none(), "the page menu, not the object menu"); - assert!(enabled(&h, "Paste in Place")); - assert!(menu_row(&h, "✓ Show/Hide Rulers").is_some(), "toggles show their state"); - // Escape closes the menu and does nothing else: the tool would deselect, the shortcuts - // would switch to the Selection tool. - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(menu_row(&h, "Paste in Place").is_none()); - assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a])); - right_click(&mut h, empty); - menu_row(&h, "Paste").unwrap().click(); - h.run_steps(3); - assert_eq!(spread_items(&h).len(), 2); - } - - #[test] - fn right_clicking_another_object_while_the_menu_is_open_reopens_it_there() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - let b = app.run("frame.create", json!({"rect": [36, 600, 200, 760]})).unwrap()["id"].as_u64().unwrap(); - let mut h = harness(app); - // The menu opens down from A, with the pointer on its first row (no submenu open); B is below it. - let (on_a, on_b) = (screen_of(&h, 60.0, 60.0), screen_of(&h, 50.0, 700.0)); - right_click(&mut h, on_a); - assert_eq!(selected(&h), [a]); - assert!(menu_row(&h, "Arrange").is_some()); - right_click(&mut h, on_b); - assert_eq!(selected(&h), [b]); - assert!(menu_row(&h, "Arrange").is_some(), "the menu reopens at the new click"); - } - - #[test] - fn a_context_menu_in_one_pane_keeps_the_keys_from_the_other() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap(); - app.select_tool("rectangleFrame"); - app.split = true; - let mut h = harness(app); - // The focused pane is the left one; this point is near its right edge, away from the frame. - let left = h.state().canvas_rect.unwrap(); - right_click(&mut h, pos2(left.max.x - 40.0, left.center().y)); - assert!(menu_row(&h, "Paste in Place").is_some()); - // Escape closes the left pane's menu before the right pane handles the keys. - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(menu_row(&h, "Paste in Place").is_none()); - assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a])); - } - - #[test] - fn right_clicking_text_keeps_the_selected_text_or_places_the_caret() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 400, 200], "content": "text"})).unwrap(); - app.select_tool("type"); - app.run("text.insert", json!({"text": "Hello world"})).unwrap(); - let sid = *app.session.doc().unwrap().doc.stories.keys().next().unwrap(); - app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap(); - let mut h = harness(app); - let text_sel = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.as_ref().map(|t| (t.anchor, t.focus)); - // Inside "Hello": the selection stays. - let inside = screen_of(&h, 45.0, 44.0); - right_click(&mut h, inside); - assert_eq!(text_sel(&h), Some((0, 5))); - assert!(menu_row(&h, "Paste without Formatting").is_some(), "the text menu"); - h.key_press(egui::Key::Escape); - h.run_steps(3); - // Past the end of the line: the caret goes there. - let past_end = screen_of(&h, 300.0, 44.0); - right_click(&mut h, past_end); - assert_eq!(text_sel(&h), Some((11, 11))); - assert!(menu_row(&h, "Paste without Formatting").is_some()); - } - - #[test] - fn rows_hidden_in_the_menu_bar_are_hidden_in_context_menus() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap(); - app.ui.hidden_menu_items.push(crate::menus::menu_key("Object/Arrange", "Bring to Front")); - let mut h = harness(app); - let on_frame = screen_of(&h, 60.0, 60.0); - right_click(&mut h, on_frame); - menu_row(&h, "Arrange").unwrap().click(); - h.run_steps(3); - assert!(menu_row(&h, "Bring to Front").is_none()); - assert!(menu_row(&h, "Send to Back").is_some()); - assert!(h.query_by_label("Show All Menu Items").is_some()); - } - - #[test] - fn a_secondary_drag_neither_moves_marquees_nor_draws() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - let mut h = harness(app); - // A secondary-button drag between spread points. - let drag = |h: &mut Harness<'_, DesignApp>, from: (f64, f64), to: (f64, f64)| { - let (from, to) = (screen_of(h, from.0, from.1), screen_of(h, to.0, to.1)); - h.hover_at(from); - h.step(); - h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); - h.step(); - for t in [0.25, 0.5, 0.75, 1.0] { - h.event(egui::Event::PointerMoved(from + (to - from) * t)); - h.step(); - } - h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); - h.run_steps(3); - }; - let xf = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.item(designcraft_doc::ItemId(a)).unwrap().xf; - let before = xf(&h); - // Selection tool: on the object (no move), and from empty page across it (no marquee). - drag(&mut h, (100.0, 100.0), (300.0, 300.0)); - assert_eq!(xf(&h), before); - h.state_mut().run("edit.deselectAll", json!({})).unwrap(); - drag(&mut h, (400.0, 400.0), (20.0, 20.0)); - assert!(selected(&h).is_empty()); - // Rectangle Frame tool: no frame. - h.state_mut().select_tool("rectangleFrame"); - drag(&mut h, (300.0, 300.0), (500.0, 500.0)); - assert_eq!(spread_items(&h), [a]); - } - - /// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a - /// row must land within the double-click delay). - fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let r = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": text})).unwrap(); - let id = r["id"].as_u64().unwrap(); - app.run("tool.select", json!({"tool": "type"})).unwrap(); - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(4); - (h, id) - } - - /// The screen point over the first line of frame `id` where a click puts the caret at a byte - /// in `bytes`. - fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range) -> Pos2 { - let mut x = 74.0; - let p = loop { - assert!(x < 400.0, "no point on the first line hits {bytes:?}"); - h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap(); - if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) { - break Point::new(x, 80.0); - } - x += 1.0; - }; - h.state_mut().run("edit.deselectAll", json!({})).unwrap(); - let app = h.state(); - let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p); - Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c) - } - - fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) { - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - h.step(); - } - } - - fn selected_range(h: &Harness<'_, DesignApp>) -> std::ops::Range { - h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default() - } - - #[test] - fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() { - let text = "One two. Three four! Five six.\nSecond para here."; - let (mut h, id) = typing(text); - // Inside "Three": double-click selects the word, then line and paragraph with return. - let p = screen_at(&mut h, id, 10..14); - h.hover_at(p); - h.step(); - let mut got = vec![]; - for _ in 0..5 { - click(&mut h, p); - let r = selected_range(&h); - got.push(text[r].to_string()); - } - assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}"); - assert!(got[0].is_empty(), "one click places the caret: {got:?}"); - } - - #[test] - fn esc_that_closes_a_dialog_keeps_the_type_tool_and_its_text_selection() { - let (mut h, id) = typing("One two three"); - // A click in the text gives the canvas the keyboard focus, as when typing. - let p = screen_at(&mut h, id, 5..6); - h.hover_at(p); - h.step(); - for _ in 0..2 { - click(&mut h, p); - } - h.run_steps(4); - let words = selected_range(&h); - assert_eq!(words, 4..7, "the double-click selects \"two\""); - let app = h.state_mut(); - let name = app.run("style.character.create", json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); - app.ui.dialog = Some(crate::dialogs::Dialog::new("characterStyleOptions", json!({"name": name}))); - h.run_steps(3); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(h.state().ui.dialog.is_none(), "Esc closes the dialog"); - assert_eq!((h.state().session.tool_id(), selected_range(&h)), ("type", words)); - // With no dialog open, Esc in the text still leaves it for the Selection tool. - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(h.state().session.tool_id(), "selection"); - } - - #[test] - fn slow_clicks_do_not_add_up() { - let (mut h, id) = typing("One two. Three four!"); - let p = screen_at(&mut h, id, 10..14); - h.hover_at(p); - h.step(); - for _ in 0..3 { - click(&mut h, p); - h.run_steps(30); - } - assert!(selected_range(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected_range(&h)); - } - - /// A viewport wider than the GPU's largest texture: the canvas texture is sampled down, and an - /// edit repaints it whole. A region repainted in view pixels would land in the wrong place, - /// or outside the texture (a wgpu validation error). A view that fits is still patched. - #[test] - fn an_edit_repaints_a_canvas_texture_sampled_down_to_the_gpu_limit_whole() { - for (width, sampled_down) in [(1440.0, false), (2600.0, true)] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let frame = app.run("frame.create", json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Text"})).unwrap(); - let mut h = Harness::builder().with_size(vec2(width, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(6); - let limit = h.ctx.input(|i| i.max_texture_side); - let size = h.state().canvas.texture.as_ref().map(|t| t.size()).unwrap(); - assert!(size[0] <= limit && size[1] <= limit, "{size:?}"); - let shown = h.state().canvas.shown.unwrap().size; - assert_eq!(shown.0 > limit as f32, sampled_down, "view {shown:?}, limit {limit}"); - let patches = h.state().canvas.patches; - // A small edit: one more character in the frame. - h.state_mut().run("text.insert", json!({"story": frame["story"], "at": 4, "text": "s"})).unwrap(); - h.run_steps(6); - assert_eq!(h.state().canvas.patches == patches, sampled_down, "width {width}"); - assert_eq!(h.state().canvas.texture.as_ref().map(|t| t.size()), Some(size)); - } - } - - /// ⌥E then I types "í" on a Mac: the input method composes the dead key's accent, which - /// it does only for a window that turned it on. The canvas never did, so ⌥E typed "e". - #[test] - fn dead_keys_compose_through_the_input_method() { - let (mut h, id) = typing("T"); - h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [390.0, 80.0]})).unwrap(); - h.run_steps(2); - assert!(h.output().platform_output.ime.is_some(), "a text caret turns the input method on"); - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "´".into(), active_range_chars: None })); - h.run_steps(2); - let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.stories.values().map(|s| s.text.clone()).collect::(); - assert_eq!(text(&h), "T´", "the accent being composed shows in the story"); - assert!(h.state().session.tool_composing(), "and is marked as composed, not typed"); - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None })); - h.event(egui::Event::Ime(egui::ImeEvent::Commit("í".into()))); - h.run_steps(2); - assert_eq!(text(&h), "Tí"); - assert!(!h.state().session.tool_composing()); - // Moving the caret mid-composition keeps the accent as typed and tells the input method - // to drop its copy. - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "˜".into(), active_range_chars: None })); - h.run_steps(2); - h.state_mut().run("text.move", json!({"dir": "left"})).unwrap(); - h.step(); - assert_eq!(text(&h), "Tí˜"); - assert!(!h.state().session.tool_composing()); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|i| i.should_interrupt_composition)); - assert!(h.state_mut().take_ime_discard()); - // Another tool takes no text: the input method is off. - h.state_mut().run("tool.select", json!({"tool": "selection"})).unwrap(); - h.run_steps(2); - assert!(h.output().platform_output.ime.is_none()); - } - - #[test] - fn tools_show_their_own_cursors_over_the_page() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let mut h = harness(app); - let p = h.state().canvas_rect.unwrap().center(); - let mut shown = |tool: &str| { - h.state_mut().run("tool.select", json!({"tool": tool})).unwrap(); - h.hover_at(p); - h.run_steps(2); - let out = &h.output().platform_output; - (out.cursor_icon, out.cursor_image.clone()) - }; - let (pen, direct, text, selection) = (shown("pen"), shown("directSelection"), shown("type"), shown("selection")); - let ppp = h.ctx.pixels_per_point(); - let images = &mut h.state_mut().cursors; - match crate::cursors::mode() { - crate::cursors::Mode::Os => { - assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen"); - assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection"); - assert_eq!(selection.1, images.get(Cursor::Arrow, ppp), "Selection"); - assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor"); - } - crate::cursors::Mode::Painted => { - assert_eq!((pen.0, direct.0, selection.0), (egui::CursorIcon::None, egui::CursorIcon::None, egui::CursorIcon::None)); - } - crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)), - } - } - - #[test] - fn document_grid_is_drawn_where_points_snap_to_it() { - use designcraft_tools::{SnapView, ToolContext}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - let layout = CanvasLayout::new(&doc, false); - let sr = SpreadRef::Doc(0); - // Where the grid snaps a point in the first page (72 pt / 8 subdivisions = 9 pt). - let page = doc.spreads[0].pages[0].bounds(); - let sel = Selection::default(); - let cx = ToolContext { - doc: &doc, - selection: &sel, - cache: &app.session.cache, - layout: &layout, - zoom: 1.0, - layer: doc.layers[0].id, - snap: SnapView { snap_to_document_grid: true, zone_px: 20.0, ..SnapView::OFF }, - unit: Unit::Points, - stroke_in_front: false, - }; - let (snapped, _) = designcraft_tools::snap::snap_point(&cx, sr, Point::new(page.x0 + 31.3, page.y0 + 47.9)); - assert_eq!((snapped.x - page.x0, snapped.y - page.y0), (27.0, 45.0)); - // Render 40 × 40 pt around it at 4 px/pt. - let scale = 4.0; - let corner = layout.xf(sr) * Point::new(snapped.x - 20.0, snapped.y - 20.0); - let view = Affine::scale(scale) * Affine::translate((-corner.x, -corner.y)); - let placed: Vec<_> = layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect(); - let render = |app: &DesignApp| { - let opts = screen_options(app, &layout, false, 1.0); - designcraft_render::Renderer::new().render(&doc, &app.session.cache, &placed, 160, 160, view, &opts) - }; - // The snapped point is at pixel (80, 80); halfway to the next line is 18 px further. - let darkest = |img: &designcraft_render::Rendered, xs: [u32; 2], ys: [u32; 2]| { - (xs[0]..xs[1]).flat_map(|x| (ys[0]..ys[1]).map(move |y| (x, y))).map(|(x, y)| img.pixel(x, y)[0]).min().unwrap() - }; - let off = render(&app); - assert_eq!(darkest(&off, [78, 82], [60, 64]), 255, "no grid while it is hidden"); - app.run("view.documentGrid", json!({})).unwrap(); - let on = render(&app); - assert!(darkest(&on, [79, 81], [60, 64]) < 250, "a vertical line at the snapped x"); - assert!(darkest(&on, [60, 64], [79, 81]) < 250, "a horizontal line at the snapped y"); - assert_eq!(darkest(&on, [96, 100], [96, 100]), 255, "nothing between lines"); - // Preview hides it. - app.ui.screen_mode = ScreenMode::Preview; - assert!(screen_options(&app, &layout, true, 1.0).document_grid.is_empty()); - } - - /// egui moves keyboard focus on a plain arrow key or Tab, and Space/Return then clicks the - /// focused widget (e.g. the status bar's spread buttons) while typing still reaches the text. - #[test] - fn arrow_keys_and_tab_keep_keyboard_focus_on_the_canvas() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 3})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap(); - app.select_tool("type"); - let mut h = harness(app); - let p = { - let app = h.state(); - let st = app.session.active().unwrap(); - let layout = CanvasLayout::new(&st.doc, st.editing_parents); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(100.0, 60.0)) - }; - h.hover_at(p); - h.step(); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - h.step(); - } - h.run_steps(2); - let focus = h.ctx.memory(|m| m.focused()); - assert!(focus.is_some(), "a click on the canvas takes keyboard focus"); - let view = *h.state().view().unwrap(); - for key in [egui::Key::ArrowDown, egui::Key::Space, egui::Key::ArrowRight, egui::Key::Enter, egui::Key::Tab, egui::Key::Escape] { - h.key_press(key); - if key == egui::Key::Space { - h.event(egui::Event::Text(" ".into())); - } - h.run_steps(2); - assert_eq!(h.ctx.memory(|m| m.focused()), focus, "{key:?} keeps keyboard focus on the canvas"); - } - let v = *h.state().view().unwrap(); - assert_eq!((v.origin, v.zoom), (view.origin, view.zoom), "the view stays where it was"); - let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone(); - assert_eq!(text, "Hello \n\t", "Space, Return and Tab reach the text"); - } - - #[test] - fn rulers_open_no_units_menu_without_a_document() { - let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default())); - let Some(rect) = h.state().canvas_rect else { return }; - right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); - assert!(h.query_by_label(" Points").is_none()); - } - - /// One frame of the whole app with `events`; returns what it asks of the system IME. - fn ime_frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec) -> Option { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - app.logic(ui.ctx()); - app.ui(ui); - }); - out.textures_delta.clear(); - out.platform_output.ime - } - - /// An edit patches the canvas texture in place only while that texture is at full resolution: - /// past the GPU's texture limit `upload` shrinks it, and a full-resolution patch written into - /// it is a renderer validation error. - #[test] - fn edits_patch_the_canvas_only_at_full_resolution() { - for (max_side, patches) in [(None, true), (Some(1024), false)] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let frame = |app: &mut DesignApp| { - // Wider than the limit (egui's font atlas needs at least 1024). - let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1900.0, 900.0))), ..Default::default() }; - if let Some(m) = max_side { - raw.max_texture_side = Some(m); - } - let mut out = ctx.run_ui(raw, |ui| { - app.logic(ui.ctx()); - app.ui(ui); - }); - out.textures_delta.clear(); - }; - app.run("file.new", json!({})).unwrap(); - for _ in 0..3 { - frame(&mut app); - } - app.run("frame.create", json!({"rect": [36, 36, 60, 60]})).unwrap(); - frame(&mut app); - let size = app.canvas.texture.as_ref().unwrap().size(); - assert!(max_side.is_none_or(|m| size[0] <= m && size[1] <= m), "{size:?}"); - assert_eq!(app.canvas.patches > 0, patches, "limit {max_side:?}"); - } - } - - /// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames - /// drawn; returns the story id. - fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value { - app.run("file.new", json!({})).unwrap(); - let f = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": text})).unwrap(); - let sid = f["story"].clone(); - app.session.execute("text.select", &json!({"story": sid, "anchor": text.len(), "focus": text.len()})).unwrap(); - app.select_tool("type"); - for _ in 0..4 { - ime_frame(app, ctx, vec![]); - } - sid - } - - fn story_text(app: &mut DesignApp, sid: &Value) -> String { - app.session.execute("story.get", &json!({"story": sid})).unwrap()["text"].as_str().unwrap().to_string() - } - - /// Spread point `p` on screen. - fn on_screen(app: &DesignApp, p: Point) -> Pos2 { - let st = app.session.active().unwrap(); - let c = CanvasLayout::new(&st.doc, st.editing_parents).to_canvas(SpreadRef::Doc(0), p); - Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c) - } - - fn preedit(t: &str, c: usize) -> egui::Event { - egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) }) - } - - /// Extract `(surrounding text, cursor, anchor)` from an IME output. - fn ime_payload(ime: &egui::output::IMEOutput) -> Option<(&str, usize, usize)> { - ime.surrounding_text.available().map(|p| (p.text.as_str(), p.cursor, p.anchor)) - } - - /// Set an engine text selection for a test fixture. - fn text_selection(app: &mut DesignApp, sid: &Value, anchor: usize, focus: usize) { - app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": focus})).unwrap(); - } - - struct NativeClickFixture { - app: DesignApp, - ctx: egui::Context, - target: Value, - old: Value, - at: Pos2, - focus: usize, - } - - /// Build the old and target stories, measure an interior target caret, and leave the old story selected before the click. - fn native_gui_click_fixture() -> NativeClickFixture { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let old = typing_app(&mut app, &ctx, "Old story"); - let frame = app.run("frame.create", json!({"rect": [36, 280, 300, 400], "content": "text", "text": "Target story"})).unwrap(); - let target = frame["story"].clone(); - // Measure an interior first-word caret through the engine, rather than guessing a - // font-dependent screen pixel or clicking the frame's resize border. - let (point, focus) = (50..180) - .find_map(|x| { - app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap(); - let sel = app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!(sel.story.0, target.as_u64().unwrap()); - (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus)) - }) - .expect("an interior point in the target's first word"); - text_selection(&mut app, &old, "Old story".len(), "Old story".len()); - for _ in 0..4 { - ime_frame(&mut app, &ctx, vec![]); - } - let at = on_screen(&app, point); - assert!(app.canvas_rect.unwrap().contains(at)); - ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); - assert_eq!(app.session.doc().unwrap().selection.text.unwrap().story.0, old.as_u64().unwrap()); - NativeClickFixture { app, ctx, target, old, at, focus } - } - - /// Build a primary pointer press or release event at a position. - fn native_gui_button(pos: Pos2, pressed: bool) -> egui::Event { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } - } - - /// The 37-byte Devanagari line the native run had in the previous story. - const NATIVE_GUI_OLD_DEVANAGARI: &str = "नमस्ते दुनिया"; - - /// The click fixture with the non-empty selection in the previous story that the native - /// Windows run had (37-byte Devanagari, 0..37). A non-empty selection shows the contextual - /// task bar; keep it present but clear of the target click. - fn native_gui_selected_old_click_fixture() -> NativeClickFixture { - let mut f = native_gui_click_fixture(); - text_selection(&mut f.app, &f.old, 0, "Old story".len()); - f.app.run("text.insert", json!({"text": NATIVE_GUI_OLD_DEVANAGARI})).unwrap(); - text_selection(&mut f.app, &f.old, 0, NATIVE_GUI_OLD_DEVANAGARI.len()); - for _ in 0..4 { - ime_frame(&mut f.app, &f.ctx, vec![]); - } - let sel = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((sel.story.0, sel.anchor, sel.focus), (f.old.as_u64().unwrap(), 0, NATIVE_GUI_OLD_DEVANAGARI.len())); - assert_eq!(NATIVE_GUI_OLD_DEVANAGARI.len(), 37, "the native fixture's Devanagari line was 37 UTF-8 bytes"); - assert!(!sel.is_caret(), "the previous story's selection is non-empty"); - assert!(!context_menu_open(&f.ctx), "no context menu owns this frame's keys"); - assert!(f.app.ui.dialog.is_none() && f.app.ui.palette.is_none(), "no modal owns the keyboard"); - assert!(!f.ctx.text_edit_focused(), "no text field owns the keyboard"); - assert_eq!(f.app.pane, f.app.focus_pane, "the canvas pane takes the keyboard"); - let task_bar = egui::Id::unique(("task_bar", f.ctx.viewport_id(), f.app.pane)); - let bar = f.ctx.memory(|m| m.area_rect(task_bar)).expect("the old selection shows the floating task bar"); - assert!(!bar.contains(f.at), "the floating task bar does not cover the target click at {bar:?}"); - f - } - - /// Run one raw event batch, optionally force a discarded pass, and return the pointer edges observed by each pass. - fn native_gui_input(f: &mut NativeClickFixture, events: Vec, discard: bool) -> Vec<(bool, bool, bool)> { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() }; - let mut edges = Vec::new(); - let mut out = f.ctx.run_ui(raw, |ui| { - edges.push(ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.press_origin().is_some()))); - f.app.logic(ui.ctx()); - f.app.ui(ui); - if discard && edges.len() == 1 { - ui.ctx().request_discard("native same-batch click exactly-once regression"); - } - }); - if discard { - assert_eq!(out.platform_output.num_completed_passes, 2, "the requested discarded pass actually ran"); - } - out.textures_delta.clear(); - edges - } - - /// Assert that the primary button, canvas press state and tool gesture are all released. - fn native_gui_released(f: &NativeClickFixture) { - assert!(!f.ctx.input(|i| i.pointer.primary_down()), "the native primary button is up"); - let down = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap_or(false); - assert!(!down, "the canvas retained a released pointer"); - assert!(!f.app.session.tool_busy(), "a released click must not leave a tool gesture"); - } - - /// Create an independently measured second-story caret farther apart than the double-click distance. - fn native_gui_second_click_target(f: &mut NativeClickFixture) -> (Value, Pos2, usize) { - let frame = f.app.run("frame.create", json!({"rect": [330, 280, 575, 400], "content": "text", "text": "Second story"})).unwrap(); - let story = frame["story"].clone(); - let (point, focus) = (345..465) - .find_map(|x| { - f.app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap(); - let sel = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!(sel.story.0, story.as_u64().unwrap()); - (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus)) - }) - .expect("an independently measured interior caret in the second story"); - text_selection(&mut f.app, &f.old, "Old story".len(), "Old story".len()); - for _ in 0..4 { - ime_frame(&mut f.app, &f.ctx, vec![]); - } - let at = on_screen(&f.app, point); - assert!(f.app.canvas_rect.unwrap().contains(f.at)); - assert!(f.app.canvas_rect.unwrap().contains(at)); - let max_click_dist = f.ctx.options(|o| o.input_options.max_click_dist); - assert!((at - f.at).length() > max_click_dist, "the two target presses must not form a double click"); - (story, at, focus) - } - - /// Two completed clicks in one batch use the last press once, emit one caret/release pair, add no history, and type at the final caret. - #[test] - fn native_gui_two_completed_clicks_use_last_primary_press_once() { - for reverse in [false, true] { - for discard in [false, true] { - let mut f = native_gui_click_fixture(); - let (second, second_at, second_focus) = native_gui_second_click_target(&mut f); - let (first_at, last_at, final_story, final_focus) = - if reverse { (second_at, f.at, f.target.clone(), f.focus) } else { (f.at, second_at, second.clone(), second_focus) }; - let initial = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((initial.story.0, initial.anchor, initial.focus), (f.old.as_u64().unwrap(), "Old story".len(), "Old story".len())); - let undo = f.app.session.doc().unwrap().history.undo.len(); - let journal = f.app.session.journal.len(); - let edges = native_gui_input( - &mut f, - vec![ - egui::Event::PointerMoved(first_at), - native_gui_button(first_at, true), - native_gui_button(first_at, false), - egui::Event::PointerMoved(last_at), - native_gui_button(last_at, true), - native_gui_button(last_at, false), - ], - discard, - ); - assert_eq!(edges[0], (true, true, false), "both completed clicks leave no held origin"); - assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay either press"); - let sel = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!( - (sel.story.0, sel.anchor, sel.focus), - (final_story.as_u64().unwrap(), final_focus, final_focus), - "reverse={reverse}, discard={discard}" - ); - let commands = &f.app.session.journal[journal..]; - assert_eq!( - commands.iter().filter(|(id, _)| id == "text.placeCaret").count(), - 1, - "one aggregate canvas selection, reverse={reverse}, discard={discard}" - ); - assert_eq!( - commands.iter().filter(|(id, _)| id == "text.release").count(), - 1, - "one corresponding release, reverse={reverse}, discard={discard}" - ); - let clicks = - f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one recovered canvas press"); - assert_eq!(clicks.n, 1, "separated clicks and discarded passes must not select a word"); - assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "pointer selection adds no document history"); - native_gui_released(&f); - native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false); - let mut target_text = "Target story".to_owned(); - let mut second_text = "Second story".to_owned(); - if reverse { - target_text.insert(final_focus, '!'); - } else { - second_text.insert(final_focus, '!'); - } - assert_eq!(story_text(&mut f.app, &f.target), target_text); - assert_eq!(story_text(&mut f.app, &second), second_text); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "typing at the final caret is one edit"); - native_gui_released(&f); - } - } - } - - /// A non-finite final press rejects the click instead of reviving an earlier valid press; later motion cannot drag. - #[test] - fn native_gui_nonfinite_final_press_cannot_reuse_an_earlier_click() { - for discard in [false, true] { - let mut f = native_gui_click_fixture(); - let at = f.at; - let initial = f.app.session.doc().unwrap().selection.text; - let undo = f.app.session.doc().unwrap().history.undo.len(); - let journal = f.app.session.journal.len(); - let edges = native_gui_input( - &mut f, - vec![ - egui::Event::PointerMoved(at), - native_gui_button(at, true), - native_gui_button(at, false), - native_gui_button(pos2(f32::NAN, at.y), true), - egui::Event::PointerMoved(at), - native_gui_button(at, false), - ], - discard, - ); - assert_eq!(edges[0], (true, true, false)); - assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay malformed input"); - assert_eq!( - f.app.session.doc().unwrap().selection.text, - initial, - "discard={discard}: reject the last press instead of reviving an earlier valid one" - ); - assert!(f.app.session.journal[journal..].iter().all(|(id, _)| id != "text.placeCaret" && id != "text.release")); - assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo); - assert_eq!(story_text(&mut f.app, &f.target), "Target story"); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - native_gui_released(&f); - native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false); - assert_eq!(f.app.session.doc().unwrap().selection.text, initial, "motion after the invalid released press cannot drag"); - native_gui_released(&f); - } - } - - /// A same-batch click switches story exactly once; typing, undo and redo affect only the target story, including discarded-pass runs. - #[test] - fn native_gui_same_batch_click_switches_story_once_before_typing() { - for discard in [false, true] { - let mut f = native_gui_click_fixture(); - let undo = f.app.session.doc().unwrap().history.undo.len(); - let at = f.at; - let edges = - native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], discard); - assert_eq!(edges[0], (true, true, false), "the real input consumed both edges and cleared the origin"); - assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "a discarded pass must not replay the press"); - let selection = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((selection.story.0, selection.anchor, selection.focus), (f.target.as_u64().unwrap(), f.focus, f.focus), "discard={discard}"); - let clicks = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click"); - assert_eq!(clicks.n, 1, "discard={discard}: replay must not turn a caret into word selection"); - native_gui_released(&f); - assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "a click is not a document edit"); - let end = |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - native_gui_input(&mut f, vec![end(true), end(false)], false); - let caret = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((caret.story.0, caret.focus), (f.target.as_u64().unwrap(), "Target story".len())); - native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false); - assert_eq!(story_text(&mut f.app, &f.target), "Target story!"); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "one typed edit, including discarded-pass control"); - f.app.run("edit.undo", json!({})).unwrap(); - assert_eq!(story_text(&mut f.app, &f.target), "Target story"); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - f.app.run("edit.redo", json!({})).unwrap(); - assert_eq!(story_text(&mut f.app, &f.target), "Target story!"); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - native_gui_released(&f); - } - } - - /// The native Windows failure: with a non-empty selection in another story, a click that - /// switches stories followed by End in the same job left the new story's caret at the click - /// point. End in a later job worked. Drive the actual app UI and actual pointer/key events in - /// one batch, in split batches, and with End while the press is still held; discard a pass to - /// cover replay. The End press must reach the type tool once and win over the click, wherever - /// the pointer release falls, and typing must go there once. - #[test] - fn native_gui_click_then_end_in_one_batch_keeps_the_target_caret_at_the_story_end() { - let names = ["same batch, click events first", "click batch then End batch", "End while the press is held"]; - for (layout, name) in names.into_iter().enumerate() { - for discard in [false, true] { - let mut f = native_gui_selected_old_click_fixture(); - let (at, target, old) = (f.at, f.target.clone(), f.old.clone()); - let undo = f.app.session.doc().unwrap().history.undo.len(); - let journal = f.app.session.journal.len(); - let moved = || egui::Event::PointerMoved(at); - let down = || native_gui_button(at, true); - let up = || native_gui_button(at, false); - let end = - |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - let batches: Vec> = match layout { - 0 => vec![vec![moved(), down(), up(), end(true), end(false)]], - 1 => vec![vec![moved(), down(), up()], vec![end(true), end(false)]], - _ => vec![vec![moved(), down()], vec![end(true)], vec![up(), end(false)]], - }; - for events in batches { - native_gui_input(&mut f, events, discard); - } - let selection = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!( - (selection.story.0, selection.anchor, selection.focus), - (target.as_u64().unwrap(), "Target story".len(), "Target story".len()), - "{name}, discard={discard}: End must win after the click, wherever the release falls" - ); - let commands = &f.app.session.journal[journal..]; - assert_eq!( - commands.iter().filter(|(id, _)| id == "text.move").count(), - 1, - "{name}, discard={discard}: the End press reached the type tool once" - ); - let clicks = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click"); - assert_eq!(clicks.n, 1, "{name}, discard={discard}: a discarded pass must not replay the press as a word selection"); - native_gui_released(&f); - native_gui_input(&mut f, vec![egui::Event::Text("!".into())], discard); - assert_eq!(story_text(&mut f.app, &target), "Target story!", "{name}, discard={discard}: typing lands at the End caret once"); - assert_eq!(story_text(&mut f.app, &old), NATIVE_GUI_OLD_DEVANAGARI); - assert_eq!( - f.app.session.journal[journal..].iter().filter(|(id, _)| id == "text.insert").count(), - 1, - "{name}, discard={discard}: the text event is not replayed" - ); - assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "{name}, discard={discard}: one edit"); - } - } - } - - /// Pointer ownership survives a split press/move/release; a real drag selects, release ends it, and later motion cannot continue it. - #[test] - fn native_gui_split_click_and_drag_release_keep_pointer_ownership() { - for drag in [false, true] { - let mut f = native_gui_click_fixture(); - let at = f.at; - native_gui_input(&mut f, vec![native_gui_button(at, true)], false); - let sel = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((sel.story.0, sel.focus), (f.target.as_u64().unwrap(), f.focus)); - assert!(f.ctx.input(|i| i.pointer.primary_down())); - assert!(f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap()); - if drag { - let moved = at + vec2(60.0, 0.0); - native_gui_input(&mut f, vec![egui::Event::PointerMoved(moved)], false); - let sel = f.app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!(sel.story.0, f.target.as_u64().unwrap()); - assert!(!sel.is_caret(), "a real held drag selects text"); - } - let release = if drag { pos2(-20.0, at.y) } else { at }; - native_gui_input(&mut f, vec![egui::Event::PointerMoved(release), native_gui_button(release, false)], false); - native_gui_released(&f); - let selection = f.app.session.doc().unwrap().selection.text; - native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false); - assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "motion after release cannot continue the old drag"); - assert_eq!(story_text(&mut f.app, &f.target), "Target story"); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - } - } - - /// An unowned outside press, and a press that dismisses an open menu, cannot move the selection or edit either story. - #[test] - fn native_gui_outside_press_and_open_menu_do_not_click_through() { - for menu in [false, true] { - let mut f = native_gui_click_fixture(); - let at = f.at; - let selection = f.app.session.doc().unwrap().selection.text; - if menu { - let blank = f.app.canvas_rect.unwrap().max - vec2(30.0, 30.0); - for pressed in [true, false] { - let event = - egui::Event::PointerButton { pos: blank, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; - native_gui_input(&mut f, vec![egui::Event::PointerMoved(blank), event], false); - } - assert!(context_menu_open(&f.ctx), "the actual secondary click opened the canvas menu"); - assert_eq!(f.app.session.doc().unwrap().selection.text, selection); - native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], false); - } else { - let outside = pos2(-20.0, -20.0); - assert!(!f.app.canvas_rect.unwrap().contains(outside)); - native_gui_input( - &mut f, - vec![ - egui::Event::PointerMoved(outside), - native_gui_button(outside, true), - egui::Event::PointerMoved(at), - native_gui_button(at, false), - ], - false, - ); - } - assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "menu={menu}: an unowned press cannot move the old caret"); - assert_eq!(story_text(&mut f.app, &f.target), "Target story"); - assert_eq!(story_text(&mut f.app, &f.old), "Old story"); - native_gui_released(&f); - } - } - - /// Font inventory distinguishes exact bundled faces, missing styles and missing families without accepting installed or injected substitutes. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn native_gui_font_inventory_keeps_exact_regular_and_missing_style_diagnostics() { - if designcraft_fonts::CRAFT_FONTS.is_empty() { - assert!(std::env::var_os("CRAFT_FONTS_REQUIRED").is_none(), "required canonical fonts were not embedded"); - return; // The supported optional-input build has no central document fonts. - } - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - for (family, text) in [("Noto Sans Hebrew", "שלום"), ("Noto Sans Devanagari", "नमस्ते")] { - assert!(designcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == family && f.style == "Regular"), "canonical {family} Regular absent"); - for style in ["Regular", "Unavailable Native GUI Style"] { - let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); - app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": text.len()})).unwrap(); - app.run("type.char", json!({"fontFamily": family, "fontStyle": style})).unwrap(); - } - } - let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "Missing"})).unwrap(); - app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 7})).unwrap(); - app.run("type.char", json!({"fontFamily": "Unavailable Native GUI Family", "fontStyle": "Regular"})).unwrap(); - let inventory = app.run("font.list", json!({})).unwrap(); - let rows = inventory.as_array().unwrap(); - assert_eq!(rows.len(), 5, "{inventory}"); - for family in ["Noto Sans Hebrew", "Noto Sans Devanagari"] { - for style in ["Regular", "Unavailable Native GUI Style"] { - let row = rows.iter().find(|r| r["family"] == family && r["style"] == style).unwrap(); - assert_eq!(row["missing"], false, "{row}"); - assert_eq!(row["styleMissing"], style != "Regular", "{row}"); - assert_eq!(row["matchStatus"], if style == "Regular" { "exact" } else { "styleSubstitute" }, "{row}"); - assert_eq!(row["resolvedFamily"], family, "{row}"); - assert_eq!(row["resolvedStyle"], "Regular", "{row}"); - assert_eq!(row["source"], "bundled", "an installed or injected face cannot satisfy this production contract: {row}"); - } - } - let missing = rows.iter().find(|r| r["family"] == "Unavailable Native GUI Family").unwrap(); - assert_eq!(missing["missing"], true, "{missing}"); - assert_eq!(missing["matchStatus"], "missing", "{missing}"); - assert!(missing["source"].is_null(), "{missing}"); - } - - #[test] - #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may. - fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "曲:"); - // At a text caret the IME is allowed, its window on the caret as the canvas draws it. - let ime = ime_frame(&mut app, &ctx, vec![]).expect("IME allowed at a text caret"); - let (top, bottom) = { - let st = app.session.active().unwrap(); - let cs = app.session.cache.get(&st.doc, designcraft_doc::StoryId(sid.as_u64().unwrap()), None); - let (fi, x, bl, asc, desc) = compose::caret(&cs, "曲:".len()).unwrap(); - let fid = cs.frames[fi].frame; - let (a, _) = item_canvas_xf(&st.doc, &CanvasLayout::new(&st.doc, st.editing_parents), fid).unwrap(); - let m = a * st.doc.text_xf(st.doc.item(fid).unwrap()); - let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); - (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc))) - }; - assert!(ime.rect.expand(1.0).contains(top) && ime.rect.expand(1.0).contains(bottom), "{:?} vs {top:?}–{bottom:?}", ime.rect); - assert_eq!(ime.cursor_rect, ime.rect); - assert!(!ime.should_interrupt_composition); - assert!(app.canvas_ime(), "the web build keeps whole words typed at the caret"); - // "ni" → に → 日, with the events winit sends. - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Enabled), preedit("ni", 2)]); - assert_eq!(story_text(&mut app, &sid), "曲:ni", "marked text shows in place"); - assert!(app.session.tool_composing()); - // Keys, plain text, the clipboard and Undo (the native menu's ⌘Z) wait for the IME. - let steps = app.session.doc().unwrap().history.undo.len(); - let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - ime_frame( - &mut app, - &ctx, - vec![key(egui::Key::Backspace, true), key(egui::Key::Backspace, false), egui::Event::Text("x".into()), egui::Event::Paste("y".into())], - ); - crate::menus::activate(&mut app, "edit.undo", &Value::Null); - assert!(!crate::menus::enabled(&app, "edit.undo")); - assert_eq!(story_text(&mut app, &sid), "曲:ni"); - let ime2 = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("IME allowed while composing"); - assert_eq!(story_text(&mut app, &sid), "曲:に"); - assert!(ime2.rect.center().x > ime.rect.center().x, "the window follows the IME's cursor: {:?} {:?}", ime2.rect, ime.rect); - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Ime(egui::ImeEvent::Disabled)]); - assert_eq!(story_text(&mut app, &sid), "曲:日"); - assert!(!app.session.tool_composing()); - assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the commit is one undo step"); - assert_eq!(app.session.journal.last(), Some(&("text.insert".to_string(), json!({"text": "日"})))); - // After the commit, typing and Undo work again. - ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]); - assert_eq!(story_text(&mut app, &sid), "曲:日!"); - crate::menus::activate(&mut app, "edit.undo", &Value::Null); - crate::menus::activate(&mut app, "edit.undo", &Value::Null); - assert_eq!(story_text(&mut app, &sid), "曲:"); - // Without a text caret the IME is off: single-key tool shortcuts keep working. - app.select_tool("selection"); - assert!(ime_frame(&mut app, &ctx, vec![]).is_none()); - assert!(!app.canvas_ime()); - } - - /// Both panes of a split window see the same keyboard events: only the pane last clicked - /// types them. - #[test] - fn a_split_window_types_once() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "ab"); - app.run("window.split", json!({"on": true})).unwrap(); - for _ in 0..3 { - ime_frame(&mut app, &ctx, vec![]); - } - assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some(), "both panes are drawn"); - ime_frame(&mut app, &ctx, vec![egui::Event::Text("c".into())]); - assert_eq!(story_text(&mut app, &sid), "abc"); - let key = |pressed| egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - ime_frame(&mut app, &ctx, vec![key(true), key(false)]); - assert_eq!(story_text(&mut app, &sid), "ab"); - ime_frame(&mut app, &ctx, vec![egui::Event::Paste("de".into())]); - assert_eq!(story_text(&mut app, &sid), "abde"); - ime_frame(&mut app, &ctx, vec![preedit("に", 1)]); - assert_eq!(story_text(&mut app, &sid), "abdeに"); - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]); - assert_eq!(story_text(&mut app, &sid), "abde日"); - } - - /// Surrounding text is committed text only, preserves reversed selection direction, and a commit keeps owner/generation while reporting `InputMethod`. - #[test] - fn ime_reports_the_committed_story_and_excludes_the_pre_edit() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "a😀b"); - let len = "a😀b".len(); - text_selection(&mut app, &sid, 0, len); - let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0)), "reversed selection keeps its direction"); - let owner = (ime.owner, ime.context_generation); - // Marked text previews in the document but is not committed surrounding text. - let ime = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("a text caret"); - assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0))); - assert_eq!(ime.owner, owner.0); - let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret"); - assert_eq!(ime_payload(&ime), Some(("日", 3, 3))); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); - assert_eq!(story_text(&mut app, &sid), "日"); - assert_eq!(ime.owner, owner.0); - assert_eq!(ime.context_generation, owner.1, "a commit is not a new context"); - let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert_eq!(ime_payload(&ime), Some(("日", 3, 3)), "a later pass reports the same committed text"); - assert_eq!((ime.owner, ime.context_generation), owner, "an unchanged pass keeps the context"); - } - - /// An empty story provides `("",0,0)`; long text is bounded and an out-of-window selection is explicitly unavailable. - #[test] - fn ime_empty_story_is_available_and_wide_text_is_bounded() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - typing_app(&mut app, &ctx, ""); - let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert_eq!(ime_payload(&ime), Some(("", 0, 0)), "an empty document is available, not unavailable"); - assert!(!app.session.tool_composing()); - - let long = "a".repeat(5000); - let sid = typing_app(&mut app, &ctx, &long); - let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - let (text, _, _) = ime_payload(&ime).expect("a long document still has surrounding text"); - assert!(text.len() <= egui::output::MAX_IME_SURROUNDING_TEXT_BYTES, "{}", text.len()); - text_selection(&mut app, &sid, 0, 5000); - let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert!(ime.surrounding_text.available().is_none(), "a selection beyond the bound is explicitly unavailable"); - } - - /// Caret movement preserves owner; changing story or document changes owner and generation. - #[test] - fn ime_owner_follows_the_story_and_the_document() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - typing_app(&mut app, &ctx, "ab"); - let first = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - app.session.execute("text.move", &json!({"dir": "left"})).unwrap(); - let moved = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert_eq!((moved.owner, moved.context_generation), (first.owner, first.context_generation), "a caret move keeps the context"); - - let other = app.run("frame.create", json!({"rect": [400, 36, 200, 100], "content": "text", "text": "xy"})).unwrap(); - let other_sid = other["story"].clone(); - text_selection(&mut app, &other_sid, 2, 2); - let second = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert_ne!(second.owner, first.owner, "another story is another owner"); - assert_ne!(second.context_generation, first.context_generation); - - app.run("file.new", json!({})).unwrap(); - let doc = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "z"})).unwrap(); - text_selection(&mut app, &doc["story"], 1, 1); - let replaced = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); - assert_ne!(replaced.owner, second.owner, "a new document is another owner"); - assert_eq!(ime_payload(&replaced), Some(("z", 1, 1))); - } - - /// Pure commits report `InputMethod`; typing before or after a commit in one pass makes the cause `Other`. - #[test] - fn ime_cause_distinguishes_commits_from_application_edits() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - typing_app(&mut app, &ctx, "a"); - let committed = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret"); - assert_eq!(committed.change_cause, egui::output::ImeChangeCause::InputMethod); - let typed = ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]).expect("a text caret"); - assert_eq!(typed.change_cause, egui::output::ImeChangeCause::Other, "ordinary typing is an application edit"); - assert_eq!(ime_payload(&typed), Some(("a日!", 5, 5))); - - // An application edit before the commit in one pass breaks the receipt chain. - let mut before = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - typing_app(&mut before, &ctx, "a"); - let mixed = ime_frame(&mut before, &ctx, vec![egui::Event::Text("x".into()), egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]) - .expect("a text caret"); - assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other); - assert_eq!(ime_payload(&mixed), Some(("ax日", 5, 5))); - - // An application edit after the commit in one pass also dominates. - let mut after = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - typing_app(&mut after, &ctx, "a"); - let mixed = ime_frame(&mut after, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Text("!".into())]) - .expect("a text caret"); - assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other); - assert_eq!(ime_payload(&mixed), Some(("a日!", 5, 5))); - } - - /// The settled multipass result rebuilds the current surrounding text while retaining the accepted commit cause. - #[test] - fn ime_cause_and_context_survive_a_discarded_pass() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - typing_app(&mut app, &ctx, "a"); - let raw = egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), - events: vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))], - ..Default::default() - }; - let mut passes = 0; - let mut out = ctx.run_ui(raw, |ui| { - passes += 1; - if passes == 1 { - ui.ctx().request_discard("IME multipass regression"); - } - app.logic(ui.ctx()); - app.ui(ui); - }); - out.textures_delta.clear(); - assert_eq!(out.platform_output.num_completed_passes, 2, "the frame really was multipass"); - let ime = out.platform_output.ime.expect("a text caret"); - assert_eq!(ime_payload(&ime), Some(("a日", 4, 4)), "the second pass rebuilds the current text"); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the discarded pass keeps the accepted commit's cause"); - } - - /// Autocorrected commit text is an application edit with cause `Other`. - #[test] - fn ime_autocorrect_is_not_an_input_method_cause() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.session.prefs.autocorrect = true; - let sid = typing_app(&mut app, &ctx, "teh"); - let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit(" ".into()))]).expect("a text caret"); - assert_eq!(story_text(&mut app, &sid), "the "); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::Other); - } - - /// The selection stays selected and directed; byte partials leave whole characters; the deletion is one undo step. - #[test] - fn ime_delete_surrounding_excludes_the_selection_and_rounds_bytes_inward() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "aé😀b"); - // Select é, which keeps its bytes and direction; 'a' before and 😀 after go. - text_selection(&mut app, &sid, 1, 3); - ime_frame(&mut app, &ctx, vec![]); - let steps = app.session.doc().unwrap().history.undo.len(); - let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })]) - .expect("a text caret"); - assert_eq!(story_text(&mut app, &sid), "éb"); - let sel = app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!((sel.anchor, sel.focus), (0, 2), "the selected text stays selected and directed"); - assert_eq!(ime_payload(&ime), Some(("éb", 2, 0))); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); - assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "one deletion is one undo step"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(story_text(&mut app, &sid), "aé😀b"); - ime_frame(&mut app, &ctx, vec![]); - // The same deletion with a reversed selection keeps anchor > focus. - text_selection(&mut app, &sid, 3, 1); - ime_frame(&mut app, &ctx, vec![]); - let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })]) - .expect("a text caret"); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); - let sel = app.session.doc().unwrap().selection.text.unwrap(); - assert_eq!(story_text(&mut app, &sid), "éb"); - assert_eq!((sel.anchor, sel.focus), (2, 0), "reversed selection stays reversed"); - - // One byte of a two-byte character leaves the whole character. - let partial = typing_app(&mut app, &ctx, "aé"); - text_selection(&mut app, &partial, 1, 1); - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 1 })]); - assert_eq!(story_text(&mut app, &partial), "aé"); - // A preceding count that lands inside the four-byte emoji leaves it whole too. - let partial = typing_app(&mut app, &ctx, "a😀"); - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 0 })]); - assert_eq!(story_text(&mut app, &partial), "a😀"); - } - - /// A 200-character request deletes the whole 100-character story. - #[test] - fn ime_delete_surrounding_has_no_sixty_four_character_cap() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, &"x".repeat(100)); - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 200, after_chars: 0 })]); - assert_eq!(story_text(&mut app, &sid), ""); - } - - /// Delete plus commit in one IME batch produces one undoable edit and reports the final surrounding text. - #[test] - fn ime_delete_and_commit_are_one_undo_step() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "ab"); - text_selection(&mut app, &sid, 1, 2); - ime_frame(&mut app, &ctx, vec![]); - let steps = app.session.doc().unwrap().history.undo.len(); - let ime = ime_frame( - &mut app, - &ctx, - vec![ - egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 }), - egui::Event::Ime(egui::ImeEvent::Commit("X".into())), - ], - ) - .expect("a text caret"); - assert_eq!(story_text(&mut app, &sid), "X"); - assert_eq!(ime_payload(&ime), Some(("X", 1, 1))); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); - assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the IME batch is one undo step"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(story_text(&mut app, &sid), "ab"); - } - - /// The input method's Commit for a composition a click ended earlier in the same event batch - /// must not type the marked text again at the clicked caret. - #[test] - fn a_commit_after_a_click_in_the_same_batch_is_not_typed_twice() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "ab"); - ime_frame(&mut app, &ctx, vec![preedit("い", 1)]); - assert_eq!(story_text(&mut app, &sid), "abい"); - let p = on_screen(&app, Point::new(150.0, 120.0)); - let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))]) - .expect("still at a text caret"); - let typed = story_text(&mut app, &sid); - assert_eq!(typed.matches('い').count(), 1, "the click typed the marked text once: {typed:?}"); - assert!(typed.starts_with("ab"), "{typed:?}"); - assert!(!app.session.tool_composing()); - assert!(app.take_ime_discard(), "the system IME is told to drop its copy"); - ime_frame(&mut app, &ctx, vec![press(false)]); - } - - /// A delete-surrounding and its commit from the same ended composition must not edit the - /// clicked caret's text either. - #[test] - fn a_delete_and_commit_after_a_click_in_the_same_batch_are_dropped() { - for delete in [ - egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 }, - egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 }, - ] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, "ab"); - ime_frame(&mut app, &ctx, vec![preedit("い", 1)]); - let p = on_screen(&app, Point::new(150.0, 120.0)); - let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - ime_frame( - &mut app, - &ctx, - vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(delete), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))], - ) - .expect("still at a text caret"); - let typed = story_text(&mut app, &sid); - assert_eq!(typed.matches('い').count(), 1, "the late commit is dropped: {typed:?}"); - assert!(typed.contains("ab"), "the click's text was not deleted: {typed:?}"); - assert!(app.take_ime_discard()); - ime_frame(&mut app, &ctx, vec![press(false)]); - } - } - - /// A byte-count delete that reaches past the bounded IME window is still exactly the requested - /// input method mutation: the engine reports the ranges from the whole story. - #[test] - fn a_delete_beyond_the_surrounding_window_is_still_an_input_method_cause() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, &"x".repeat(5000)); - let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 4500, after_bytes: 0 })]) - .expect("a text caret"); - assert_eq!(story_text(&mut app, &sid).len(), 500); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); - assert_eq!(ime_payload(&ime).map(|(text, cursor, anchor)| (text.len(), cursor, anchor)), Some((500, 500, 500))); - } - - /// The pass's IME observation comes after the later UI sections: a click into the Story - /// Editor's field takes the keyboard from the canvas in the same pass, so the composition - /// ends there and the canvas reports no IME. - #[test] - fn a_later_field_taking_the_keyboard_ends_the_composition_in_that_pass() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap(); - let sid = f["story"].clone(); - app.select_tool("type"); - app.run("text.select", json!({"story": sid, "anchor": 2, "focus": 2})).unwrap(); - app.run("app.storyEditor", json!({"story": sid})).unwrap(); - let mut h = crate::test_window::open(app, egui::vec2(1440.0, 900.0)); - h.event(preedit("い", 1)); - h.run_steps(2); - assert!(h.state().app.session.tool_composing()); - let canvas_owner = h.output().platform_output.ime.as_ref().expect("the canvas owns the composition").owner; - let field = h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().expect("the Story Editor's text field"); - field.click(); - h.run_steps(2); - assert!(!h.state().app.session.tool_composing(), "the composition ended where the field took the keyboard"); - assert!(h.state_mut().app.take_ime_discard()); - assert!(h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().unwrap().is_focused(), "the field has the keyboard"); - let ime = h.output().platform_output.ime.as_ref().expect("the focused Story Editor publishes its IME context"); - assert_ne!(ime.owner, canvas_owner, "the field owns the IME, not the canvas"); - let typed = story_text(&mut h.state_mut().app, &sid); - assert!(typed.contains('い'), "the marked text stays as typed: {typed:?}"); - h.event(egui::Event::Ime(egui::ImeEvent::Commit("X".into()))); - h.run_steps(2); - let edited = story_text(&mut h.state_mut().app, &sid); - assert_eq!(edited.matches('X').count(), 1, "the field's next commit is applied once: {edited:?}"); - assert_eq!(edited.matches('い').count(), 1, "the old canvas composition is not replayed: {edited:?}"); - } - - #[test] - fn clicking_away_mid_composition_keeps_the_text_and_interrupts_the_ime() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, ""); - ime_frame(&mut app, &ctx, vec![preedit("しょうこ", 4)]); - assert!(app.session.tool_composing()); - // A click in the frame (macOS and Windows send nothing for it): the marked text stays as - // typed and the IME is told to drop its composition, once. - let p = on_screen(&app, Point::new(150.0, 120.0)); - let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let ime = ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true)]).expect("still at a text caret"); - assert!(ime.should_interrupt_composition); - ime_frame(&mut app, &ctx, vec![press(false)]); - assert!(!app.session.tool_composing()); - assert_eq!(story_text(&mut app, &sid), "しょうこ"); - assert!(app.take_ime_discard(), "the host tells the system IME to drop its marked text"); - assert!(!ime_frame(&mut app, &ctx, vec![]).expect("still at a text caret").should_interrupt_composition); - assert!(!app.take_ime_discard()); - // A bare line break from the IME confirms a composition: the marked text, no new paragraph. - ime_frame(&mut app, &ctx, vec![preedit("がく", 2)]); - ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("\n".into()))]); - assert!(!app.session.tool_composing()); - let typed = story_text(&mut app, &sid); - assert!(typed.contains("がく") && typed.contains("しょうこ") && !typed.contains('\n'), "{typed:?}"); - } - - #[test] - fn baseline_grid_lines_are_the_ones_on_the_page() { - // A start far above the page used to be walked line by line, without end. - for start in [-1e9, -1e17] { - let mut far = baseline_grid_lines(start, 12.0, 792.0); - assert_eq!((far.next(), far.count()), (Some(8.0), 65)); - } - let lines = |start, increment, height| baseline_grid_lines(start, increment, height).collect::>(); - assert_eq!(lines(36.0, 12.0, 72.0), [36.0, 48.0, 60.0], "the bottom edge is not a line"); - assert_eq!(lines(-30.0, 12.0, 30.0), [6.0, 18.0], "a start above the page keeps its rhythm"); - assert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]); - assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES); - } - - #[test] - fn enter_or_tab_in_a_panel_field_leave_the_selected_text_alone() { - for key in [egui::Key::Enter, egui::Key::Tab] { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap(); - app.select_tool("type"); - app.run("text.select", json!({"story": f["story"], "anchor": 1, "focus": 4})).unwrap(); - assert!(app.session.wants_text()); - let mut h = harness(app); - let size = h.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("12 pt")).unwrap(); - size.focus(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - h.event(egui::Event::Text("18".into())); - h.run_steps(1); - h.key_press(key); - h.run_steps(3); - let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone(); - assert_eq!(text, "Hello", "{key:?} confirms the field and leaves the story alone"); - let size = crate::panels::text_attrs(h.state_mut()).unwrap()["chars"]["size"].clone(); - assert_eq!(size, 18.0, "{key:?} applies the typed size"); - } - } - - #[test] - fn trailing_spaces_show_dots_before_the_paragraph_mark() { - let text = "ab \ncd "; - let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); - let lid = d.default_layer(); - let rect = DRect::new(0.0, 0.0, 300.0, 100.0); - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, text, Default::default()).unwrap(); - let cs = compose::compose_story(&d, sid, &compose::ComposeOptions::default()); - let lines: Vec<_> = cs.frames.iter().flat_map(|f| &f.lines).collect(); - assert_eq!(lines.len(), 2); - for (l, end_mark) in lines.iter().zip(["¶", "#"]) { - let marks = hidden_marks(text, l); - let dots: Vec = marks.iter().filter(|m| m.1 == "·").map(|m| m.0).collect(); - assert_eq!(dots.len(), 2, "a dot for each trailing space: {marks:?}"); - let &(para_x, mark, _) = marks.last().unwrap(); - assert_eq!(mark, end_mark); - // The dots sit past the last letter, and the mark comes after both spaces. - let space = l.glyphs.iter().rev().find(|g| g.len > 0).unwrap(); - assert!(dots.iter().all(|&x| x > l.end_x && x < para_x), "{dots:?} then {mark} at {para_x}"); - assert!(para_x >= space.x + space.adv, "{mark} at {para_x} overlaps the last space"); - } - } -} +mod tests; #[cfg(test)] mod pencil_preview_tests { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs new file mode 100644 index 000000000..ce68f3c12 --- /dev/null +++ b/crates/ui-egui/src/canvas/tests.rs @@ -0,0 +1,2839 @@ +use designcraft_geom::Unit; +use egui_kittest::{Harness, kittest::Queryable}; + +use super::*; + +#[test] +fn a_press_after_a_drag_is_not_a_double_click() { + let (delay, dist) = (0.3, 6.0); + let press = |last, x: f32, now| press_count(last, pos2(x, 0.0), now, delay, dist); + // Click, click: a double click. + let n = press(None, 0.0, 0.0); + let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n }, pos2(0.0, 0.0), 0.1, dist); + assert_eq!(press(Some(up), 1.0, 0.2), 2); + // A drag from 0 to 100, then a fast press where it started or where it ended: a single click. + let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n: 1 }, pos2(100.0, 0.0), 0.1, dist); + assert_eq!(press(Some(up), 0.0, 0.2), 1); + assert_eq!(press(Some(up), 100.0, 0.2), 1); + // Too slow: a single click. + let up = release_clicks(Clicks { at: f64::NEG_INFINITY, pos: pos2(0.0, 0.0), n: 1 }, pos2(0.0, 0.0), 0.1, dist); + assert_eq!(press(Some(up), 0.0, 1.0), 1); +} + +/// While a page's render is on its way the page shows paper, not the black of its shadow. +#[test] +fn pages_show_paper_under_their_render() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); + let ctx = egui::Context::default(); + let mut shapes = Vec::new(); + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + shapes = out.shapes; + } + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The paper swatch on screen (white, as the colour settings show it). + let [r, g, b, _] = st.doc.resolve_color(designcraft_color::swatch::PAPER, 1.0).unwrap().to_rgba8(1.0); + let paper: Vec = shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(s) if s.fill == Color32::from_rgb(r, g, b) => Some(s.rect), + _ => None, + }) + .collect(); + // Each page on its own (a spread's pages may differ in size). + assert_eq!(paper.len(), st.doc.page_count()); + for abs in 0..st.doc.page_count() { + let want = xf.rect(layout.page_rect(&st.doc, abs).unwrap()); + assert!(paper.iter().any(|r| (r.min - want.min).length() < 0.01 && (r.max - want.max).length() < 0.01), "page {abs}"); + } +} + +/// Bleed and Slug are preview modes: like Preview they hide the guides, and what the page +/// shows widens to the bleed or the slug box. The slug guide is drawn in Normal, in its own +/// colour, beside the bleed guide. +#[test] +fn bleed_and_slug_are_preview_modes_that_show_their_area() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"bleed": 9, "slug": 18})).unwrap(); + let strokes = |app: &mut DesignApp, want: [u8; 3]| -> usize { + let ctx = egui::Context::default(); + let mut shapes = Vec::new(); + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + shapes = out.shapes; + } + let want = c32(want); + shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(s) if s.stroke.color == want)).count() + }; + let s = app.session.active().unwrap().doc.settings.clone(); + // Normal draws every guide, the slug's among them. + app.ui.screen_mode = ScreenMode::Normal; + assert!(strokes(&mut app, s.margin_color) > 0, "Normal draws the margin guide"); + assert!(strokes(&mut app, s.bleed_color) > 0, "Normal draws the bleed guide"); + assert!(strokes(&mut app, s.slug_color) > 0, "Normal draws the slug guide"); + // Every preview mode hides them. + for mode in [ScreenMode::Preview, ScreenMode::Bleed, ScreenMode::Slug, ScreenMode::Presentation] { + app.ui.screen_mode = mode; + assert_eq!(strokes(&mut app, s.margin_color), 0, "{mode:?} hides the margin guide"); + assert_eq!(strokes(&mut app, s.slug_color), 0, "{mode:?} hides the slug guide"); + } +} + +/// Each preview mode's shown area: Preview stops at the trim, Bleed reaches the bleed box and +/// Slug the slug box. A slug narrower than the bleed never pulls the edge back in. +#[test] +fn shown_area_widens_to_the_bleed_and_slug_boxes() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"bleed": 9, "slug": 18})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let xf = Xf::new(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)), &View::default()); + let slot = &layout.slots[0]; + let area = |app: &mut DesignApp, mode| { + app.ui.screen_mode = mode; + shown_area(app, &doc, &xf, slot) + }; + let trim = xf.rect(slot.bounds); + assert_eq!(area(&mut app, ScreenMode::Preview), trim, "Preview stops at the trim"); + assert_eq!(area(&mut app, ScreenMode::Presentation), trim, "Presentation stops at the trim"); + let bleed = area(&mut app, ScreenMode::Bleed); + let slug = area(&mut app, ScreenMode::Slug); + assert!(bleed.contains_rect(trim) && bleed != trim, "Bleed reaches past the trim"); + assert!(slug.contains_rect(bleed) && slug != bleed, "Slug reaches past the bleed"); + // 9 pt of bleed and 18 pt of slug at this zoom, on every edge. + let grew = |r: Rect, pt: f64| { + let d = (pt * xf.zoom) as f32; + (r.min - trim.min + vec2(d, d)).length() < 0.01 && (r.max - trim.max - vec2(d, d)).length() < 0.01 + }; + assert!(grew(bleed, 9.0), "Bleed grows by the bleed: {bleed:?}"); + assert!(grew(slug, 18.0), "Slug grows by the slug: {slug:?}"); + // A slug inside the bleed: Slug still shows every printing element, so the bleed too. + app.run("file.new", serde_json::json!({"bleed": 18, "slug": 9})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + app.ui.screen_mode = ScreenMode::Slug; + assert!(grew(shown_area(&app, &doc, &xf, slot), 18.0), "the wider of the two boxes wins"); + // No bleed and no slug: nothing to widen to. + app.run("file.new", serde_json::json!({})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + for mode in [ScreenMode::Bleed, ScreenMode::Slug] { + app.ui.screen_mode = mode; + assert_eq!(shown_area(&app, &doc, &xf, slot), trim, "{mode:?} without a bleed or slug"); + } +} + +/// Build the four-fps app harness used by canvas tests. +fn harness(app: DesignApp) -> Harness<'static, DesignApp> { + harness_with_step(app, 1.0 / 4.0) +} + +/// A window whose frames last `step_dt` seconds. Wheel motion is tested at a realistic frame +/// rate: egui ends a scroll action after 150 ms without wheel events, so quarter-second +/// frames would split every motion into separate actions. +fn harness_with_step(app: DesignApp, step_dt: f32) -> Harness<'static, DesignApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(step_dt).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +#[test] +fn display_option_change_drops_the_render_in_flight() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let shown = crate::Shown { doc: (1, 2, 3, false), origin: Point::new(0.0, 0.0), zoom: 1.0, size: (10.0, 10.0), editing_parents: false }; + invalidate_on_display_change(&mut app); + app.canvas.shown = Some(shown); + app.canvas.pending = Some((7, shown)); + // Nothing changed: the texture and the request stay. + invalidate_on_display_change(&mut app); + assert!(app.canvas.shown.is_some() && app.canvas.pending.is_some()); + // A display option changed while the render ran: its result must not be accepted. + app.ui.display_quality = designcraft_render::DisplayQuality::Fast; + invalidate_on_display_change(&mut app); + assert!(app.canvas.shown.is_none() && app.canvas.pending.is_none() && app.canvas.pending_doc.is_none()); + // The document grid is drawn into the texture too. + app.canvas.shown = Some(shown); + app.ui.document_grid = !app.ui.document_grid; + invalidate_on_display_change(&mut app); + assert!(app.canvas.shown.is_none()); +} + +/// A primary-button drag from `a` to `b` over a few frames. +fn drag(h: &mut Harness<'_, DesignApp>, a: Pos2, b: Pos2) { + h.hover_at(a); + h.step(); + h.event(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + for k in 1..=4 { + h.hover_at(a + (b - a) * (k as f32 / 4.0)); + h.step(); + } + h.event(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); +} + +#[test] +fn the_page_tool_draws_liquid_guides_from_the_rulers() { + // Chris Cicchino's Page Tool and Liquid Layout video (11:00): with the Page tool, a guide + // dragged from the ruler is a liquid guide (dashed). + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.set_tool("page"); + let mut h = harness(app); + let r = h.state().canvas_rect.unwrap(); + let guides = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].guides.clone(); + drag(&mut h, pos2(r.center().x, r.min.y - 8.0), r.center()); + let g = guides(&h); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(g[0].liquid && g[0].orientation == designcraft_doc::Orientation::Horizontal); + // With the Selection tool it's a ruler guide. + h.state_mut().session.set_tool("selection"); + drag(&mut h, pos2(r.center().x, r.min.y - 8.0), r.center() + vec2(0.0, 40.0)); + let g = guides(&h); + assert_eq!(g.len(), 2); + assert!(!g[1].liquid); +} + +/// Dragging a column guide with the Selection tool moves its gutter (one undo step); with +/// column guides locked the same drag leaves the columns alone. +#[test] +fn the_selection_tool_drags_a_column_guide() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + // Two columns across the 540 pt margin box: the gutter's left edge is at x = 300. + app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap(); + let mut h = harness(app); + let page = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].clone(); + let screen = |h: &Harness<'_, DesignApp>, x: f64| { + let app = h.state(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); + let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap(); + (xf.to_screen(slot.xf * Point::new(x, 400.0)), xf.zoom as f32) + }; + let (at, zoom) = screen(&h, 300.0); + drag(&mut h, at, at + vec2(72.0 * zoom, 0.0)); + assert_eq!(page(&h).columns.positions, None, "column guides are locked in a new document"); + h.hover_at(at); + h.run_steps(2); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); + + h.state_mut().run("view.lockColumnGuides", json!({"on": false})).unwrap(); + h.run_steps(2); + let (at, zoom) = screen(&h, 300.0); + drag(&mut h, at, at + vec2(72.0 * zoom, 0.0)); + let pg = page(&h); + let cols = pg.column_rects(); + assert!((cols[0].x1 - 372.0).abs() < 1.0 && (cols[1].x0 - cols[0].x1 - 12.0).abs() < 1e-9, "{cols:?}"); + assert!(pg.local_margins, "the dragged page's columns are its own"); + // Over the moved guide: a resize cursor. + h.hover_at(screen(&h, 372.0).0); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(page(&h).columns.positions, None, "one undo step"); + + // Escape during the drag puts the gutter back. + h.hover_at(at); + h.step(); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.hover_at(at + vec2(40.0, 0.0)); + h.step(); + assert!(page(&h).columns.positions.is_some(), "the drag previews"); + h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.step(); + h.event(egui::Event::PointerButton { + pos: at + vec2(40.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }); + h.run_steps(3); + assert_eq!(page(&h).columns.positions, None); + assert!(!page(&h).local_margins); + + // Space pressed during the drag and the button released under it: the drag ends with the + // release and the gutter stops following the pointer. + let key = |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + h.hover_at(at); + h.step(); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.hover_at(at + vec2(40.0, 0.0)); + h.step(); + h.event(key(true)); + h.step(); + h.event(egui::Event::PointerButton { + pos: at + vec2(40.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }); + h.step(); + h.event(key(false)); + h.run_steps(2); + let moved = page(&h).columns.positions; + assert!(moved.is_some()); + h.hover_at(at + vec2(120.0, 0.0)); + h.run_steps(3); + assert_eq!(page(&h).columns.positions, moved, "the gutter stays where the drag ended"); + assert!(h.state().session.active().unwrap().interaction.is_none()); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(page(&h).columns.positions, None, "the drag was one undo step"); +} + +/// A column guide is not picked where the screen mode hides guides, where an object on the +/// parent being edited lies over it, or where its columns cannot move. +#[test] +fn column_guides_are_picked_only_where_a_drag_can_move_them() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 1})).unwrap(); + app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap(); + app.run("view.lockColumnGuides", json!({"on": false})).unwrap(); + let mut h = harness(app); + let hit = |h: &Harness<'_, DesignApp>, r: SpreadRef, x: f64| { + let app = h.state(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let slot = layout.slots.iter().find(|s| s.spread == r).unwrap(); + column_guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(x, 400.0))) + }; + assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_some()); + h.state_mut().ui.screen_mode = ScreenMode::Preview; + assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_none(), "Preview hides the guides"); + h.state_mut().ui.screen_mode = ScreenMode::Normal; + + // Editing parent A: its right page (the one page 0 follows) and a frame over its gutter. + h.state_mut().run("layout.parents.edit", json!({"on": true, "parent": "A-Parent"})).unwrap(); + h.run_steps(2); + let parent = SpreadRef::Parent(0); + let x = h.state().session.active().unwrap().doc.parents[0].pages[1].column_rects()[0].x1; + assert!(hit(&h, parent, x).is_some()); + h.state_mut() + .run("frame.create", json!({"spread": {"kind": "parent", "index": 0}, "rect": [x - 20.0, 300.0, x + 20.0, 500.0], "content": "text"})) + .unwrap(); + h.run_steps(2); + assert!(hit(&h, parent, x).is_none(), "the parent's frame takes the press"); + h.state_mut().run("layout.parents.edit", json!({"on": false})).unwrap(); + h.run_steps(2); + + // Gutters wider than the margin box: the even split cannot be moved. + h.state_mut().run("layout.marginsAndColumns", json!({"pages": [0], "columns": 2, "gutter": 1000})).unwrap(); + h.run_steps(2); + let x = h.state().session.active().unwrap().doc.spreads[0].pages[0].column_rects()[0].x1; + assert!(hit(&h, SpreadRef::Doc(0), x).is_none()); +} + +fn right_click(h: &mut Harness<'_, DesignApp>, p: Pos2) { + h.hover_at(p); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }); + } + h.run_steps(3); +} + +fn new_document() -> Harness<'static, DesignApp> { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + harness(app) +} + +/// [`new_document`] at 60 frames a second, the cadence a wheel motion really arrives at. +fn new_document_60fps() -> Harness<'static, DesignApp> { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + harness_with_step(app, 1.0 / 60.0) +} + +fn held(modifiers: egui::Modifiers) -> egui::Event { + egui::Event::ModifiersChanged(modifiers) +} + +/// Construct a point-unit vertical mouse-wheel event with an unknown source. +fn wheel(phase: egui::TouchPhase, up: f32, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, up), phase, modifiers, source: egui::MouseWheelSource::Unknown } +} + +// Plays `events` with the pointer at `at`, a frame each, and lets the motion settle. +fn play(h: &mut Harness<'_, DesignApp>, at: Pos2, events: &[egui::Event]) -> View { + h.hover_at(at); + for event in events { + h.event(event.clone()); + h.step(); + } + h.run_steps(30); + *h.state().view().unwrap() +} + +/// Alt + wheel scrolled the view like the plain wheel; it zooms at the pointer (#470). +#[test] +fn alt_wheel_zooms_at_the_pointer() { + use egui::{Modifiers, TouchPhase::Move}; + let mut h = new_document(); + let rect = h.state().canvas_rect.unwrap(); + let at = rect.center() + vec2(150.0, 90.0); + let before = *h.state().view().unwrap(); + let under = Xf::new(rect, &before).to_canvas(at); + let zoomed = play(&mut h, at, &[held(Modifiers::ALT), wheel(Move, 100.0, Modifiers::ALT)]); + assert!(zoomed.zoom > before.zoom * 1.2, "wheel up zooms in: {} -> {}", before.zoom, zoomed.zoom); + let still = Xf::new(rect, &zoomed).to_canvas(at); + assert!((still.x - under.x).abs() < 0.01 && (still.y - under.y).abs() < 0.01, "the point under the pointer stays: {under:?} -> {still:?}"); + let back = play(&mut h, at, &[held(Modifiers::ALT), wheel(Move, -100.0, Modifiers::ALT)]); + assert!((back.zoom - before.zoom).abs() < 1e-6, "wheel down zooms out: {} -> {}", zoomed.zoom, back.zoom); + // The plain wheel still scrolls. + let scrolled = play(&mut h, at, &[held(Modifiers::NONE), wheel(Move, 100.0, Modifiers::NONE)]); + assert!(scrolled.zoom == back.zoom && scrolled.origin.y < back.origin.y, "{back:?} -> {scrolled:?}"); +} + +/// Alt zooms exactly as Ctrl/Cmd does, also when the key is let go while the wheel's motion is +/// still arriving: the rest of it zooms too and does not scroll the page. +#[test] +fn alt_wheel_zooms_like_ctrl_wheel_to_the_end_of_the_motion() { + use egui::{ + Modifiers, + TouchPhase::{End, Move, Start}, + }; + const NONE: Modifiers = Modifiers::NONE; + // Each motion in steps; the views are compared after every step. + let motions: [fn(Modifiers) -> Vec>; 4] = [ + |key| vec![vec![held(key), wheel(Move, 100.0, key)]], + // A wheel turned fast, the key let go a frame later. + |key| vec![vec![held(key), wheel(Move, 400.0, key), held(NONE)]], + // A trackpad swipe that coasts on after the key is let go; once it has ended, the wheel scrolls. + |key| { + vec![ + vec![held(key), wheel(Start, 0.0, key), wheel(Move, 50.0, key), held(NONE), wheel(Move, 200.0, NONE)], + vec![wheel(End, 0.0, NONE), wheel(Move, 100.0, NONE)], + ] + }, + |key| vec![vec![held(key | Modifiers::SHIFT), wheel(Move, 100.0, key | Modifiers::SHIFT)]], + ]; + for (i, motion) in motions.iter().enumerate() { + let (mut with_alt, mut with_command) = (new_document_60fps(), new_document_60fps()); + let at = with_alt.state().canvas_rect.unwrap().center() + vec2(150.0, 90.0); + let start = *with_alt.state().view().unwrap(); + for (alt, command) in motion(Modifiers::ALT).iter().zip(motion(Modifiers::COMMAND)) { + let (alt, command) = (play(&mut with_alt, at, alt), play(&mut with_command, at, &command)); + assert!(command.zoom > start.zoom, "motion {i} zooms"); + assert_eq!(alt, command, "motion {i}"); + } + } +} + +fn units(h: &Harness<'_, DesignApp>) -> (Unit, Unit) { + let s = &h.state().session.doc().unwrap().doc.settings; + (s.horizontal_units, s.vertical_units) +} + +fn zoom_app(tool: &str) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.select_tool(tool); + app.ui.rulers = false; + app +} + +/// Run one app frame with the supplied modifiers, install fonts, draw the canvas when ready and return the cursor icon. +fn canvas_frame(app: &mut DesignApp, ctx: &egui::Context, m: egui::Modifiers, mut events: Vec) -> egui::CursorIcon { + events.insert(0, egui::Event::ModifiersChanged(m)); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }, |ui| { + app.logic(ui.ctx()); + // Fonts are installed by the first real UI pass, just as in the full application. + app.ui_setup(ui.ctx()); + if app.fonts_ready { + show(app, ui); + } + }); + output.textures_delta.clear(); + output.platform_output.cursor_icon +} + +/// The cursor icon the canvas sets for `c` on this platform (bitmap and painted cursors +/// report their own icon). +fn shown(c: Cursor) -> egui::CursorIcon { + crate::cursors::show(&egui::Context::default(), &mut crate::cursors::Images::default(), c, Pos2::ZERO) +} + +fn space_key(pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers } +} + +fn press(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +fn hover(app: &mut DesignApp, ctx: &egui::Context, p: Pos2) { + for _ in 0..3 { + canvas_frame(app, ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p)]); + } +} + +const CMD: egui::Modifiers = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; + +#[test] +fn spring_zoom_click_is_anchored_view_only_and_release_restores_previous_tool() { + for tool in ["rectangleFrame", "directSelection", "type", "hand", "zoom"] { + let mut app = zoom_app(tool); + if tool == "rectangleFrame" { + let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap(); + app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap(); + } + let ctx = egui::Context::default(); + let p = pos2(300.0, 250.0); + hover(&mut app, &ctx, p); + let before = *app.view().unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let selection = app.session.doc().unwrap().selection.clone(); + let history = app.run("document.history", json!({})).unwrap(); + let cursor = canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]); + assert_eq!(cursor, shown(Cursor::ZoomIn), "{tool}"); + canvas_frame(&mut app, &ctx, CMD, vec![press(p, true, CMD)]); + canvas_frame(&mut app, &ctx, CMD, vec![press(p, false, CMD)]); + let after = *app.view().unwrap(); + assert_eq!(after.zoom, before.zoom * 2.0, "{tool}"); + let anchor = Xf::new(app.canvas_rect.unwrap(), &before).to_canvas(p); + assert!((Xf::new(app.canvas_rect.unwrap(), &after).to_canvas(p) - anchor).hypot() < 1e-9); + let cursor = canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]); + assert_eq!(app.session.tool_id(), tool); + let expected = app.session.cursor(anchor, Mods::default(), app.view_info()); + assert_eq!(cursor, shown(expected), "{tool}"); + assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); + assert_eq!(selection, app.session.doc().unwrap().selection); + assert_eq!(history, app.run("document.history", json!({})).unwrap()); + } +} + +#[test] +fn spring_zoom_alt_clicks_out_and_modifier_release_switches_back_to_hand() { + let mut app = zoom_app("rectangleFrame"); + let ctx = egui::Context::default(); + let p = pos2(300.0, 250.0); + hover(&mut app, &ctx, p); + let z = app.view().unwrap().zoom; + let alt = egui::Modifiers { alt: true, ..CMD }; + assert_eq!(canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]), shown(Cursor::ZoomIn)); + assert_eq!(canvas_frame(&mut app, &ctx, alt, vec![]), shown(Cursor::ZoomOut)); + canvas_frame(&mut app, &ctx, alt, vec![press(p, true, alt)]); + canvas_frame(&mut app, &ctx, alt, vec![press(p, false, alt)]); + assert_eq!(app.view().unwrap().zoom, z * 0.5); + assert_eq!(canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![]), shown(Cursor::Hand)); + let before = *app.view().unwrap(); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p + vec2(80.0, 0.0))]); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p + vec2(80.0, 0.0), false, egui::Modifiers::NONE)]); + assert_eq!(app.view().unwrap().zoom, before.zoom); + assert!(app.view().unwrap().origin.x < before.origin.x); + assert_eq!(app.session.tool_id(), "rectangleFrame"); +} + +#[test] +fn spring_zoom_scrubs_and_owns_pointer_release_after_shortcut_release() { + let mut app = zoom_app("rectangleFrame"); + let ctx = egui::Context::default(); + let p = pos2(300.0, 250.0); + hover(&mut app, &ctx, p); + let z = app.view().unwrap().zoom; + let doc = app.session.doc().unwrap().doc.clone(); + // Ctrl is the platform command modifier on Windows/Linux, using the same input path. + let cmd = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + canvas_frame(&mut app, &ctx, cmd, vec![space_key(true, cmd), press(p, true, cmd)]); + let end = p + vec2(150.0, 0.0); + canvas_frame(&mut app, &ctx, cmd, vec![egui::Event::PointerMoved(end)]); + assert!((app.view().unwrap().zoom - z * std::f64::consts::E).abs() < 1e-9); + let scrubbed = app.view().unwrap().zoom; + assert_eq!(canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]), shown(Cursor::Crosshair)); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(end, false, egui::Modifiers::NONE)]); + assert_eq!(app.view().unwrap().zoom, scrubbed, "no extra click zoom at the end of a scrub"); + assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); + // The original tool still draws after the temporary gesture. + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![egui::Event::PointerMoved(p + vec2(50.0, 50.0))]); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p + vec2(50.0, 50.0), false, egui::Modifiers::NONE)]); + assert!(!std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); + assert_eq!(app.session.tool_id(), "rectangleFrame"); +} + +#[test] +fn spring_zoom_is_suppressed_while_typing_in_a_text_frame() { + let mut app = zoom_app("type"); + let frame = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap(); + app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap(); + assert!(app.session.wants_text()); + let ctx = egui::Context::default(); + let p = pos2(300.0, 250.0); + hover(&mut app, &ctx, p); + let before = *app.view().unwrap(); + let alt = egui::Modifiers { alt: true, ..CMD }; + for m in [CMD, alt] { + app.run("text.select", json!({"story":frame["story"],"anchor":5})).unwrap(); + assert!(app.session.wants_text()); + assert!(!matches!(canvas_frame(&mut app, &ctx, m, vec![space_key(true, m)]), egui::CursorIcon::ZoomIn | egui::CursorIcon::ZoomOut)); + canvas_frame(&mut app, &ctx, m, vec![press(p, true, m)]); + canvas_frame(&mut app, &ctx, m, vec![press(p, false, m)]); + assert_eq!(app.view().unwrap().zoom, before.zoom); + assert_eq!(app.view().unwrap().origin, before.origin); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![space_key(false, egui::Modifiers::NONE)]); + } +} + +#[test] +fn spring_zoom_is_suppressed_while_a_text_field_has_focus() { + let mut app = zoom_app("rectangleFrame"); + let ctx = egui::Context::default(); + let mut text = String::new(); + let p = pos2(300.0, 250.0); + hover(&mut app, &ctx, p); + let before = *app.view().unwrap(); + for m in [egui::Modifiers::NONE, CMD, egui::Modifiers { alt: true, ..CMD }] { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), + events: vec![egui::Event::ModifiersChanged(m), space_key(true, m), egui::Event::Text("x".into()), egui::Event::PointerMoved(p)], + ..Default::default() + }, + |ui| { + ui.text_edit_singleline(&mut text).request_focus(); + show(&mut app, ui); + }, + ); + output.textures_delta.clear(); + assert!(ctx.text_edit_focused()); + assert!(!matches!(output.platform_output.cursor_icon, egui::CursorIcon::ZoomIn | egui::CursorIcon::ZoomOut | egui::CursorIcon::Grab)); + assert_eq!(app.view().unwrap().zoom, before.zoom); + assert_eq!(app.session.tool_id(), "rectangleFrame"); + } + assert!(!text.is_empty(), "typing still reaches the field"); +} + +#[test] +fn spring_zoom_does_not_interrupt_an_existing_tool_drag() { + let mut app = zoom_app("rectangleFrame"); + let ctx = egui::Context::default(); + let p = pos2(300.0, 250.0); + hover(&mut app, &ctx, p); + let before = *app.view().unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + canvas_frame(&mut app, &ctx, egui::Modifiers::NONE, vec![press(p, true, egui::Modifiers::NONE)]); + let end = p + vec2(100.0, 100.0); + canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD), egui::Event::PointerMoved(end)]); + canvas_frame(&mut app, &ctx, CMD, vec![press(end, false, CMD)]); + assert_eq!(app.view().unwrap().zoom, before.zoom); + assert_eq!(app.view().unwrap().origin, before.origin); + assert!(!std::sync::Arc::ptr_eq(&doc, &app.session.doc().unwrap().doc)); +} + +#[test] +fn spring_zoom_does_not_zoom_on_the_rulers() { + let mut app = zoom_app("rectangleFrame"); + app.ui.rulers = true; + let ctx = egui::Context::default(); + hover(&mut app, &ctx, pos2(300.0, 250.0)); + let rect = app.canvas_rect.unwrap(); + let p = pos2(rect.min.x - RULER / 2.0, rect.center().y); + hover(&mut app, &ctx, p); + let before = *app.view().unwrap(); + canvas_frame(&mut app, &ctx, CMD, vec![space_key(true, CMD)]); + canvas_frame(&mut app, &ctx, CMD, vec![press(p, true, CMD)]); + canvas_frame(&mut app, &ctx, CMD, vec![press(p, false, CMD)]); + assert_eq!(app.view().unwrap().zoom, before.zoom); + assert_eq!(app.view().unwrap().origin, before.origin); +} + +#[test] +fn parent_guides_on_a_page_are_not_picked_there() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + // 100 pt into A's right page, which page 1 (a right page at x = 0) shows. + let parent_guide = json!({"spread": {"kind": "parent", "index": 0}, "page": 1, "orientation": "vertical", "position": 712}); + app.run("guide.add", parent_guide).unwrap(); + let mut h = harness(app); + let at = |app: &DesignApp| { + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); + let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap(); + guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(100.0, 300.0))) + }; + assert_eq!(at(h.state()), None, "the parent's guide is edited on the parent"); + h.state_mut().run("guide.add", json!({"orientation": "vertical", "position": 100})).unwrap(); + h.run_steps(2); + assert!(matches!(at(h.state()), Some((SpreadRef::Doc(0), 0, 0, _))), "the page's own guide is"); +} + +#[test] +fn mouse_double_clicking_a_frame_handle_fits_with_one_undo_step() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [100, 100, 400, 300], "content": "text", "text": "Fit this text"})).unwrap()["id"].as_u64().unwrap(), + ); + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + let original = app.session.doc().unwrap().doc.item(id).unwrap().bounds(); + // 60 frames a second: the default 0.25 s step puts two clicks past egui's double-click delay. + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + let app = h.state(); + let st = app.session.doc().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let p = xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(original.x1, original.y1)); + h.hover_at(p); + h.step(); + // Separate frames model the actual mouse, including egui's release-time double click. + for _ in 0..2 { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); + } + } + h.run_steps(2); + let fitted = h.state().session.doc().unwrap().doc.item(id).unwrap().bounds(); + assert!(fitted.width() < original.width() && fitted.height() < original.height(), "{fitted:?}"); + assert_eq!(h.state().session.tool_id(), "selection"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(h.state().session.doc().unwrap().doc.item(id).unwrap().bounds(), original); +} + +const ART: &str = r##""##; + +#[test] +fn pasting_svg_from_another_app_places_editable_paths_in_the_middle_of_the_view() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut h = harness(app); + h.run_steps(2); + let undo = h.state().session.doc().unwrap().history.undo.len(); + h.event(egui::Event::Paste(ART.into())); + h.run_steps(2); + let app = h.state(); + let st = app.session.doc().unwrap(); + assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); + let id = *st.selection.items.first().expect("the pasted path is selected"); + let it = st.doc.item(id).unwrap(); + assert_eq!(it.shape, designcraft_doc::Shape::Path); + assert_eq!(it.path.subpaths[0].anchors.len(), 2); + assert!((it.stroke.weight - 2.0).abs() < 1e-9); + // Centred where text from another app would go: the middle of the view. + let (_, centre) = view_centre(app).unwrap(); + assert!((it.bounds().center() - centre).hypot() < 0.01, "{:?} vs {centre:?}", it.bounds()); +} + +#[test] +fn the_paste_in_place_shortcut_pastes_in_place_and_plain_paste_offsets() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let original = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds(); + app.run("edit.copy", json!({})).unwrap(); + let clip = app.object_clip_text.clone().expect("the copy's placeholder text"); + let mut h = harness(app); + let paste = |h: &mut Harness<'static, DesignApp>, modifiers: egui::Modifiers| { + // As egui-winit delivers ⌃⌥⇧V: the chord's paste and the V release, no V press; here the + // modifiers are released within the same frame. + let release = egui::Event::Key { key: egui::Key::V, physical_key: None, pressed: false, repeat: false, modifiers }; + let none = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + h.input_mut().events.extend([egui::Event::ModifiersChanged(modifiers), egui::Event::Paste(clip.clone()), release, none]); + h.run_steps(2); + let st = h.state().session.doc().unwrap(); + let pasted = *st.selection.items.first().expect("the copy is selected"); + assert_ne!(pasted.0, id); + st.doc.item(pasted).unwrap().bounds() + }; + let linux = egui::Modifiers { alt: true, ctrl: true, shift: true, mac_cmd: false, command: true }; + assert_eq!(paste(&mut h, linux), original, "Paste in Place"); + let moved = paste(&mut h, egui::Modifiers::COMMAND); + assert!((moved.x0 - original.x0 - 12.0).abs() < 1e-9 && (moved.y0 - original.y0 - 12.0).abs() < 1e-9, "{moved:?}"); + // The modifiers went down in an earlier frame than the paste. + h.event_modifiers(egui::Event::Paste(clip.clone()), linux); + h.run_steps(2); + let st = h.state().session.doc().unwrap(); + let pasted = *st.selection.items.first().expect("the copy is selected"); + assert_eq!(st.doc.item(pasted).unwrap().bounds(), original); +} + +#[test] +fn edit_paste_from_the_menu_pastes_svg_on_the_system_clipboard_as_paths() { + let services = crate::Services { clipboard_text: Some(Box::new(|| Some(ART.to_string()))), ..Default::default() }; + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + let st = app.session.doc().unwrap(); + let id = *st.selection.items.first().expect("the pasted path is selected"); + assert_eq!(st.doc.item(id).unwrap().shape, designcraft_doc::Shape::Path); + assert!(st.selection.text.is_none(), "paths, not a text frame of markup"); + // With an insertion point, the markup is text like any other. + let story = app.run("frame.create", json!({"rect": [10, 10, 300, 300], "content": "text"})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items, "no paths added"); +} + +#[test] +fn selected_merged_owners_paint_the_same_row_and_column_targets() { + for column in [true, false] { + for merged in [false, true] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 1})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text"})).unwrap(); + app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); + if merged { + let range = if column { json!({"rows": [0, 0], "cols": [0, 1]}) } else { json!({"rows": [0, 1], "cols": [0, 0]}) }; + app.run("table.select", range).unwrap(); + app.run("table.merge", json!({})).unwrap(); + } + app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap(); + app.run(if column { "table.selectColumn" } else { "table.selectRow" }, json!({})).unwrap(); + let st = app.session.doc().unwrap(); + let selection = st.selection.clone(); + let ts = selection.text.unwrap(); + let selected = selection.cells.unwrap(); + assert_eq!( + selected.range, + if column { designcraft_doc::CellRange::new(0, 1, 1, 1) } else { designcraft_doc::CellRange::new(1, 0, 1, 1) } + ); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let cs = app.session.cache.get(&st.doc, ts.story, None); + let ft = &cs.frames[0]; + let table = ft.tables.iter().find(|t| t.table == selected.table).unwrap(); + let (a, _) = item_canvas_xf(&st.doc, &layout, ft.frame).unwrap(); + let m = a * st.doc.text_xf(st.doc.item(ft.frame).unwrap()); + let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) }; + let owners = if merged { + [(0, 0), (1, 1)] + } else if column { + [(0, 1), (1, 1)] + } else { + [(1, 0), (1, 1)] + }; + let expected: Vec<_> = owners + .into_iter() + .map(|(r, c)| { + let rect = table.cells.iter().find(|cell| cell.row == r && cell.col == c).unwrap().rect; + vec![ + xf.to_screen(m * Point::new(rect.x0, rect.y0)), + xf.to_screen(m * Point::new(rect.x1, rect.y0)), + xf.to_screen(m * Point::new(rect.x1, rect.y1)), + xf.to_screen(m * Point::new(rect.x0, rect.y1)), + ] + }) + .collect(); + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_text_selection(&app, ui.painter(), &xf, &st.doc, &layout, ts, Some(selected)); + }); + output.textures_delta.clear(); + let tint = Color32::from_rgba_unmultiplied(80, 140, 255, 90); + let painted: Vec<_> = output + .shapes + .into_iter() + .filter_map(|s| match s.shape { + egui::Shape::Path(path) if path.fill == tint => { + assert!(path.closed); + assert_eq!(path.stroke, egui::epaint::PathStroke::NONE); + Some(path.points) + } + _ => None, + }) + .collect(); + assert_eq!(painted, expected, "only the two touched owners are tinted; column={column}, merged={merged}"); + assert_eq!(app.session.doc().unwrap().selection, selection); + } + } +} + +/// A selected group lists the text frames inside it for ports. +#[test] +fn grouped_text_frames_get_ports() { + let mut s = designcraft_engine::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [10, 10, 110, 60], "content": "text"})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [10, 80, 110, 130]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [a, b]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let group = doc.item(designcraft_doc::ItemId(g)).unwrap(); + let mut out = Vec::new(); + text_frames_in(group, 0, &mut out); + assert_eq!(out.iter().map(|(it, _)| it.id.0).collect::>(), vec![a], "one text frame in the group"); + // A plain text frame lists itself. + out.clear(); + text_frames_in(out_frame(doc, a), 0, &mut out); + assert_eq!(out.len(), 1); +} + +/// A selected group paints both ports of the overset text frame inside it, on top of the +/// group's own selection marks. +#[test] +fn a_selected_group_paints_both_ports_of_its_text_frame() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let s = &mut app.session; + let text = "far too much text for a frame this small, over and over again ".repeat(8); + let a = s.execute("frame.create", &json!({"rect": [100, 100, 200, 140], "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [100, 200, 200, 260]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [a, b]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("transform.rotate", &json!({"angle": 30, "ids": [g]})).unwrap(); + s.execute("selection.set", &json!({"ids": [g]})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) }; + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_selection(&app, ui.painter(), &xf, &doc, &layout); + }); + output.textures_delta.clear(); + let white: Vec = output + .shapes + .into_iter() + .filter_map(|s| match s.shape { + egui::Shape::Rect(r) if r.fill == Color32::WHITE => Some(r.rect), + _ => None, + }) + .collect(); + for out in [false, true] { + let c = xf.to_screen(designcraft_tools::thread::port_center(&doc, &layout, designcraft_doc::ItemId(a), out, xf.zoom).unwrap()); + let port = white.iter().position(|r| (r.center() - c).length() < 0.01).unwrap_or_else(|| panic!("port (out: {out}) at {c:?}")); + assert!(!white[port + 1..].iter().any(|r| r.contains(c)), "nothing painted later covers the port (out: {out})"); + } +} + +fn out_frame(doc: &Document, id: u64) -> &Item { + doc.item(designcraft_doc::ItemId(id)).unwrap() +} + +/// An overset frame inside a group is listed for the red mark even when nothing is +/// selected; a frame with room, or a hidden one, is not. +#[test] +fn overset_frames_are_found_inside_groups() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let s = &mut app.session; + let frame_with = |s: &mut designcraft_engine::Session, rect: [f64; 4], text: &str| { + s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap() + }; + let tiny = frame_with(s, [10.0, 10.0, 40.0, 16.0], "far too much text for a frame this small, over and over again"); + let roomy = frame_with(s, [10.0, 100.0, 300.0, 300.0], "fits"); + s.execute("selection.set", &json!({"ids": [tiny, roomy]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut out = Vec::new(); + overset_frames(&app, &doc, &doc.spreads[0].items, 0, &mut out); + assert_eq!(out.iter().map(|it| it.id.0).collect::>(), vec![tiny]); + // Hidden: no mark. + app.session.execute("object.hide", &json!({"ids": [tiny]})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + out.clear(); + overset_frames(&app, &doc, &doc.spreads[0].items, 0, &mut out); + assert!(out.is_empty()); +} + +/// The always-on overset mark sits at the frame's out port, a step along its own right edge +/// (so a rotated frame gets it inside its edge, not straight up from the corner), and a +/// selected overset frame gets only the mark its ports draw. +#[test] +fn overset_mark_sits_on_the_out_port_once() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let s = &mut app.session; + let id = s + .execute("frame.create", &json!({"rect": [100, 100, 200, 160], "content": "text", "text": "far too much text for a frame this small, over and over again ".repeat(8)})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("transform.rotate", &json!({"angle": 90, "ids": [id]})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let zoom = 1.0; + let marks = overset_marks(&app, &doc, &layout, &doc.spreads[0].items, zoom, &ported_frames(&app, &doc)); + assert_eq!(marks.len(), 1); + let it = out_frame(&doc, id); + let (a, _) = item_canvas_xf(&doc, &layout, it.id).unwrap(); + let m = a * it.xf; + let r = it.inner_bounds(); + let corner = m * Point::new(r.x1, r.y1); + let edge = (m * Point::new(r.x1, r.y0)) - corner; + let d = marks[0].1 - corner; + assert!((d.x * edge.y - d.y * edge.x).abs() < 1e-6, "the mark lies on the frame's right edge: {d:?} along {edge:?}"); + assert!((d.hypot() - 12.0 / zoom).abs() < 1e-6, "12 screen px from the corner: {d:?}"); + // Selected: the ports draw the mark, so no always-on mark is added. + app.session.execute("selection.set", &json!({"ids": [id]})).unwrap(); + let marks = overset_marks(&app, &doc, &layout, &doc.spreads[0].items, zoom, &ported_frames(&app, &doc)); + assert!(marks.is_empty()); +} + +#[test] +fn right_clicking_a_ruler_sets_that_rulers_units() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + assert_eq!(units(&h), (Unit::Picas, Unit::Picas)); + // Vertical ruler: the current unit is checked; picking one sets only the vertical units. + right_click(&mut h, pos2(rect.min.x - RULER / 2.0, rect.center().y)); + h.get_by_label("✓ Picas"); + h.get_by_label(" Millimeters").click(); + h.run_steps(3); + assert_eq!(units(&h), (Unit::Picas, Unit::Millimeters)); + // Horizontal ruler. + right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); + h.get_by_label("✓ Picas"); + h.get_by_label(" Inches").click(); + h.run_steps(3); + assert_eq!(units(&h), (Unit::Inches, Unit::Millimeters)); + // The corner where the rulers meet sets both, as InDesign's: nothing is checked while + // they differ. + let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0); + right_click(&mut h, corner); + assert!(h.query_by_label("✓ Inches").is_none() && h.query_by_label("✓ Millimeters").is_none()); + let _ = h.get_by_label_contains("Hide Rulers"); + let _ = h.get_by_label(" Lock Zero Point"); + assert!(h.query_by_label(" Delete All Guides on Spread").is_none(), "only on the horizontal ruler"); + h.get_by_label(" Points").click(); + h.run_steps(3); + assert_eq!(units(&h), (Unit::Points, Unit::Points)); + // InDesign's list: no Q or Ha. + right_click(&mut h, corner); + h.get_by_label("✓ Points"); + assert!(h.query_by_label(" Q").is_none() && h.query_by_label(" Ha").is_none()); + let _ = h.get_by_label(" Inches Decimal"); + // The horizontal ruler's menu also deletes the spread's guides; Hide Rulers hides them. + right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); + let _ = h.get_by_label(" Delete All Guides on Spread"); + h.get_by_label_contains("Hide Rulers").click(); + h.run_steps(3); + assert!(!h.state().ui.rulers); + // The page opens no units menu. + right_click(&mut h, rect.center()); + assert!(h.query_by_label(" Points").is_none()); +} + +/// The live-corner widget draws on a selected rectangle frame; clicking it draws the diamonds. +#[test] +fn live_corner_widget_and_diamonds_draw() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap(); + let id = app.session.doc().unwrap().doc.spreads[0].items[0].id; + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(1.0).wgpu().build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + let screen = |h: &Harness<'_, DesignApp>, x: f64, y: f64| { + let app = h.state(); + let layout = CanvasLayout::new(&app.session.doc().unwrap().doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + xf.to_screen(layout.to_canvas(SpreadRef::Doc(0), Point::new(x, y))) + }; + let widget = screen(&h, 300.0, 100.0) + vec2(0.0, 11.5); + let diamond = screen(&h, 100.0, 100.0) + vec2(12.0, 0.0); + let yellow = |h: &mut Harness<'_, DesignApp>, p: Pos2| -> Option { + let img = match h.render() { + Ok(img) => img, + Err(e) => { + eprintln!("skipped: no offscreen renderer ({e})"); + return None; + } + }; + let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32).0; + Some(px[0] > 200 && px[1] > 180 && px[2] < 100) + }; + let Some(w) = yellow(&mut h, widget) else { return }; + assert!(w, "no widget at {widget:?}"); + assert_eq!(yellow(&mut h, diamond), Some(false)); + h.hover_at(widget); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: widget, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); + } + h.run_steps(3); + assert_eq!(yellow(&mut h, diamond), Some(true), "no diamond at {diamond:?}"); + assert_eq!(yellow(&mut h, widget), Some(false)); +} + +/// A harness whose frames are 1 ms apart, so two clicks make a double-click. +fn fast_harness(app: DesignApp) -> Harness<'static, DesignApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(0.001).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn primary(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool) { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(2); +} + +fn corner_drag(h: &mut Harness<'_, DesignApp>, from: Pos2, to: Pos2) { + h.hover_at(from); + h.step(); + primary(h, from, true); + h.event(egui::Event::PointerMoved(from + (to - from) / 2.0)); + h.run_steps(2); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(2); + primary(h, to, false); +} + +fn corner_click(h: &mut Harness<'_, DesignApp>, p: Pos2) { + h.hover_at(p); + h.step(); + primary(h, p, true); + primary(h, p, false); +} + +/// Where the rulers measure from (canvas coordinates): the document's zero point on the +/// spread in view (its first page, for a page origin). +fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option { + ruler_pieces(app, doc, layout, doc.zero_point()).first().map(|p| p.2) +} + +fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] { + h.state().session.doc().unwrap().doc.settings.zero_point +} + +#[test] +fn the_ruler_corner_drags_resets_and_locks_the_zero_point() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + let mut h = fast_harness(app); + let rect = h.state().canvas_rect.unwrap(); + let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0); + // A click that stays in the corner leaves the zero point. + corner_click(&mut h, corner); + assert_eq!(zero_point(&h), [0.0, 0.0]); + // Dragged out, it lands where released, measured from the spread in view. + let dest = rect.min + vec2(80.0, 50.0); + let expected = { + let app = h.state(); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let slot = layout.slots[current_slot(app, &layout).unwrap()]; + let sp = slot.to_spread(Xf::new(rect, app.view().unwrap()).to_canvas(dest)); + let b = st.doc.spread(slot.spread).unwrap().bounds(); + [sp.x - b.x0, sp.y - b.y0] + }; + corner_drag(&mut h, corner, dest); + let zp = zero_point(&h); + assert!((zp[0] - expected[0]).abs() < 0.5 && (zp[1] - expected[1]).abs() < 0.5, "{zp:?} vs {expected:?}"); + assert!(zp[0].abs() > 1.0 && zp[1].abs() > 1.0, "moved: {zp:?}"); + // The rulers measure from the point it was dropped on. + { + let app = h.state(); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let o = ruler_zero(app, &st.doc, &layout).unwrap(); + let on_screen = Xf::new(rect, app.view().unwrap()).to_screen(o); + assert!((on_screen - dest).length() < 0.5, "{on_screen:?} vs {dest:?}"); + } + // A double-click resets it. + corner_click(&mut h, corner); + corner_click(&mut h, corner); + assert_eq!(zero_point(&h), [0.0, 0.0]); + // Locked from the corner's context menu, the corner ignores drags and double-clicks. + right_click(&mut h, corner); + h.get_by_label(" Lock Zero Point").click(); + h.run_steps(3); + assert!(h.state().session.doc().unwrap().doc.settings.zero_point_locked); + corner_drag(&mut h, corner, dest); + assert_eq!(zero_point(&h), [0.0, 0.0]); + // Unlocked again from the same menu. + right_click(&mut h, corner); + h.get_by_label(" Unlock Zero Point").click(); + h.run_steps(3); + corner_drag(&mut h, corner, dest); + assert_ne!(zero_point(&h), [0.0, 0.0]); + h.state_mut().run("view.lockZeroPoint", json!({"on": true})).unwrap(); + corner_click(&mut h, corner); + corner_click(&mut h, corner); + assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset"); +} + +#[test] +fn cmd_dragging_the_ruler_corner_makes_a_guide_each_way() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0); + let dest = rect.min + vec2(120.0, 90.0); + let (r, at) = { + let app = h.state(); + let st = app.session.active().unwrap(); + CanvasLayout::new(&st.doc, false).spread_at(Xf::new(rect, app.view().unwrap()).to_canvas(dest)).unwrap() + }; + h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND)); + h.step(); + corner_drag(&mut h, corner, dest); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.step(); + let doc = h.state().session.doc().unwrap().doc.clone(); + let guides: Vec<_> = doc.spread(r).unwrap().pages.iter().flat_map(|p| p.guides.clone()).collect(); + assert_eq!(guides.len(), 2, "{guides:?}"); + let pos = |o: designcraft_doc::Orientation| guides.iter().find(|g| g.orientation == o).map(|g| g.position).unwrap(); + assert!((pos(designcraft_doc::Orientation::Horizontal) - at.y).abs() < 0.5); + assert!((pos(designcraft_doc::Orientation::Vertical) - at.x).abs() < 0.5); + assert!(guides.iter().all(|g| g.spread)); + assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays"); +} + +/// A guide being dragged out of a ruler says where it is, as the rulers measure it (#1282): +/// from the zero point, in the ruler units, and the label follows the pointer while it moves. +#[test] +fn a_dragged_guide_shows_where_it_is() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + let dest = rect.min + vec2(160.0, 110.0); + let (xf, at) = { + let app = h.state(); + let xf = Xf::new(rect, app.view().unwrap()); + let st = app.session.active().unwrap(); + (xf, CanvasLayout::new(&st.doc, false).spread_at(xf.to_canvas(dest)).unwrap().1) + }; + let units = h.state().session.doc().unwrap().doc.settings.horizontal_units; + for (orientation, label, want) in + [(designcraft_doc::Orientation::Vertical, "X", at.x - 100.0), (designcraft_doc::Orientation::Horizontal, "Y", at.y - 50.0)] + { + let g = GuideDrag { orientation, from: None, at: Some(dest), mods: egui::Modifiers::NONE }; + let (l, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); + assert_eq!(l, label); + assert!((v - want).abs() < 1e-6, "{label}: {v} vs {want}"); + let text = guide_readout(h.state(), &xf, &g).unwrap(); + assert_eq!(text, format!("{label}: {}", designcraft_geom::units::format_measure(v, units))); + } + // While a guide is actually being dragged out of the top ruler, the readout is there. + let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0); + h.hover_at(ruler); + h.step(); + primary(&mut h, ruler, true); + h.event(egui::Event::PointerMoved(dest)); + h.run_steps(2); + let g = h.ctx.data(|d| d.get_temp::(egui::Id::unique(GUIDE_DRAG))).expect("dragging"); + assert_eq!(g.orientation, designcraft_doc::Orientation::Horizontal); + assert!(guide_readout(h.state(), &xf, &g).is_some_and(|t| t.starts_with("Y: "))); + primary(&mut h, dest, false); +} + +/// Over a spread other than the one in the middle of the view, the readout measures that +/// spread, the one the guide is dropped on: it reads the position the guide gets. +#[test] +fn the_guide_readout_measures_the_spread_under_the_pointer() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 5})).unwrap(); + app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); + let h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + let xf = Xf::new(rect, h.state().view().unwrap()); + let st = h.state().session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let current = current_slot(h.state(), &layout).unwrap(); + // A point inside the last spread, well away from the one in view. + let last = layout.slots.last().unwrap(); + assert_ne!(layout.slots.iter().position(|s| s.spread == last.spread), Some(current), "the last spread isn't the one in view"); + let inside = Point::new(last.bounds.center().x, last.bounds.y0 + (last.bounds.y1 - last.bounds.y0) * 0.3); + let (r, sp) = layout.spread_at(inside).unwrap(); + assert_eq!(r, last.spread); + let g = + GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: None, at: Some(xf.to_screen(inside)), mods: egui::Modifiers::NONE }; + let (label, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); + assert_eq!(label, "Y"); + // The guide would be stored at `sp.y` on that spread, which its ruler reads from the zero point. + // (To screen and back in f32: a few hundred-thousandths of a point.) + assert!((v - (sp.y - 50.0)).abs() < 1e-3, "{v} vs {}", sp.y - 50.0); + // An existing guide of another spread can't be dropped there (it only moves on its own + // spread): no readout over this one, a readout over its own. + let first = layout.slots[current].spread; + let moving = GuideDrag { + orientation: designcraft_doc::Orientation::Horizontal, + from: Some((first, 0, 0)), + at: Some(xf.to_screen(inside)), + mods: egui::Modifiers::NONE, + }; + assert!(guide_measure(h.state(), &xf, &moving).is_none(), "an existing guide over another spread"); + let own = layout.slots[current].bounds; + let over_own = Point::new(own.center().x, own.y0 + (own.y1 - own.y0) * 0.3); + let moving_here = GuideDrag { at: Some(xf.to_screen(over_own)), ..moving }; + assert!(guide_measure(h.state(), &xf, &moving_here).is_some(), "over its own spread"); +} + +/// The guide readout stays on the canvas: below right of the pointer in the open, flipped +/// left or up near the right or bottom edge, and inside the canvas in every corner. +#[test] +fn the_guide_readout_stays_inside_the_canvas() { + let area = Rect::from_min_max(pos2(50.0, 40.0), pos2(850.0, 640.0)); + let size = vec2(80.0, 14.0); + let inside = |at: Pos2| { + let r = Rect::from_min_size(at, size).expand(3.0); + r.min.x >= area.min.x - 1e-3 && r.min.y >= area.min.y - 1e-3 && r.max.x <= area.max.x + 1e-3 && r.max.y <= area.max.y + 1e-3 + }; + assert_eq!(readout_at(pos2(400.0, 300.0), size, area), pos2(412.0, 312.0), "in the open: below right"); + let right = readout_at(pos2(845.0, 300.0), size, area); + assert!(right.x + size.x < 845.0 && inside(right), "near the right edge: left of the pointer, {right:?}"); + let bottom = readout_at(pos2(400.0, 636.0), size, area); + assert!(bottom.y + size.y < 636.0 && inside(bottom), "near the bottom: above it, {bottom:?}"); + for p in [area.min, pos2(area.max.x, area.min.y), area.max, pos2(area.min.x, area.max.y), pos2(-500.0, 2000.0)] { + assert!(inside(readout_at(p, size, area)), "{p:?}"); + } + // A canvas narrower than the label: pinned to its top left, not past it. + let tiny = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 10.0)); + assert_eq!(readout_at(pos2(20.0, 5.0), size, tiny), pos2(3.0, 3.0)); +} + +#[test] +fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + // Spread 0: page 1; spread 1: pages 2 and 3. + app.run("file.new", json!({"pages": 3})).unwrap(); + app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); + app.session.prefs.dimensions_include_stroke = false; + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + for (spread, x0) in [(0usize, 136.0), (1, 736.0)] { + let app = h.state_mut(); + let id = app.run("frame.create", json!({"spread": spread, "rect": [x0, 70, x0 + 50.0, 120]})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + // X/Y (Control, Properties and Info panels). + let r = crate::panels::sel_info(app).unwrap().page_rect; + assert!((r.x0 - (x0 - 100.0)).abs() < 1e-6 && (r.y0 - 20.0).abs() < 1e-6, "spread {spread}: {r:?}"); + // The rulers, with that spread in view. + let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); + let slot = layout.slots[spread]; + let v = app.view_mut().unwrap(); + let zoom = v.zoom; + let c = slot.bounds.center(); + v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / zoom, c.y - rect.height() as f64 / 2.0 / zoom); + h.run_steps(2); + let app = h.state(); + let doc = app.session.active().unwrap().doc.clone(); + assert_eq!(current_slot(app, &layout), Some(spread)); + let o = ruler_zero(app, &doc, &layout).unwrap(); + assert!((o.x - slot.bounds.x0 - 100.0).abs() < 1e-6 && (o.y - slot.bounds.y0 - 50.0).abs() < 1e-6, "spread {spread}: {o:?}"); + } +} + +/// Screen position of spread 0's point (x, y). +fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 { + let app = h.state(); + let st = app.session.active().unwrap(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y)) +} + +/// A menu row: a button that isn't a toggle, named by its label, then its shortcut if it has +/// one. Toggle buttons with the same name (the Task Bar's icons) don't match, nor do buttons +/// right of the canvas (the Properties panel's Arrange). +fn menu_row<'h>(h: &'h Harness<'_, DesignApp>, label: &'h str) -> Option> { + let right = f64::from(h.state().canvas_rect.map_or(f32::INFINITY, |r| r.max.x)); + h.query_by(move |n| { + n.role() == egui::accesskit::Role::Button + && n.toggled().is_none() + && n.bounding_box().is_none_or(|b| b.x0 < right) + && n.label().is_some_and(|l| l == label || l.strip_prefix(label).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.contains(' '))) + }) +} + +fn enabled(h: &Harness<'_, DesignApp>, label: &str) -> bool { + use egui_kittest::kittest::NodeT; + !menu_row(h, label).unwrap_or_else(|| panic!("no menu row {label}")).accesskit_node().is_disabled() +} + +fn spread_items(h: &Harness<'_, DesignApp>) -> Vec { + h.state().session.doc().unwrap().doc.spreads[0].items.iter().map(|i| i.id.0).collect() +} + +fn selected(h: &Harness<'_, DesignApp>) -> Vec { + h.state().session.doc().unwrap().selection.items.iter().map(|i| i.0).collect() +} + +#[test] +fn right_clicking_an_object_selects_it_and_its_menu_arranges_it() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("frame.create", json!({"rect": [150, 150, 300, 300]})).unwrap()["id"].as_u64().unwrap(); + let mut h = harness(app); + assert_eq!(selected(&h), [b]); + let on_a = screen_of(&h, 60.0, 60.0); + right_click(&mut h, on_a); + assert_eq!(selected(&h), [a], "the object under the pointer is selected first"); + // An empty frame's menu: Content, but no Fitting (nothing to fit) and no text frame entries. + assert!(menu_row(&h, "Content").is_some()); + assert!(menu_row(&h, "Fitting").is_none() && menu_row(&h, "Text Frame Options…").is_none()); + // Paste is available with nothing copied here: the system clipboard may hold another app's text. + assert!(enabled(&h, "Copy") && enabled(&h, "Paste")); + menu_row(&h, "Arrange").unwrap().click(); + h.run_steps(3); + menu_row(&h, "Bring to Front").unwrap().click(); + h.run_steps(3); + assert_eq!(spread_items(&h), [b, a]); + assert!(menu_row(&h, "Arrange").is_none(), "choosing an entry closes the menu"); +} + +#[test] +fn right_clicking_empty_canvas_offers_paste_after_a_copy() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.select_tool("rectangleFrame"); + let mut h = harness(app); + let empty = screen_of(&h, 400.0, 500.0); + right_click(&mut h, empty); + assert_eq!(selected(&h), [a], "a right-click on nothing keeps the selection"); + assert!(menu_row(&h, "Arrange").is_none(), "the page menu, not the object menu"); + assert!(enabled(&h, "Paste in Place")); + assert!(menu_row(&h, "✓ Show/Hide Rulers").is_some(), "toggles show their state"); + // Escape closes the menu and does nothing else: the tool would deselect, the shortcuts + // would switch to the Selection tool. + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(menu_row(&h, "Paste in Place").is_none()); + assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a])); + right_click(&mut h, empty); + menu_row(&h, "Paste").unwrap().click(); + h.run_steps(3); + assert_eq!(spread_items(&h).len(), 2); +} + +#[test] +fn right_clicking_another_object_while_the_menu_is_open_reopens_it_there() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 600, 200, 760]})).unwrap()["id"].as_u64().unwrap(); + let mut h = harness(app); + // The menu opens down from A, with the pointer on its first row (no submenu open); B is below it. + let (on_a, on_b) = (screen_of(&h, 60.0, 60.0), screen_of(&h, 50.0, 700.0)); + right_click(&mut h, on_a); + assert_eq!(selected(&h), [a]); + assert!(menu_row(&h, "Arrange").is_some()); + right_click(&mut h, on_b); + assert_eq!(selected(&h), [b]); + assert!(menu_row(&h, "Arrange").is_some(), "the menu reopens at the new click"); +} + +#[test] +fn a_context_menu_in_one_pane_keeps_the_keys_from_the_other() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("rectangleFrame"); + app.split = true; + let mut h = harness(app); + // The focused pane is the left one; this point is near its right edge, away from the frame. + let left = h.state().canvas_rect.unwrap(); + right_click(&mut h, pos2(left.max.x - 40.0, left.center().y)); + assert!(menu_row(&h, "Paste in Place").is_some()); + // Escape closes the left pane's menu before the right pane handles the keys. + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(menu_row(&h, "Paste in Place").is_none()); + assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a])); +} + +#[test] +fn right_clicking_text_keeps_the_selected_text_or_places_the_caret() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 400, 200], "content": "text"})).unwrap(); + app.select_tool("type"); + app.run("text.insert", json!({"text": "Hello world"})).unwrap(); + let sid = *app.session.doc().unwrap().doc.stories.keys().next().unwrap(); + app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap(); + let mut h = harness(app); + let text_sel = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.as_ref().map(|t| (t.anchor, t.focus)); + // Inside "Hello": the selection stays. + let inside = screen_of(&h, 45.0, 44.0); + right_click(&mut h, inside); + assert_eq!(text_sel(&h), Some((0, 5))); + assert!(menu_row(&h, "Paste without Formatting").is_some(), "the text menu"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + // Past the end of the line: the caret goes there. + let past_end = screen_of(&h, 300.0, 44.0); + right_click(&mut h, past_end); + assert_eq!(text_sel(&h), Some((11, 11))); + assert!(menu_row(&h, "Paste without Formatting").is_some()); +} + +#[test] +fn rows_hidden_in_the_menu_bar_are_hidden_in_context_menus() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap(); + app.ui.hidden_menu_items.push(crate::menus::menu_key("Object/Arrange", "Bring to Front")); + let mut h = harness(app); + let on_frame = screen_of(&h, 60.0, 60.0); + right_click(&mut h, on_frame); + menu_row(&h, "Arrange").unwrap().click(); + h.run_steps(3); + assert!(menu_row(&h, "Bring to Front").is_none()); + assert!(menu_row(&h, "Send to Back").is_some()); + assert!(h.query_by_label("Show All Menu Items").is_some()); +} + +#[test] +fn a_secondary_drag_neither_moves_marquees_nor_draws() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let mut h = harness(app); + // A secondary-button drag between spread points. + let drag = |h: &mut Harness<'_, DesignApp>, from: (f64, f64), to: (f64, f64)| { + let (from, to) = (screen_of(h, from.0, from.1), screen_of(h, to.0, to.1)); + h.hover_at(from); + h.step(); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.step(); + for t in [0.25, 0.5, 0.75, 1.0] { + h.event(egui::Event::PointerMoved(from + (to - from) * t)); + h.step(); + } + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + }; + let xf = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.item(designcraft_doc::ItemId(a)).unwrap().xf; + let before = xf(&h); + // Selection tool: on the object (no move), and from empty page across it (no marquee). + drag(&mut h, (100.0, 100.0), (300.0, 300.0)); + assert_eq!(xf(&h), before); + h.state_mut().run("edit.deselectAll", json!({})).unwrap(); + drag(&mut h, (400.0, 400.0), (20.0, 20.0)); + assert!(selected(&h).is_empty()); + // Rectangle Frame tool: no frame. + h.state_mut().select_tool("rectangleFrame"); + drag(&mut h, (300.0, 300.0), (500.0, 500.0)); + assert_eq!(spread_items(&h), [a]); +} + +/// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a +/// row must land within the double-click delay). +fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": text})).unwrap(); + let id = r["id"].as_u64().unwrap(); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + (h, id) +} + +/// The screen point over the first line of frame `id` where a click puts the caret at a byte +/// in `bytes`. +fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range) -> Pos2 { + let mut x = 74.0; + let p = loop { + assert!(x < 400.0, "no point on the first line hits {bytes:?}"); + h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap(); + if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) { + break Point::new(x, 80.0); + } + x += 1.0; + }; + h.state_mut().run("edit.deselectAll", json!({})).unwrap(); + let app = h.state(); + let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p); + Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c) +} + +fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); + } +} + +fn selected_range(h: &Harness<'_, DesignApp>) -> std::ops::Range { + h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default() +} + +#[test] +fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() { + let text = "One two. Three four! Five six.\nSecond para here."; + let (mut h, id) = typing(text); + // Inside "Three": double-click selects the word, then line and paragraph with return. + let p = screen_at(&mut h, id, 10..14); + h.hover_at(p); + h.step(); + let mut got = vec![]; + for _ in 0..5 { + click(&mut h, p); + let r = selected_range(&h); + got.push(text[r].to_string()); + } + assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}"); + assert!(got[0].is_empty(), "one click places the caret: {got:?}"); +} + +#[test] +fn esc_that_closes_a_dialog_keeps_the_type_tool_and_its_text_selection() { + let (mut h, id) = typing("One two three"); + // A click in the text gives the canvas the keyboard focus, as when typing. + let p = screen_at(&mut h, id, 5..6); + h.hover_at(p); + h.step(); + for _ in 0..2 { + click(&mut h, p); + } + h.run_steps(4); + let words = selected_range(&h); + assert_eq!(words, 4..7, "the double-click selects \"two\""); + let app = h.state_mut(); + let name = app.run("style.character.create", json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string(); + app.ui.dialog = Some(crate::dialogs::Dialog::new("characterStyleOptions", json!({"name": name}))); + h.run_steps(3); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none(), "Esc closes the dialog"); + assert_eq!((h.state().session.tool_id(), selected_range(&h)), ("type", words)); + // With no dialog open, Esc in the text still leaves it for the Selection tool. + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().session.tool_id(), "selection"); +} + +#[test] +fn slow_clicks_do_not_add_up() { + let (mut h, id) = typing("One two. Three four!"); + let p = screen_at(&mut h, id, 10..14); + h.hover_at(p); + h.step(); + for _ in 0..3 { + click(&mut h, p); + h.run_steps(30); + } + assert!(selected_range(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected_range(&h)); +} + +/// A viewport wider than the GPU's largest texture: the canvas texture is sampled down, and an +/// edit repaints it whole. A region repainted in view pixels would land in the wrong place, +/// or outside the texture (a wgpu validation error). A view that fits is still patched. +#[test] +fn an_edit_repaints_a_canvas_texture_sampled_down_to_the_gpu_limit_whole() { + for (width, sampled_down) in [(1440.0, false), (2600.0, true)] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Text"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(width, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(6); + let limit = h.ctx.input(|i| i.max_texture_side); + let size = h.state().canvas.texture.as_ref().map(|t| t.size()).unwrap(); + assert!(size[0] <= limit && size[1] <= limit, "{size:?}"); + let shown = h.state().canvas.shown.unwrap().size; + assert_eq!(shown.0 > limit as f32, sampled_down, "view {shown:?}, limit {limit}"); + let patches = h.state().canvas.patches; + // A small edit: one more character in the frame. + h.state_mut().run("text.insert", json!({"story": frame["story"], "at": 4, "text": "s"})).unwrap(); + h.run_steps(6); + assert_eq!(h.state().canvas.patches == patches, sampled_down, "width {width}"); + assert_eq!(h.state().canvas.texture.as_ref().map(|t| t.size()), Some(size)); + } +} + +/// ⌥E then I types "í" on a Mac: the input method composes the dead key's accent, which +/// it does only for a window that turned it on. The canvas never did, so ⌥E typed "e". +#[test] +fn dead_keys_compose_through_the_input_method() { + let (mut h, id) = typing("T"); + h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [390.0, 80.0]})).unwrap(); + h.run_steps(2); + assert!(h.output().platform_output.ime.is_some(), "a text caret turns the input method on"); + h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "´".into(), active_range_chars: None })); + h.run_steps(2); + let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.stories.values().map(|s| s.text.clone()).collect::(); + assert_eq!(text(&h), "T´", "the accent being composed shows in the story"); + assert!(h.state().session.tool_composing(), "and is marked as composed, not typed"); + h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None })); + h.event(egui::Event::Ime(egui::ImeEvent::Commit("í".into()))); + h.run_steps(2); + assert_eq!(text(&h), "Tí"); + assert!(!h.state().session.tool_composing()); + // Moving the caret mid-composition keeps the accent as typed and tells the input method + // to drop its copy. + h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "˜".into(), active_range_chars: None })); + h.run_steps(2); + h.state_mut().run("text.move", json!({"dir": "left"})).unwrap(); + h.step(); + assert_eq!(text(&h), "Tí˜"); + assert!(!h.state().session.tool_composing()); + assert!(h.output().platform_output.ime.as_ref().is_some_and(|i| i.should_interrupt_composition)); + assert!(h.state_mut().take_ime_discard()); + // Another tool takes no text: the input method is off. + h.state_mut().run("tool.select", json!({"tool": "selection"})).unwrap(); + h.run_steps(2); + assert!(h.output().platform_output.ime.is_none()); +} + +#[test] +fn tools_show_their_own_cursors_over_the_page() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut h = harness(app); + let p = h.state().canvas_rect.unwrap().center(); + let mut shown = |tool: &str| { + h.state_mut().run("tool.select", json!({"tool": tool})).unwrap(); + h.hover_at(p); + h.run_steps(2); + let out = &h.output().platform_output; + (out.cursor_icon, out.cursor_image.clone()) + }; + let (pen, direct, text, selection) = (shown("pen"), shown("directSelection"), shown("type"), shown("selection")); + let ppp = h.ctx.pixels_per_point(); + let images = &mut h.state_mut().cursors; + match crate::cursors::mode() { + crate::cursors::Mode::Os => { + assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen"); + assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection"); + assert_eq!(selection.1, images.get(Cursor::Arrow, ppp), "Selection"); + assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor"); + } + crate::cursors::Mode::Painted => { + assert_eq!((pen.0, direct.0, selection.0), (egui::CursorIcon::None, egui::CursorIcon::None, egui::CursorIcon::None)); + } + crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)), + } +} + +#[test] +fn document_grid_is_drawn_where_points_snap_to_it() { + use designcraft_tools::{SnapView, ToolContext}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let sr = SpreadRef::Doc(0); + // Where the grid snaps a point in the first page (72 pt / 8 subdivisions = 9 pt). + let page = doc.spreads[0].pages[0].bounds(); + let sel = Selection::default(); + let cx = ToolContext { + doc: &doc, + selection: &sel, + cache: &app.session.cache, + layout: &layout, + zoom: 1.0, + layer: doc.layers[0].id, + snap: SnapView { snap_to_document_grid: true, zone_px: 20.0, ..SnapView::OFF }, + unit: Unit::Points, + stroke_in_front: false, + }; + let (snapped, _) = designcraft_tools::snap::snap_point(&cx, sr, Point::new(page.x0 + 31.3, page.y0 + 47.9)); + assert_eq!((snapped.x - page.x0, snapped.y - page.y0), (27.0, 45.0)); + // Render 40 × 40 pt around it at 4 px/pt. + let scale = 4.0; + let corner = layout.xf(sr) * Point::new(snapped.x - 20.0, snapped.y - 20.0); + let view = Affine::scale(scale) * Affine::translate((-corner.x, -corner.y)); + let placed: Vec<_> = layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect(); + let render = |app: &DesignApp| { + let opts = screen_options(app, &layout, false, 1.0); + designcraft_render::Renderer::new().render(&doc, &app.session.cache, &placed, 160, 160, view, &opts) + }; + // The snapped point is at pixel (80, 80); halfway to the next line is 18 px further. + let darkest = |img: &designcraft_render::Rendered, xs: [u32; 2], ys: [u32; 2]| { + (xs[0]..xs[1]).flat_map(|x| (ys[0]..ys[1]).map(move |y| (x, y))).map(|(x, y)| img.pixel(x, y)[0]).min().unwrap() + }; + let off = render(&app); + assert_eq!(darkest(&off, [78, 82], [60, 64]), 255, "no grid while it is hidden"); + app.run("view.documentGrid", json!({})).unwrap(); + let on = render(&app); + assert!(darkest(&on, [79, 81], [60, 64]) < 250, "a vertical line at the snapped x"); + assert!(darkest(&on, [60, 64], [79, 81]) < 250, "a horizontal line at the snapped y"); + assert_eq!(darkest(&on, [96, 100], [96, 100]), 255, "nothing between lines"); + // Preview hides it. + app.ui.screen_mode = ScreenMode::Preview; + assert!(screen_options(&app, &layout, true, 1.0).document_grid.is_empty()); +} + +/// egui moves keyboard focus on a plain arrow key or Tab, and Space/Return then clicks the +/// focused widget (e.g. the status bar's spread buttons) while typing still reaches the text. +#[test] +fn arrow_keys_and_tab_keep_keyboard_focus_on_the_canvas() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap(); + app.select_tool("type"); + let mut h = harness(app); + let p = { + let app = h.state(); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(100.0, 60.0)) + }; + h.hover_at(p); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); + } + h.run_steps(2); + let focus = h.ctx.memory(|m| m.focused()); + assert!(focus.is_some(), "a click on the canvas takes keyboard focus"); + let view = *h.state().view().unwrap(); + for key in [egui::Key::ArrowDown, egui::Key::Space, egui::Key::ArrowRight, egui::Key::Enter, egui::Key::Tab, egui::Key::Escape] { + h.key_press(key); + if key == egui::Key::Space { + h.event(egui::Event::Text(" ".into())); + } + h.run_steps(2); + assert_eq!(h.ctx.memory(|m| m.focused()), focus, "{key:?} keeps keyboard focus on the canvas"); + } + let v = *h.state().view().unwrap(); + assert_eq!((v.origin, v.zoom), (view.origin, view.zoom), "the view stays where it was"); + let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone(); + assert_eq!(text, "Hello \n\t", "Space, Return and Tab reach the text"); +} + +#[test] +fn rulers_open_no_units_menu_without_a_document() { + let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default())); + let Some(rect) = h.state().canvas_rect else { return }; + right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); + assert!(h.query_by_label(" Points").is_none()); +} + +/// One frame of the whole app with `events`; returns what it asks of the system IME. +fn ime_frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec) -> Option { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + out.platform_output.ime +} + +/// An edit patches the canvas texture in place only while that texture is at full resolution: +/// past the GPU's texture limit `upload` shrinks it, and a full-resolution patch written into +/// it is a renderer validation error. +#[test] +fn edits_patch_the_canvas_only_at_full_resolution() { + for (max_side, patches) in [(None, true), (Some(1024), false)] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp| { + // Wider than the limit (egui's font atlas needs at least 1024). + let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1900.0, 900.0))), ..Default::default() }; + if let Some(m) = max_side { + raw.max_texture_side = Some(m); + } + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + app.run("file.new", json!({})).unwrap(); + for _ in 0..3 { + frame(&mut app); + } + app.run("frame.create", json!({"rect": [36, 36, 60, 60]})).unwrap(); + frame(&mut app); + let size = app.canvas.texture.as_ref().unwrap().size(); + assert!(max_side.is_none_or(|m| size[0] <= m && size[1] <= m), "{size:?}"); + assert_eq!(app.canvas.patches > 0, patches, "limit {max_side:?}"); + } +} + +/// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames +/// drawn; returns the story id. +fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value { + app.run("file.new", json!({})).unwrap(); + let f = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": text})).unwrap(); + let sid = f["story"].clone(); + app.session.execute("text.select", &json!({"story": sid, "anchor": text.len(), "focus": text.len()})).unwrap(); + app.select_tool("type"); + for _ in 0..4 { + ime_frame(app, ctx, vec![]); + } + sid +} + +fn story_text(app: &mut DesignApp, sid: &Value) -> String { + app.session.execute("story.get", &json!({"story": sid})).unwrap()["text"].as_str().unwrap().to_string() +} + +/// Spread point `p` on screen. +fn on_screen(app: &DesignApp, p: Point) -> Pos2 { + let st = app.session.active().unwrap(); + let c = CanvasLayout::new(&st.doc, st.editing_parents).to_canvas(SpreadRef::Doc(0), p); + Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c) +} + +fn preedit(t: &str, c: usize) -> egui::Event { + egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) }) +} + +/// Extract `(surrounding text, cursor, anchor)` from an IME output. +fn ime_payload(ime: &egui::output::IMEOutput) -> Option<(&str, usize, usize)> { + ime.surrounding_text.available().map(|p| (p.text.as_str(), p.cursor, p.anchor)) +} + +/// Set an engine text selection for a test fixture. +fn text_selection(app: &mut DesignApp, sid: &Value, anchor: usize, focus: usize) { + app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": focus})).unwrap(); +} + +struct NativeClickFixture { + app: DesignApp, + ctx: egui::Context, + target: Value, + old: Value, + at: Pos2, + focus: usize, +} + +/// Build the old and target stories, measure an interior target caret, and leave the old story selected before the click. +fn native_gui_click_fixture() -> NativeClickFixture { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let old = typing_app(&mut app, &ctx, "Old story"); + let frame = app.run("frame.create", json!({"rect": [36, 280, 300, 400], "content": "text", "text": "Target story"})).unwrap(); + let target = frame["story"].clone(); + // Measure an interior first-word caret through the engine, rather than guessing a + // font-dependent screen pixel or clicking the frame's resize border. + let (point, focus) = (50..180) + .find_map(|x| { + app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap(); + let sel = app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!(sel.story.0, target.as_u64().unwrap()); + (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus)) + }) + .expect("an interior point in the target's first word"); + text_selection(&mut app, &old, "Old story".len(), "Old story".len()); + for _ in 0..4 { + ime_frame(&mut app, &ctx, vec![]); + } + let at = on_screen(&app, point); + assert!(app.canvas_rect.unwrap().contains(at)); + ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert_eq!(app.session.doc().unwrap().selection.text.unwrap().story.0, old.as_u64().unwrap()); + NativeClickFixture { app, ctx, target, old, at, focus } +} + +/// Build a primary pointer press or release event at a position. +fn native_gui_button(pos: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// The 37-byte Devanagari line the native run had in the previous story. +const NATIVE_GUI_OLD_DEVANAGARI: &str = "नमस्ते दुनिया"; + +/// The click fixture with the non-empty selection in the previous story that the native +/// Windows run had (37-byte Devanagari, 0..37). A non-empty selection shows the contextual +/// task bar; keep it present but clear of the target click. +fn native_gui_selected_old_click_fixture() -> NativeClickFixture { + let mut f = native_gui_click_fixture(); + text_selection(&mut f.app, &f.old, 0, "Old story".len()); + f.app.run("text.insert", json!({"text": NATIVE_GUI_OLD_DEVANAGARI})).unwrap(); + text_selection(&mut f.app, &f.old, 0, NATIVE_GUI_OLD_DEVANAGARI.len()); + for _ in 0..4 { + ime_frame(&mut f.app, &f.ctx, vec![]); + } + let sel = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((sel.story.0, sel.anchor, sel.focus), (f.old.as_u64().unwrap(), 0, NATIVE_GUI_OLD_DEVANAGARI.len())); + assert_eq!(NATIVE_GUI_OLD_DEVANAGARI.len(), 37, "the native fixture's Devanagari line was 37 UTF-8 bytes"); + assert!(!sel.is_caret(), "the previous story's selection is non-empty"); + assert!(!context_menu_open(&f.ctx), "no context menu owns this frame's keys"); + assert!(f.app.ui.dialog.is_none() && f.app.ui.palette.is_none(), "no modal owns the keyboard"); + assert!(!f.ctx.text_edit_focused(), "no text field owns the keyboard"); + assert_eq!(f.app.pane, f.app.focus_pane, "the canvas pane takes the keyboard"); + let task_bar = egui::Id::unique(("task_bar", f.ctx.viewport_id(), f.app.pane)); + let bar = f.ctx.memory(|m| m.area_rect(task_bar)).expect("the old selection shows the floating task bar"); + assert!(!bar.contains(f.at), "the floating task bar does not cover the target click at {bar:?}"); + f +} + +/// Run one raw event batch, optionally force a discarded pass, and return the pointer edges observed by each pass. +fn native_gui_input(f: &mut NativeClickFixture, events: Vec, discard: bool) -> Vec<(bool, bool, bool)> { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() }; + let mut edges = Vec::new(); + let mut out = f.ctx.run_ui(raw, |ui| { + edges.push(ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.press_origin().is_some()))); + f.app.logic(ui.ctx()); + f.app.ui(ui); + if discard && edges.len() == 1 { + ui.ctx().request_discard("native same-batch click exactly-once regression"); + } + }); + if discard { + assert_eq!(out.platform_output.num_completed_passes, 2, "the requested discarded pass actually ran"); + } + out.textures_delta.clear(); + edges +} + +/// Assert that the primary button, canvas press state and tool gesture are all released. +fn native_gui_released(f: &NativeClickFixture) { + assert!(!f.ctx.input(|i| i.pointer.primary_down()), "the native primary button is up"); + let down = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap_or(false); + assert!(!down, "the canvas retained a released pointer"); + assert!(!f.app.session.tool_busy(), "a released click must not leave a tool gesture"); +} + +/// Create an independently measured second-story caret farther apart than the double-click distance. +fn native_gui_second_click_target(f: &mut NativeClickFixture) -> (Value, Pos2, usize) { + let frame = f.app.run("frame.create", json!({"rect": [330, 280, 575, 400], "content": "text", "text": "Second story"})).unwrap(); + let story = frame["story"].clone(); + let (point, focus) = (345..465) + .find_map(|x| { + f.app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap(); + let sel = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!(sel.story.0, story.as_u64().unwrap()); + (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus)) + }) + .expect("an independently measured interior caret in the second story"); + text_selection(&mut f.app, &f.old, "Old story".len(), "Old story".len()); + for _ in 0..4 { + ime_frame(&mut f.app, &f.ctx, vec![]); + } + let at = on_screen(&f.app, point); + assert!(f.app.canvas_rect.unwrap().contains(f.at)); + assert!(f.app.canvas_rect.unwrap().contains(at)); + let max_click_dist = f.ctx.options(|o| o.input_options.max_click_dist); + assert!((at - f.at).length() > max_click_dist, "the two target presses must not form a double click"); + (story, at, focus) +} + +/// Two completed clicks in one batch use the last press once, emit one caret/release pair, add no history, and type at the final caret. +#[test] +fn native_gui_two_completed_clicks_use_last_primary_press_once() { + for reverse in [false, true] { + for discard in [false, true] { + let mut f = native_gui_click_fixture(); + let (second, second_at, second_focus) = native_gui_second_click_target(&mut f); + let (first_at, last_at, final_story, final_focus) = + if reverse { (second_at, f.at, f.target.clone(), f.focus) } else { (f.at, second_at, second.clone(), second_focus) }; + let initial = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((initial.story.0, initial.anchor, initial.focus), (f.old.as_u64().unwrap(), "Old story".len(), "Old story".len())); + let undo = f.app.session.doc().unwrap().history.undo.len(); + let journal = f.app.session.journal.len(); + let edges = native_gui_input( + &mut f, + vec![ + egui::Event::PointerMoved(first_at), + native_gui_button(first_at, true), + native_gui_button(first_at, false), + egui::Event::PointerMoved(last_at), + native_gui_button(last_at, true), + native_gui_button(last_at, false), + ], + discard, + ); + assert_eq!(edges[0], (true, true, false), "both completed clicks leave no held origin"); + assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay either press"); + let sel = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!( + (sel.story.0, sel.anchor, sel.focus), + (final_story.as_u64().unwrap(), final_focus, final_focus), + "reverse={reverse}, discard={discard}" + ); + let commands = &f.app.session.journal[journal..]; + assert_eq!( + commands.iter().filter(|(id, _)| id == "text.placeCaret").count(), + 1, + "one aggregate canvas selection, reverse={reverse}, discard={discard}" + ); + assert_eq!( + commands.iter().filter(|(id, _)| id == "text.release").count(), + 1, + "one corresponding release, reverse={reverse}, discard={discard}" + ); + let clicks = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one recovered canvas press"); + assert_eq!(clicks.n, 1, "separated clicks and discarded passes must not select a word"); + assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "pointer selection adds no document history"); + native_gui_released(&f); + native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false); + let mut target_text = "Target story".to_owned(); + let mut second_text = "Second story".to_owned(); + if reverse { + target_text.insert(final_focus, '!'); + } else { + second_text.insert(final_focus, '!'); + } + assert_eq!(story_text(&mut f.app, &f.target), target_text); + assert_eq!(story_text(&mut f.app, &second), second_text); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "typing at the final caret is one edit"); + native_gui_released(&f); + } + } +} + +/// A non-finite final press rejects the click instead of reviving an earlier valid press; later motion cannot drag. +#[test] +fn native_gui_nonfinite_final_press_cannot_reuse_an_earlier_click() { + for discard in [false, true] { + let mut f = native_gui_click_fixture(); + let at = f.at; + let initial = f.app.session.doc().unwrap().selection.text; + let undo = f.app.session.doc().unwrap().history.undo.len(); + let journal = f.app.session.journal.len(); + let edges = native_gui_input( + &mut f, + vec![ + egui::Event::PointerMoved(at), + native_gui_button(at, true), + native_gui_button(at, false), + native_gui_button(pos2(f32::NAN, at.y), true), + egui::Event::PointerMoved(at), + native_gui_button(at, false), + ], + discard, + ); + assert_eq!(edges[0], (true, true, false)); + assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay malformed input"); + assert_eq!( + f.app.session.doc().unwrap().selection.text, + initial, + "discard={discard}: reject the last press instead of reviving an earlier valid one" + ); + assert!(f.app.session.journal[journal..].iter().all(|(id, _)| id != "text.placeCaret" && id != "text.release")); + assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo); + assert_eq!(story_text(&mut f.app, &f.target), "Target story"); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + native_gui_released(&f); + native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false); + assert_eq!(f.app.session.doc().unwrap().selection.text, initial, "motion after the invalid released press cannot drag"); + native_gui_released(&f); + } +} + +/// A same-batch click switches story exactly once; typing, undo and redo affect only the target story, including discarded-pass runs. +#[test] +fn native_gui_same_batch_click_switches_story_once_before_typing() { + for discard in [false, true] { + let mut f = native_gui_click_fixture(); + let undo = f.app.session.doc().unwrap().history.undo.len(); + let at = f.at; + let edges = native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], discard); + assert_eq!(edges[0], (true, true, false), "the real input consumed both edges and cleared the origin"); + assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "a discarded pass must not replay the press"); + let selection = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((selection.story.0, selection.anchor, selection.focus), (f.target.as_u64().unwrap(), f.focus, f.focus), "discard={discard}"); + let clicks = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click"); + assert_eq!(clicks.n, 1, "discard={discard}: replay must not turn a caret into word selection"); + native_gui_released(&f); + assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "a click is not a document edit"); + let end = |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + native_gui_input(&mut f, vec![end(true), end(false)], false); + let caret = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((caret.story.0, caret.focus), (f.target.as_u64().unwrap(), "Target story".len())); + native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false); + assert_eq!(story_text(&mut f.app, &f.target), "Target story!"); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "one typed edit, including discarded-pass control"); + f.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(story_text(&mut f.app, &f.target), "Target story"); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + f.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(story_text(&mut f.app, &f.target), "Target story!"); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + native_gui_released(&f); + } +} + +/// The native Windows failure: with a non-empty selection in another story, a click that +/// switches stories followed by End in the same job left the new story's caret at the click +/// point. End in a later job worked. Drive the actual app UI and actual pointer/key events in +/// one batch, in split batches, and with End while the press is still held; discard a pass to +/// cover replay. The End press must reach the type tool once and win over the click, wherever +/// the pointer release falls, and typing must go there once. +#[test] +fn native_gui_click_then_end_in_one_batch_keeps_the_target_caret_at_the_story_end() { + let names = ["same batch, click events first", "click batch then End batch", "End while the press is held"]; + for (layout, name) in names.into_iter().enumerate() { + for discard in [false, true] { + let mut f = native_gui_selected_old_click_fixture(); + let (at, target, old) = (f.at, f.target.clone(), f.old.clone()); + let undo = f.app.session.doc().unwrap().history.undo.len(); + let journal = f.app.session.journal.len(); + let moved = || egui::Event::PointerMoved(at); + let down = || native_gui_button(at, true); + let up = || native_gui_button(at, false); + let end = |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + let batches: Vec> = match layout { + 0 => vec![vec![moved(), down(), up(), end(true), end(false)]], + 1 => vec![vec![moved(), down(), up()], vec![end(true), end(false)]], + _ => vec![vec![moved(), down()], vec![end(true)], vec![up(), end(false)]], + }; + for events in batches { + native_gui_input(&mut f, events, discard); + } + let selection = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!( + (selection.story.0, selection.anchor, selection.focus), + (target.as_u64().unwrap(), "Target story".len(), "Target story".len()), + "{name}, discard={discard}: End must win after the click, wherever the release falls" + ); + let commands = &f.app.session.journal[journal..]; + assert_eq!( + commands.iter().filter(|(id, _)| id == "text.move").count(), + 1, + "{name}, discard={discard}: the End press reached the type tool once" + ); + let clicks = f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click"); + assert_eq!(clicks.n, 1, "{name}, discard={discard}: a discarded pass must not replay the press as a word selection"); + native_gui_released(&f); + native_gui_input(&mut f, vec![egui::Event::Text("!".into())], discard); + assert_eq!(story_text(&mut f.app, &target), "Target story!", "{name}, discard={discard}: typing lands at the End caret once"); + assert_eq!(story_text(&mut f.app, &old), NATIVE_GUI_OLD_DEVANAGARI); + assert_eq!( + f.app.session.journal[journal..].iter().filter(|(id, _)| id == "text.insert").count(), + 1, + "{name}, discard={discard}: the text event is not replayed" + ); + assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "{name}, discard={discard}: one edit"); + } + } +} + +/// Pointer ownership survives a split press/move/release; a real drag selects, release ends it, and later motion cannot continue it. +#[test] +fn native_gui_split_click_and_drag_release_keep_pointer_ownership() { + for drag in [false, true] { + let mut f = native_gui_click_fixture(); + let at = f.at; + native_gui_input(&mut f, vec![native_gui_button(at, true)], false); + let sel = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((sel.story.0, sel.focus), (f.target.as_u64().unwrap(), f.focus)); + assert!(f.ctx.input(|i| i.pointer.primary_down())); + assert!(f.ctx.data(|d| d.get_temp::(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap()); + if drag { + let moved = at + vec2(60.0, 0.0); + native_gui_input(&mut f, vec![egui::Event::PointerMoved(moved)], false); + let sel = f.app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!(sel.story.0, f.target.as_u64().unwrap()); + assert!(!sel.is_caret(), "a real held drag selects text"); + } + let release = if drag { pos2(-20.0, at.y) } else { at }; + native_gui_input(&mut f, vec![egui::Event::PointerMoved(release), native_gui_button(release, false)], false); + native_gui_released(&f); + let selection = f.app.session.doc().unwrap().selection.text; + native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false); + assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "motion after release cannot continue the old drag"); + assert_eq!(story_text(&mut f.app, &f.target), "Target story"); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + } +} + +/// An unowned outside press, and a press that dismisses an open menu, cannot move the selection or edit either story. +#[test] +fn native_gui_outside_press_and_open_menu_do_not_click_through() { + for menu in [false, true] { + let mut f = native_gui_click_fixture(); + let at = f.at; + let selection = f.app.session.doc().unwrap().selection.text; + if menu { + let blank = f.app.canvas_rect.unwrap().max - vec2(30.0, 30.0); + for pressed in [true, false] { + let event = egui::Event::PointerButton { pos: blank, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; + native_gui_input(&mut f, vec![egui::Event::PointerMoved(blank), event], false); + } + assert!(context_menu_open(&f.ctx), "the actual secondary click opened the canvas menu"); + assert_eq!(f.app.session.doc().unwrap().selection.text, selection); + native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], false); + } else { + let outside = pos2(-20.0, -20.0); + assert!(!f.app.canvas_rect.unwrap().contains(outside)); + native_gui_input( + &mut f, + vec![ + egui::Event::PointerMoved(outside), + native_gui_button(outside, true), + egui::Event::PointerMoved(at), + native_gui_button(at, false), + ], + false, + ); + } + assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "menu={menu}: an unowned press cannot move the old caret"); + assert_eq!(story_text(&mut f.app, &f.target), "Target story"); + assert_eq!(story_text(&mut f.app, &f.old), "Old story"); + native_gui_released(&f); + } +} + +/// Font inventory distinguishes exact bundled faces, missing styles and missing families without accepting installed or injected substitutes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_gui_font_inventory_keeps_exact_regular_and_missing_style_diagnostics() { + if designcraft_fonts::CRAFT_FONTS.is_empty() { + assert!(std::env::var_os("CRAFT_FONTS_REQUIRED").is_none(), "required canonical fonts were not embedded"); + return; // The supported optional-input build has no central document fonts. + } + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + for (family, text) in [("Noto Sans Hebrew", "שלום"), ("Noto Sans Devanagari", "नमस्ते")] { + assert!(designcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == family && f.style == "Regular"), "canonical {family} Regular absent"); + for style in ["Regular", "Unavailable Native GUI Style"] { + let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": text.len()})).unwrap(); + app.run("type.char", json!({"fontFamily": family, "fontStyle": style})).unwrap(); + } + } + let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "Missing"})).unwrap(); + app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 7})).unwrap(); + app.run("type.char", json!({"fontFamily": "Unavailable Native GUI Family", "fontStyle": "Regular"})).unwrap(); + let inventory = app.run("font.list", json!({})).unwrap(); + let rows = inventory.as_array().unwrap(); + assert_eq!(rows.len(), 5, "{inventory}"); + for family in ["Noto Sans Hebrew", "Noto Sans Devanagari"] { + for style in ["Regular", "Unavailable Native GUI Style"] { + let row = rows.iter().find(|r| r["family"] == family && r["style"] == style).unwrap(); + assert_eq!(row["missing"], false, "{row}"); + assert_eq!(row["styleMissing"], style != "Regular", "{row}"); + assert_eq!(row["matchStatus"], if style == "Regular" { "exact" } else { "styleSubstitute" }, "{row}"); + assert_eq!(row["resolvedFamily"], family, "{row}"); + assert_eq!(row["resolvedStyle"], "Regular", "{row}"); + assert_eq!(row["source"], "bundled", "an installed or injected face cannot satisfy this production contract: {row}"); + } + } + let missing = rows.iter().find(|r| r["family"] == "Unavailable Native GUI Family").unwrap(); + assert_eq!(missing["missing"], true, "{missing}"); + assert_eq!(missing["matchStatus"], "missing", "{missing}"); + assert!(missing["source"].is_null(), "{missing}"); +} + +#[test] +#[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may. +fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "曲:"); + // At a text caret the IME is allowed, its window on the caret as the canvas draws it. + let ime = ime_frame(&mut app, &ctx, vec![]).expect("IME allowed at a text caret"); + let (top, bottom) = { + let st = app.session.active().unwrap(); + let cs = app.session.cache.get(&st.doc, designcraft_doc::StoryId(sid.as_u64().unwrap()), None); + let (fi, x, bl, asc, desc) = compose::caret(&cs, "曲:".len()).unwrap(); + let fid = cs.frames[fi].frame; + let (a, _) = item_canvas_xf(&st.doc, &CanvasLayout::new(&st.doc, st.editing_parents), fid).unwrap(); + let m = a * st.doc.text_xf(st.doc.item(fid).unwrap()); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc))) + }; + assert!(ime.rect.expand(1.0).contains(top) && ime.rect.expand(1.0).contains(bottom), "{:?} vs {top:?}–{bottom:?}", ime.rect); + assert_eq!(ime.cursor_rect, ime.rect); + assert!(!ime.should_interrupt_composition); + assert!(app.canvas_ime(), "the web build keeps whole words typed at the caret"); + // "ni" → に → 日, with the events winit sends. + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Enabled), preedit("ni", 2)]); + assert_eq!(story_text(&mut app, &sid), "曲:ni", "marked text shows in place"); + assert!(app.session.tool_composing()); + // Keys, plain text, the clipboard and Undo (the native menu's ⌘Z) wait for the IME. + let steps = app.session.doc().unwrap().history.undo.len(); + let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + ime_frame( + &mut app, + &ctx, + vec![key(egui::Key::Backspace, true), key(egui::Key::Backspace, false), egui::Event::Text("x".into()), egui::Event::Paste("y".into())], + ); + crate::menus::activate(&mut app, "edit.undo", &Value::Null); + assert!(!crate::menus::enabled(&app, "edit.undo")); + assert_eq!(story_text(&mut app, &sid), "曲:ni"); + let ime2 = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("IME allowed while composing"); + assert_eq!(story_text(&mut app, &sid), "曲:に"); + assert!(ime2.rect.center().x > ime.rect.center().x, "the window follows the IME's cursor: {:?} {:?}", ime2.rect, ime.rect); + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Ime(egui::ImeEvent::Disabled)]); + assert_eq!(story_text(&mut app, &sid), "曲:日"); + assert!(!app.session.tool_composing()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the commit is one undo step"); + assert_eq!(app.session.journal.last(), Some(&("text.insert".to_string(), json!({"text": "日"})))); + // After the commit, typing and Undo work again. + ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]); + assert_eq!(story_text(&mut app, &sid), "曲:日!"); + crate::menus::activate(&mut app, "edit.undo", &Value::Null); + crate::menus::activate(&mut app, "edit.undo", &Value::Null); + assert_eq!(story_text(&mut app, &sid), "曲:"); + // Without a text caret the IME is off: single-key tool shortcuts keep working. + app.select_tool("selection"); + assert!(ime_frame(&mut app, &ctx, vec![]).is_none()); + assert!(!app.canvas_ime()); +} + +/// Both panes of a split window see the same keyboard events: only the pane last clicked +/// types them. +#[test] +fn a_split_window_types_once() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "ab"); + app.run("window.split", json!({"on": true})).unwrap(); + for _ in 0..3 { + ime_frame(&mut app, &ctx, vec![]); + } + assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some(), "both panes are drawn"); + ime_frame(&mut app, &ctx, vec![egui::Event::Text("c".into())]); + assert_eq!(story_text(&mut app, &sid), "abc"); + let key = |pressed| egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + ime_frame(&mut app, &ctx, vec![key(true), key(false)]); + assert_eq!(story_text(&mut app, &sid), "ab"); + ime_frame(&mut app, &ctx, vec![egui::Event::Paste("de".into())]); + assert_eq!(story_text(&mut app, &sid), "abde"); + ime_frame(&mut app, &ctx, vec![preedit("に", 1)]); + assert_eq!(story_text(&mut app, &sid), "abdeに"); + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]); + assert_eq!(story_text(&mut app, &sid), "abde日"); +} + +/// Surrounding text is committed text only, preserves reversed selection direction, and a commit keeps owner/generation while reporting `InputMethod`. +#[test] +fn ime_reports_the_committed_story_and_excludes_the_pre_edit() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "a😀b"); + let len = "a😀b".len(); + text_selection(&mut app, &sid, 0, len); + let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0)), "reversed selection keeps its direction"); + let owner = (ime.owner, ime.context_generation); + // Marked text previews in the document but is not committed surrounding text. + let ime = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("a text caret"); + assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0))); + assert_eq!(ime.owner, owner.0); + let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret"); + assert_eq!(ime_payload(&ime), Some(("日", 3, 3))); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); + assert_eq!(story_text(&mut app, &sid), "日"); + assert_eq!(ime.owner, owner.0); + assert_eq!(ime.context_generation, owner.1, "a commit is not a new context"); + let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert_eq!(ime_payload(&ime), Some(("日", 3, 3)), "a later pass reports the same committed text"); + assert_eq!((ime.owner, ime.context_generation), owner, "an unchanged pass keeps the context"); +} + +/// An empty story provides `("",0,0)`; long text is bounded and an out-of-window selection is explicitly unavailable. +#[test] +fn ime_empty_story_is_available_and_wide_text_is_bounded() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + typing_app(&mut app, &ctx, ""); + let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert_eq!(ime_payload(&ime), Some(("", 0, 0)), "an empty document is available, not unavailable"); + assert!(!app.session.tool_composing()); + + let long = "a".repeat(5000); + let sid = typing_app(&mut app, &ctx, &long); + let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + let (text, _, _) = ime_payload(&ime).expect("a long document still has surrounding text"); + assert!(text.len() <= egui::output::MAX_IME_SURROUNDING_TEXT_BYTES, "{}", text.len()); + text_selection(&mut app, &sid, 0, 5000); + let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert!(ime.surrounding_text.available().is_none(), "a selection beyond the bound is explicitly unavailable"); +} + +/// Caret movement preserves owner; changing story or document changes owner and generation. +#[test] +fn ime_owner_follows_the_story_and_the_document() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + typing_app(&mut app, &ctx, "ab"); + let first = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + app.session.execute("text.move", &json!({"dir": "left"})).unwrap(); + let moved = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert_eq!((moved.owner, moved.context_generation), (first.owner, first.context_generation), "a caret move keeps the context"); + + let other = app.run("frame.create", json!({"rect": [400, 36, 200, 100], "content": "text", "text": "xy"})).unwrap(); + let other_sid = other["story"].clone(); + text_selection(&mut app, &other_sid, 2, 2); + let second = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert_ne!(second.owner, first.owner, "another story is another owner"); + assert_ne!(second.context_generation, first.context_generation); + + app.run("file.new", json!({})).unwrap(); + let doc = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "z"})).unwrap(); + text_selection(&mut app, &doc["story"], 1, 1); + let replaced = ime_frame(&mut app, &ctx, vec![]).expect("a text caret"); + assert_ne!(replaced.owner, second.owner, "a new document is another owner"); + assert_eq!(ime_payload(&replaced), Some(("z", 1, 1))); +} + +/// Pure commits report `InputMethod`; typing before or after a commit in one pass makes the cause `Other`. +#[test] +fn ime_cause_distinguishes_commits_from_application_edits() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + typing_app(&mut app, &ctx, "a"); + let committed = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret"); + assert_eq!(committed.change_cause, egui::output::ImeChangeCause::InputMethod); + let typed = ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]).expect("a text caret"); + assert_eq!(typed.change_cause, egui::output::ImeChangeCause::Other, "ordinary typing is an application edit"); + assert_eq!(ime_payload(&typed), Some(("a日!", 5, 5))); + + // An application edit before the commit in one pass breaks the receipt chain. + let mut before = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + typing_app(&mut before, &ctx, "a"); + let mixed = ime_frame(&mut before, &ctx, vec![egui::Event::Text("x".into()), egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]) + .expect("a text caret"); + assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other); + assert_eq!(ime_payload(&mixed), Some(("ax日", 5, 5))); + + // An application edit after the commit in one pass also dominates. + let mut after = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + typing_app(&mut after, &ctx, "a"); + let mixed = ime_frame(&mut after, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Text("!".into())]) + .expect("a text caret"); + assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other); + assert_eq!(ime_payload(&mixed), Some(("a日!", 5, 5))); +} + +/// The settled multipass result rebuilds the current surrounding text while retaining the accepted commit cause. +#[test] +fn ime_cause_and_context_survive_a_discarded_pass() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + typing_app(&mut app, &ctx, "a"); + let raw = egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), + events: vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))], + ..Default::default() + }; + let mut passes = 0; + let mut out = ctx.run_ui(raw, |ui| { + passes += 1; + if passes == 1 { + ui.ctx().request_discard("IME multipass regression"); + } + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + assert_eq!(out.platform_output.num_completed_passes, 2, "the frame really was multipass"); + let ime = out.platform_output.ime.expect("a text caret"); + assert_eq!(ime_payload(&ime), Some(("a日", 4, 4)), "the second pass rebuilds the current text"); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the discarded pass keeps the accepted commit's cause"); +} + +/// Autocorrected commit text is an application edit with cause `Other`. +#[test] +fn ime_autocorrect_is_not_an_input_method_cause() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.session.prefs.autocorrect = true; + let sid = typing_app(&mut app, &ctx, "teh"); + let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit(" ".into()))]).expect("a text caret"); + assert_eq!(story_text(&mut app, &sid), "the "); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::Other); +} + +/// The selection stays selected and directed; byte partials leave whole characters; the deletion is one undo step. +#[test] +fn ime_delete_surrounding_excludes_the_selection_and_rounds_bytes_inward() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "aé😀b"); + // Select é, which keeps its bytes and direction; 'a' before and 😀 after go. + text_selection(&mut app, &sid, 1, 3); + ime_frame(&mut app, &ctx, vec![]); + let steps = app.session.doc().unwrap().history.undo.len(); + let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })]) + .expect("a text caret"); + assert_eq!(story_text(&mut app, &sid), "éb"); + let sel = app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!((sel.anchor, sel.focus), (0, 2), "the selected text stays selected and directed"); + assert_eq!(ime_payload(&ime), Some(("éb", 2, 0))); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "one deletion is one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(story_text(&mut app, &sid), "aé😀b"); + ime_frame(&mut app, &ctx, vec![]); + // The same deletion with a reversed selection keeps anchor > focus. + text_selection(&mut app, &sid, 3, 1); + ime_frame(&mut app, &ctx, vec![]); + let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })]) + .expect("a text caret"); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); + let sel = app.session.doc().unwrap().selection.text.unwrap(); + assert_eq!(story_text(&mut app, &sid), "éb"); + assert_eq!((sel.anchor, sel.focus), (2, 0), "reversed selection stays reversed"); + + // One byte of a two-byte character leaves the whole character. + let partial = typing_app(&mut app, &ctx, "aé"); + text_selection(&mut app, &partial, 1, 1); + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 1 })]); + assert_eq!(story_text(&mut app, &partial), "aé"); + // A preceding count that lands inside the four-byte emoji leaves it whole too. + let partial = typing_app(&mut app, &ctx, "a😀"); + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 0 })]); + assert_eq!(story_text(&mut app, &partial), "a😀"); +} + +/// A 200-character request deletes the whole 100-character story. +#[test] +fn ime_delete_surrounding_has_no_sixty_four_character_cap() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, &"x".repeat(100)); + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 200, after_chars: 0 })]); + assert_eq!(story_text(&mut app, &sid), ""); +} + +/// Delete plus commit in one IME batch produces one undoable edit and reports the final surrounding text. +#[test] +fn ime_delete_and_commit_are_one_undo_step() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "ab"); + text_selection(&mut app, &sid, 1, 2); + ime_frame(&mut app, &ctx, vec![]); + let steps = app.session.doc().unwrap().history.undo.len(); + let ime = ime_frame( + &mut app, + &ctx, + vec![ + egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 }), + egui::Event::Ime(egui::ImeEvent::Commit("X".into())), + ], + ) + .expect("a text caret"); + assert_eq!(story_text(&mut app, &sid), "X"); + assert_eq!(ime_payload(&ime), Some(("X", 1, 1))); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the IME batch is one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(story_text(&mut app, &sid), "ab"); +} + +/// The input method's Commit for a composition a click ended earlier in the same event batch +/// must not type the marked text again at the clicked caret. +#[test] +fn a_commit_after_a_click_in_the_same_batch_is_not_typed_twice() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "ab"); + ime_frame(&mut app, &ctx, vec![preedit("い", 1)]); + assert_eq!(story_text(&mut app, &sid), "abい"); + let p = on_screen(&app, Point::new(150.0, 120.0)); + let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))]) + .expect("still at a text caret"); + let typed = story_text(&mut app, &sid); + assert_eq!(typed.matches('い').count(), 1, "the click typed the marked text once: {typed:?}"); + assert!(typed.starts_with("ab"), "{typed:?}"); + assert!(!app.session.tool_composing()); + assert!(app.take_ime_discard(), "the system IME is told to drop its copy"); + ime_frame(&mut app, &ctx, vec![press(false)]); +} + +/// A delete-surrounding and its commit from the same ended composition must not edit the +/// clicked caret's text either. +#[test] +fn a_delete_and_commit_after_a_click_in_the_same_batch_are_dropped() { + for delete in [ + egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 }, + egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 }, + ] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, "ab"); + ime_frame(&mut app, &ctx, vec![preedit("い", 1)]); + let p = on_screen(&app, Point::new(150.0, 120.0)); + let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ime_frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(delete), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))], + ) + .expect("still at a text caret"); + let typed = story_text(&mut app, &sid); + assert_eq!(typed.matches('い').count(), 1, "the late commit is dropped: {typed:?}"); + assert!(typed.contains("ab"), "the click's text was not deleted: {typed:?}"); + assert!(app.take_ime_discard()); + ime_frame(&mut app, &ctx, vec![press(false)]); + } +} + +/// A byte-count delete that reaches past the bounded IME window is still exactly the requested +/// input method mutation: the engine reports the ranges from the whole story. +#[test] +fn a_delete_beyond_the_surrounding_window_is_still_an_input_method_cause() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, &"x".repeat(5000)); + let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 4500, after_bytes: 0 })]) + .expect("a text caret"); + assert_eq!(story_text(&mut app, &sid).len(), 500); + assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod); + assert_eq!(ime_payload(&ime).map(|(text, cursor, anchor)| (text.len(), cursor, anchor)), Some((500, 500, 500))); +} + +/// The pass's IME observation comes after the later UI sections: a click into the Story +/// Editor's field takes the keyboard from the canvas in the same pass, so the composition +/// ends there and the canvas reports no IME. +#[test] +fn a_later_field_taking_the_keyboard_ends_the_composition_in_that_pass() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap(); + let sid = f["story"].clone(); + app.select_tool("type"); + app.run("text.select", json!({"story": sid, "anchor": 2, "focus": 2})).unwrap(); + app.run("app.storyEditor", json!({"story": sid})).unwrap(); + let mut h = crate::test_window::open(app, egui::vec2(1440.0, 900.0)); + h.event(preedit("い", 1)); + h.run_steps(2); + assert!(h.state().app.session.tool_composing()); + let canvas_owner = h.output().platform_output.ime.as_ref().expect("the canvas owns the composition").owner; + let field = h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().expect("the Story Editor's text field"); + field.click(); + h.run_steps(2); + assert!(!h.state().app.session.tool_composing(), "the composition ended where the field took the keyboard"); + assert!(h.state_mut().app.take_ime_discard()); + assert!(h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().unwrap().is_focused(), "the field has the keyboard"); + let ime = h.output().platform_output.ime.as_ref().expect("the focused Story Editor publishes its IME context"); + assert_ne!(ime.owner, canvas_owner, "the field owns the IME, not the canvas"); + let typed = story_text(&mut h.state_mut().app, &sid); + assert!(typed.contains('い'), "the marked text stays as typed: {typed:?}"); + h.event(egui::Event::Ime(egui::ImeEvent::Commit("X".into()))); + h.run_steps(2); + let edited = story_text(&mut h.state_mut().app, &sid); + assert_eq!(edited.matches('X').count(), 1, "the field's next commit is applied once: {edited:?}"); + assert_eq!(edited.matches('い').count(), 1, "the old canvas composition is not replayed: {edited:?}"); +} + +#[test] +fn clicking_away_mid_composition_keeps_the_text_and_interrupts_the_ime() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, ""); + ime_frame(&mut app, &ctx, vec![preedit("しょうこ", 4)]); + assert!(app.session.tool_composing()); + // A click in the frame (macOS and Windows send nothing for it): the marked text stays as + // typed and the IME is told to drop its composition, once. + let p = on_screen(&app, Point::new(150.0, 120.0)); + let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let ime = ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true)]).expect("still at a text caret"); + assert!(ime.should_interrupt_composition); + ime_frame(&mut app, &ctx, vec![press(false)]); + assert!(!app.session.tool_composing()); + assert_eq!(story_text(&mut app, &sid), "しょうこ"); + assert!(app.take_ime_discard(), "the host tells the system IME to drop its marked text"); + assert!(!ime_frame(&mut app, &ctx, vec![]).expect("still at a text caret").should_interrupt_composition); + assert!(!app.take_ime_discard()); + // A bare line break from the IME confirms a composition: the marked text, no new paragraph. + ime_frame(&mut app, &ctx, vec![preedit("がく", 2)]); + ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("\n".into()))]); + assert!(!app.session.tool_composing()); + let typed = story_text(&mut app, &sid); + assert!(typed.contains("がく") && typed.contains("しょうこ") && !typed.contains('\n'), "{typed:?}"); +} + +#[test] +fn baseline_grid_lines_are_the_ones_on_the_page() { + // A start far above the page used to be walked line by line, without end. + for start in [-1e9, -1e17] { + let mut far = baseline_grid_lines(start, 12.0, 792.0); + assert_eq!((far.next(), far.count()), (Some(8.0), 65)); + } + let lines = |start, increment, height| baseline_grid_lines(start, increment, height).collect::>(); + assert_eq!(lines(36.0, 12.0, 72.0), [36.0, 48.0, 60.0], "the bottom edge is not a line"); + assert_eq!(lines(-30.0, 12.0, 30.0), [6.0, 18.0], "a start above the page keeps its rhythm"); + assert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]); + assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES); +} + +#[test] +fn enter_or_tab_in_a_panel_field_leave_the_selected_text_alone() { + for key in [egui::Key::Enter, egui::Key::Tab] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap(); + app.select_tool("type"); + app.run("text.select", json!({"story": f["story"], "anchor": 1, "focus": 4})).unwrap(); + assert!(app.session.wants_text()); + let mut h = harness(app); + let size = h.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("12 pt")).unwrap(); + size.focus(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.event(egui::Event::Text("18".into())); + h.run_steps(1); + h.key_press(key); + h.run_steps(3); + let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone(); + assert_eq!(text, "Hello", "{key:?} confirms the field and leaves the story alone"); + let size = crate::panels::text_attrs(h.state_mut()).unwrap()["chars"]["size"].clone(); + assert_eq!(size, 18.0, "{key:?} applies the typed size"); + } +} + +#[test] +fn trailing_spaces_show_dots_before_the_paragraph_mark() { + let text = "ab \ncd "; + let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); + let lid = d.default_layer(); + let rect = DRect::new(0.0, 0.0, 300.0, 100.0); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, text, Default::default()).unwrap(); + let cs = compose::compose_story(&d, sid, &compose::ComposeOptions::default()); + let lines: Vec<_> = cs.frames.iter().flat_map(|f| &f.lines).collect(); + assert_eq!(lines.len(), 2); + for (l, end_mark) in lines.iter().zip(["¶", "#"]) { + let marks = hidden_marks(text, l); + let dots: Vec = marks.iter().filter(|m| m.1 == "·").map(|m| m.0).collect(); + assert_eq!(dots.len(), 2, "a dot for each trailing space: {marks:?}"); + let &(para_x, mark, _) = marks.last().unwrap(); + assert_eq!(mark, end_mark); + // The dots sit past the last letter, and the mark comes after both spaces. + let space = l.glyphs.iter().rev().find(|g| g.len > 0).unwrap(); + assert!(dots.iter().all(|&x| x > l.end_x && x < para_x), "{dots:?} then {mark} at {para_x}"); + assert!(para_x >= space.x + space.adv, "{mark} at {para_x} overlaps the last space"); + } +} From 56905e5076240e8b74261119e8bf5543f71db58e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:23 +0000 Subject: [PATCH 09/70] refactor(ui-egui): move the tests module of lib.rs to tests.rs --- crates/ui-egui/src/lib.rs | 2060 +---------------------------------- crates/ui-egui/src/tests.rs | 2047 ++++++++++++++++++++++++++++++++++ 2 files changed, 2048 insertions(+), 2059 deletions(-) create mode 100644 crates/ui-egui/src/tests.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3bb2a592e..71e45bf0b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2605,2065 +2605,7 @@ pub fn drop_key_name_text(raw: &mut egui::RawInput, text_input_focused: bool) { } #[cfg(test)] -mod tests { - use super::*; - - /// The Control panel's two-row groups were centred as if they were one row tall, so the second - /// row hung below the panel and was cut off. - #[test] - fn control_bar_shows_its_second_row() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - app.run("file.newSample", json!({})).unwrap(); - app.ui.control_bar = true; - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(4); - let bar = egui::containers::panel::PanelState::load(&h.ctx, h.ui_id().with("control_bar")).unwrap().outer_rect; - assert!(bar.height() > 40.0, "{bar:?}"); - // The X/Y/W/H group: its second row holds Y: and H:. - let group = h.ctx.read_response(egui::Id::unique(("object_control", "dimensions"))).unwrap().rect; - assert!(bar.contains(group.left_top()), "the X/Y/W/H group {group:?} is in the Control panel {bar:?}"); - assert!(group.bottom() <= bar.bottom(), "X/Y/W/H group {group:?} hangs below the Control panel {bar:?}"); - } - - #[test] - fn key_names_sent_as_text_are_dropped() { - let text = |t: &str| egui::Event::Text(t.to_string()); - let events = || { - vec![text("AltGraph"), text("é"), text("Dead"), text("A"), text("Unidentified"), text("ß"), text("AudioVolumeUp"), text("ab"), text("Æ")] - }; - let mut raw = egui::RawInput { events: events(), ..Default::default() }; - drop_key_name_text(&mut raw, false); - assert_eq!(raw.events, vec![text("é"), text("A"), text("ß"), text("ab"), text("Æ")]); - assert!(is_key_name("F13") && is_key_name("Escape") && is_key_name("ZoomToggle") && !is_key_name("F") && !is_key_name("Fx")); - // Capitalised words (mobile autocompletion) are text. - let words = vec![text("Hello"), text("Tokyo"), text("OK"), text("Hi there")]; - let mut raw = egui::RawInput { events: words.clone(), ..Default::default() }; - drop_key_name_text(&mut raw, false); - assert_eq!(raw.events, words); - // A focused text field or a canvas text caret gets its text from the browser's input - // events, which hold whole words, key-name-like ones too ("Help"). - let mut raw = egui::RawInput { events: events(), ..Default::default() }; - drop_key_name_text(&mut raw, true); - assert_eq!(raw.events, events()); - } - - /// InDesign shows 100% K as pure black on screen unless Appearance of Black says otherwise - /// (Display All Blacks as Rich Black is its default); settings saved without the field get it too. - #[test] - fn black_shows_as_rich_black_by_default() { - assert!(UiState::default().rich_black); - let saved: UiState = serde_json::from_str("{}").unwrap(); - assert!(saved.rich_black); - let accurate: UiState = serde_json::from_str(r#"{"richBlack": false}"#).unwrap(); - assert!(!accurate.rich_black, "a saved choice is kept"); - } - - /// Tool readouts measured in picas whatever the document's units (the UI's unit is never set): - /// they follow the active document's ruler units. - #[test] - fn tool_readouts_measure_in_the_documents_units() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - assert_eq!(app.view_info().unit, Unit::Picas, "no document: the UI's default"); - app.run("file.new", json!({})).unwrap(); - app.run("document.preferences", json!({"horizontalUnits": "inches", "verticalUnits": "millimeters"})).unwrap(); - assert_eq!(app.view_info().unit, Unit::Inches); - } - - /// Save and Export PDF dialogs started in the home folder (#1653): they start beside a saved - /// document, and for one never saved in the folder of the last save or export. - #[test] - fn save_dialogs_start_beside_the_document_or_in_the_last_folder() { - use std::{cell::RefCell, rc::Rc}; - let home = tempfile::tempdir().unwrap(); - let elsewhere = tempfile::tempdir().unwrap(); - let asked: Rc>> = Rc::default(); - let answer: Rc>> = Rc::default(); - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - let (seen, reply) = (asked.clone(), answer.clone()); - app.services.pick_save = Some(Box::new(move |name: &str| { - seen.borrow_mut().push(name.to_string()); - reply.borrow().clone() - })); - app.services.write = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); - let last = |asked: &Rc>>| asked.borrow().last().cloned().unwrap_or_default(); - let export_pdf = |app: &mut DesignApp| { - app.ui.dialog = Some(dialogs::Dialog::new("pdfExport", json!({}))); - app.ui.dialog.as_mut().unwrap().fields.insert("title".into(), json!("Report")); - dialogs::confirm(app).unwrap(); - }; - - app.run("file.new", json!({})).unwrap(); - let untitled = format!("{}.designcraft", app.session.active().unwrap().doc.title); - app.run("app.saveDialog", json!({})).unwrap(); - assert_eq!(last(&asked), untitled, "never saved, nothing remembered: the system's own folder"); - - let saved = home.path().join("Brochure.designcraft"); - *answer.borrow_mut() = Some(saved.to_string_lossy().to_string()); - app.run("app.saveDialog", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().path.as_deref(), Some(&*saved.to_string_lossy())); - // An export into another folder becomes the last folder used. - *answer.borrow_mut() = Some(elsewhere.path().join("Proof.pdf").to_string_lossy().to_string()); - export_pdf(&mut app); - *answer.borrow_mut() = None; - export_pdf(&mut app); - assert_eq!(last(&asked), home.path().join("Report.pdf").to_string_lossy(), "a saved document exports beside itself"); - - app.run("file.new", json!({})).unwrap(); - let untitled = format!("{}.designcraft", app.session.active().unwrap().doc.title); - app.run("app.saveDialog", json!({})).unwrap(); - assert_eq!(last(&asked), elsewhere.path().join(untitled).to_string_lossy(), "a new document starts in the last folder used"); - } - - /// No name (Save with no document) suggested the remembered folder itself as the file, and a - /// title with a slash moved the suggestion out of the document's folder. - #[test] - fn save_dialog_suggestions_keep_the_folder_and_only_a_file_name() { - use std::{cell::RefCell, rc::Rc}; - let folder = tempfile::tempdir().unwrap(); - let asked: Rc>> = Rc::default(); - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - let seen = asked.clone(); - app.services.pick_save = Some(Box::new(move |name: &str| { - seen.borrow_mut().push(name.to_string()); - None - })); - app.ui.last_save_folder = Some(folder.path().join("Docs").to_string_lossy().to_string()); - app.pick_save(""); - app.pick_save("Q1/Q2.pdf"); - assert_eq!(*asked.borrow(), ["".to_string(), folder.path().join("Docs").join("Q2.pdf").to_string_lossy().to_string()]); - } - - /// An app with one document that has an unsaved edit. - fn app_with_unsaved_document() -> DesignApp { - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - app.run("file.new", json!({})).unwrap(); - assert!(!app.session.documents()[0].is_dirty(), "a new document has nothing to save"); - app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap(); - assert!(app.session.documents()[0].is_dirty()); - app - } - - /// File ▸ Close (and its shortcut) closed a document with unsaved changes without asking, and - /// closing discards the document's recovery data too. - #[test] - fn closing_an_unsaved_document_asks_first() { - let mut app = app_with_unsaved_document(); - menus::activate(&mut app, "file.close", &Value::Null); - assert_eq!(app.session.documents().len(), 1, "the document stays open until the user answers"); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("closeDocument")); - // Cancel: nothing happens. - app.ui.dialog = None; - assert!(app.session.documents()[0].is_dirty()); - // The tab's × asks too. - menus::close_document(&mut app, Some(0)); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("closeDocument")); - assert_eq!(app.session.documents().len(), 1); - } - - #[test] - fn closing_without_saving_discards_the_document() { - let mut app = app_with_unsaved_document(); - menus::close_document(&mut app, None); - app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); - dialogs::confirm(&mut app).unwrap(); - assert!(app.session.documents().is_empty()); - assert!(app.ui.dialog.is_none()); - } - - #[test] - fn closing_with_save_writes_the_file_then_closes() { - let mut app = app_with_unsaved_document(); - let path = std::env::temp_dir().join(format!("designcraft-close-test-{}.designcraft", std::process::id())); - app.run("file.saveAs", json!({"path": path})).unwrap(); - let saved = std::fs::metadata(&path).unwrap().len(); - app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap(); - menus::close_document(&mut app, None); - dialogs::confirm(&mut app).unwrap(); - assert!(app.session.documents().is_empty()); - let written = std::fs::metadata(&path).unwrap().len(); - std::fs::remove_file(&path).unwrap(); - assert!(written > saved, "the second frame was saved ({saved} → {written} bytes)"); - } - - /// Save on a document that has no file opens the file picker; cancelling it must not close the - /// document. (No picker service here: the same as cancelling.) - #[test] - fn a_cancelled_save_keeps_the_document_open() { - let mut app = app_with_unsaved_document(); - menus::close_document(&mut app, None); - dialogs::confirm(&mut app).unwrap(); - assert_eq!(app.session.documents().len(), 1); - assert!(app.session.documents()[0].is_dirty()); - } - - #[test] - fn closing_a_saved_document_does_not_ask() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - app.run("file.new", json!({})).unwrap(); - menus::activate(&mut app, "file.close", &Value::Null); - assert!(app.session.documents().is_empty()); - assert!(app.ui.dialog.is_none()); - } - - /// One frame of the quit handling, with the window asked to close when `close`; returns the - /// commands sent to the window. - fn quit_frame(app: &mut DesignApp, ctx: &egui::Context, close: bool) -> Vec { - let mut raw = egui::RawInput::default(); - if close { - raw.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); - } - let mut out = ctx.run_ui(raw, |ui| app.handle_quit(ui.ctx())); - out.textures_delta.clear(); - out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default() - } - - fn dialog_uid(app: &DesignApp) -> Option { - app.ui.dialog.as_ref().filter(|d| d.id == "closeDocument").and_then(|d| d.fields.get("uid")?.as_u64()) - } - - /// Quitting closed the window at once, losing unsaved changes (#544). - #[test] - fn quitting_with_unsaved_changes_asks_and_cancel_keeps_everything() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - let cmds = quit_frame(&mut app, &ctx, true); - assert!(cmds.contains(&egui::ViewportCommand::CancelClose), "{cmds:?}"); - assert_eq!(dialog_uid(&app), Some(app.session.documents()[0].uid)); - // Cancel: the window and the document stay as they were. - app.ui.dialog = None; - for _ in 0..2 { - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - } - assert_eq!(app.session.documents().len(), 1); - assert!(app.session.documents()[0].is_dirty()); - // A Save whose file picker is cancelled stops quitting too. - quit_frame(&mut app, &ctx, true); - dialogs::confirm(&mut app).unwrap(); - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert!(app.session.documents()[0].is_dirty()); - } - - #[test] - fn quitting_asks_about_each_unsaved_document_then_closes() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap(); - app.run("file.new", json!({})).unwrap(); - let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); - assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); - for (n, uid) in uids.iter().take(2).enumerate() { - assert_eq!(dialog_uid(&app), Some(*uid), "question {n}"); - assert_eq!(app.session.active().map(|d| d.uid), Some(*uid), "the document asked about is shown"); - app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); - dialogs::confirm(&mut app).unwrap(); - let cmds = quit_frame(&mut app, &ctx, false); - assert_eq!(cmds.contains(&egui::ViewportCommand::Close), n == 1, "{cmds:?}"); - } - // All documents stay open until the backend's final close commits the decision. - assert_eq!(app.session.documents().len(), 3); - assert!(quit_frame(&mut app, &ctx, true).is_empty()); - assert!(app.session.documents().is_empty()); - } - - /// A later Cancel must not destroy documents already approved for discard. - #[test] - fn quitting_later_cancel_retains_every_document_and_active_tab() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [20, 20, 120, 120]})).unwrap(); - let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); - let active = app.session.active().unwrap().uid; - let revisions: Vec = app.session.documents().iter().map(|d| d.revision).collect(); - let docs: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - quit_frame(&mut app, &ctx, true); - app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); - dialogs::confirm(&mut app).unwrap(); - quit_frame(&mut app, &ctx, false); - assert_eq!(dialog_uid(&app), Some(uids[1])); - app.ui.dialog = None; - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), uids); - assert_eq!(app.session.active().unwrap().uid, active); - assert_eq!(app.session.documents().iter().map(|d| d.revision).collect::>(), revisions); - for (d, original) in app.session.documents().iter().zip(docs) { - assert!(std::sync::Arc::ptr_eq(&d.doc, &original)); - assert!(d.is_dirty()); - assert!(!d.history.undo.is_empty()); - } - } - - fn second_unsaved_document(app: &mut DesignApp) { - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [20, 20, 120, 120]})).unwrap(); - } - - fn discard_quit_dialog(app: &mut DesignApp) { - app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); - dialogs::confirm(app).unwrap(); - } - - #[test] - fn native_quit_prompts_restore_window_visibility_without_focusing_completed_quits() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - let commands = quit_frame(&mut app, &ctx, true); - assert!(commands.contains(&egui::ViewportCommand::CancelClose)); - for command in [egui::ViewportCommand::Visible(true), egui::ViewportCommand::Minimized(false), egui::ViewportCommand::Focus] { - assert!(commands.contains(&command), "unsaved prompt must restore the window: {commands:?}"); - } - discard_quit_dialog(&mut app); - let approved = quit_frame(&mut app, &ctx, false); - assert!(approved.contains(&egui::ViewportCommand::Close)); - let completed = quit_frame(&mut app, &ctx, true); - assert!(app.session.documents().is_empty()); - - let mut clean = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - clean.run("file.new", json!({})).unwrap(); - let clean_close = quit_frame(&mut clean, &ctx, true); - let mut control = app_with_unsaved_document(); - control.quit_without_asking = true; - let control_close = quit_frame(&mut control, &ctx, true); - for commands in [&approved, &completed, &clean_close, &control_close] { - assert!( - !commands.iter().any(|command| matches!( - command, - egui::ViewportCommand::Visible(true) | egui::ViewportCommand::Minimized(false) | egui::ViewportCommand::Focus - )), - "completed and immediate quits must not activate the window: {commands:?}" - ); - } - } - - /// Dock Quit may arrive again while the first request's dialogs are still open. - #[test] - fn repeated_native_quit_requests_preserve_partial_approvals_and_cancel() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let original_active = app.session.active().unwrap().uid; - let uids: Vec<_> = app.session.documents().iter().map(|d| d.uid).collect(); - let docs: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - let directory = tempfile::tempdir().unwrap(); - app.session.recovery_dir = Some(directory.path().to_path_buf()); - app.run("file.recovery.save", json!({})).unwrap(); - assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); - assert_eq!(dialog_uid(&app), Some(uids[0])); - discard_quit_dialog(&mut app); - quit_frame(&mut app, &ctx, false); - assert_eq!(dialog_uid(&app), Some(uids[1])); - for _ in 0..3 { - assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); - assert_eq!(dialog_uid(&app), Some(uids[1])); - } - app.ui.dialog = None; // Cancel the second document, retaining the first Don't Save answer. - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.active().unwrap().uid, original_active); - assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), uids); - for (document, original) in app.session.documents().iter().zip(docs) { - assert!(std::sync::Arc::ptr_eq(&document.doc, &original)); - assert!(document.is_dirty()); - assert!(!document.history.undo.is_empty()); - assert!(directory.path().join(format!("{}.designcraft", document.uid)).exists()); - } - // A fresh Dock Quit must ask about the first document again after cancellation. - assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); - assert_eq!(dialog_uid(&app), Some(uids[0])); - } - - #[test] - fn repeated_native_quit_requests_save_and_discard_only_after_all_answers() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let uids: Vec<_> = app.session.documents().iter().map(|d| d.uid).collect(); - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("saved.designcraft"); - let chosen = path.to_string_lossy().to_string(); - app.services.pick_save = Some(Box::new(move |_| Some(chosen.clone()))); - app.session.recovery_dir = Some(directory.path().join("recovery")); - app.run("file.recovery.save", json!({})).unwrap(); - quit_frame(&mut app, &ctx, true); - assert_eq!(dialog_uid(&app), Some(uids[0])); - dialogs::confirm(&mut app).unwrap(); // Save the first document. - assert!(!app.session.documents()[0].is_dirty()); - quit_frame(&mut app, &ctx, false); - assert_eq!(dialog_uid(&app), Some(uids[1])); - assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); - assert_eq!(dialog_uid(&app), Some(uids[1])); - discard_quit_dialog(&mut app); - assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.documents().len(), 2); - assert!(app.session.recovery_dir.as_ref().unwrap().join(format!("{}.designcraft", uids[1])).exists()); - assert!(quit_frame(&mut app, &ctx, true).is_empty()); - assert!(app.session.documents().is_empty()); - assert!(path.exists()); - assert_eq!(designcraft_engine::Session::new().execute("file.open", &json!({"path": path})).unwrap()["index"], 0); - assert_eq!(std::fs::read_dir(app.session.recovery_dir.as_ref().unwrap()).unwrap().count(), 0); - } - - #[test] - fn quitting_first_cancel_restores_original_clean_active_document() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - app.run("file.new", json!({})).unwrap(); - let original_active = app.session.active().unwrap().uid; - quit_frame(&mut app, &ctx, true); - assert_ne!(app.session.active().unwrap().uid, original_active); - app.ui.dialog = None; - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.active().unwrap().uid, original_active); - assert_eq!(app.session.documents().len(), 2); - } - - #[test] - fn quitting_save_as_cancel_after_discard_keeps_all_documents() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let active = app.session.active().unwrap().uid; - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - quit_frame(&mut app, &ctx, false); - dialogs::confirm(&mut app).unwrap(); // No picker: Save As was cancelled. - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.documents().len(), 2); - assert!(app.session.documents().iter().all(|d| d.is_dirty())); - assert_eq!(app.session.active().unwrap().uid, active); - } - - #[test] - fn quitting_save_failure_after_discard_keeps_documents_and_can_retry() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let path = std::env::temp_dir() - .join(format!("designcraft-quit-missing-{}-{}", std::process::id(), app.session.active().unwrap().uid)) - .join("missing") - .join("document.designcraft"); - assert!(!path.parent().unwrap().exists()); - let picked = path.to_string_lossy().to_string(); - app.services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - quit_frame(&mut app, &ctx, false); - assert!(dialogs::confirm(&mut app).is_err()); - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.documents().len(), 2); - assert!(app.session.documents().iter().all(|d| d.is_dirty())); - // Starting over must ask about the previously discarded first document again. - quit_frame(&mut app, &ctx, true); - assert_eq!(dialog_uid(&app), Some(app.session.documents()[0].uid)); - } - - #[test] - fn quitting_save_then_later_cancel_keeps_saved_document_open() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let first = app.session.documents()[0].uid; - let path = std::env::temp_dir().join(format!("designcraft-quit-save-{}-{first}.designcraft", std::process::id())); - let picked = path.to_string_lossy().to_string(); - app.services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); - quit_frame(&mut app, &ctx, true); - dialogs::confirm(&mut app).unwrap(); - quit_frame(&mut app, &ctx, false); - assert_eq!(app.session.documents().len(), 2); - assert!(!app.session.documents()[0].is_dirty()); - assert!(path.exists()); - app.ui.dialog = None; - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.documents()[0].uid, first); - assert!(app.session.documents()[1].is_dirty()); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn quitting_rechecks_discard_approval_after_a_later_edit() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let first = app.session.documents()[0].uid; - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - quit_frame(&mut app, &ctx, false); - app.run("file.activate", json!({"index": 0})).unwrap(); - app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap(); - discard_quit_dialog(&mut app); // Approval is bound to the second UID, despite the switch. - assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(dialog_uid(&app), Some(first), "new edit needs a fresh decision"); - assert_eq!(app.session.documents().len(), 2); - } - - #[test] - fn quitting_final_close_rechecks_new_unsaved_document() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - second_unsaved_document(&mut app); // Arrives after Close was queued, before its event. - let new_uid = app.session.active().unwrap().uid; - assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); - assert_eq!(dialog_uid(&app), Some(new_uid)); - assert_eq!(app.session.documents().len(), 2); - } - - #[test] - fn quitting_pending_save_uses_dialog_uid_after_tab_switch() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - second_unsaved_document(&mut app); - let first = app.session.documents()[0].uid; - let path = std::env::temp_dir().join(format!("designcraft-quit-uid-{}-{first}.designcraft", std::process::id())); - let picked = path.to_string_lossy().to_string(); - app.services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); - quit_frame(&mut app, &ctx, true); - app.run("file.activate", json!({"index": 1})).unwrap(); - dialogs::confirm(&mut app).unwrap(); - assert_eq!(app.session.documents()[0].path.as_deref(), path.to_str()); - assert!(!app.session.documents()[0].is_dirty()); - assert!(app.session.documents()[1].is_dirty()); - quit_frame(&mut app, &ctx, false); - assert_eq!(dialog_uid(&app), Some(app.session.documents()[1].uid)); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn quitting_discard_preserves_recovery_until_final_commit() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - let uid = app.session.active().unwrap().uid; - let dir = std::env::temp_dir().join(format!("designcraft-quit-recovery-{}-{uid}", std::process::id())); - app.session.recovery_dir = Some(dir.clone()); - app.run("file.recovery.save", json!({})).unwrap(); - let entry = dir.join(format!("{uid}.designcraft")); - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert!(entry.exists(), "a queued close is not a committed close"); - assert!(quit_frame(&mut app, &ctx, true).is_empty()); - assert!(!entry.exists(), "accepted Don't Save must not be recovered on restart"); - assert!(app.session.documents().is_empty()); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn quitting_native_exit_commits_completed_approvals_before_close_event() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert_eq!(app.session.documents().len(), 1); - app.finish_confirmed_quit().unwrap(); - assert!(app.session.documents().is_empty()); - } - - #[test] - fn quitting_native_exit_retains_incomplete_stale_and_new_document_plans() { - for case in ["incomplete", "stale", "new document"] { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - if case == "incomplete" { - second_unsaved_document(&mut app); - } - quit_frame(&mut app, &ctx, true); - discard_quit_dialog(&mut app); - quit_frame(&mut app, &ctx, false); - if case == "stale" { - app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap(); - } else if case == "new document" { - second_unsaved_document(&mut app); - } - let active = app.session.active().unwrap().uid; - let before: Vec<_> = app - .session - .documents() - .iter() - .map(|d| (d.uid, d.revision, d.doc.clone(), d.selection.items.clone(), d.history.undo.len(), d.history.redo.len())) - .collect(); - app.finish_confirmed_quit().unwrap(); - assert_eq!(app.session.documents().len(), before.len(), "{case}"); - assert_eq!(app.session.active().unwrap().uid, active, "{case}"); - for (d, (uid, revision, doc, selection, undo, redo)) in app.session.documents().iter().zip(before) { - assert_eq!( - (d.uid, d.revision, &d.selection.items, d.history.undo.len(), d.history.redo.len()), - (uid, revision, &selection, undo, redo), - "{case}" - ); - assert!(std::sync::Arc::ptr_eq(&d.doc, &doc), "{case}"); - } - } - } - - #[test] - fn quitting_without_unsaved_changes_closes_at_once() { - let ctx = egui::Context::default(); - let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); - app.run("file.new", json!({})).unwrap(); - // Quit (⌘Q) closes the window like its close button. - app.run("app.quit", json!({})).unwrap(); - assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); - assert!(quit_frame(&mut app, &ctx, true).is_empty()); - assert!(app.ui.dialog.is_none()); - } - - /// Scripts must not hang on a question: the control channel's quit never asks. - #[test] - fn control_channel_quit_does_not_ask() { - let ctx = egui::Context::default(); - let mut app = app_with_unsaved_document(); - let (req, _rx) = control::ControlRequest::new("app.quit", json!({})); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - control::handle(&mut app, ui.ctx(), &req); - }); - out.textures_delta.clear(); - assert!(quit_frame(&mut app, &ctx, true).is_empty()); - assert!(app.ui.dialog.is_none()); - } - - /// The Control panel's two-row groups were centred as if they were one row tall, so the second - /// row hung below the panel and was cut off. - #[test] - fn opening_missing_fonts_offers_repeated_replacement_and_keeps_errors_visible() { - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect":[0,0,200,200], "content":"text", "text":"Sample"})).unwrap(); - let d = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); - let sid = *d.stories.keys().next().unwrap(); - d.story_mut(sid).unwrap().format_chars(0..6, |f| { - f.over.font_family = Some("Unavailable Test Family".into()); - f.over.font_style = Some("Regular".into()); - }); - let path = std::env::temp_dir().join(format!("designcraft-font-open-{}.designcraft", std::process::id())); - app.run("file.save", json!({"path":path})).unwrap(); - app.run("file.open", json!({"path":path})).unwrap(); - let dialog = app.ui.dialog.as_mut().unwrap(); - assert_eq!(dialog.id, "findFont"); - assert_eq!(dialog.fields["onOpen"], true); - dialog.fields.insert("family".into(), json!("Unavailable Test Family")); - dialog.fields.insert("style".into(), json!("Regular")); - dialog.fields.insert("toFamily".into(), json!("Unavailable Target")); - dialog.fields.insert("toStyle".into(), json!("Regular")); - assert!(dialogs::confirm(&mut app).is_err()); - assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("error")); - app.ui.dialog.as_mut().unwrap().fields.insert("toFamily".into(), json!("Source Sans 3")); - dialogs::confirm(&mut app).unwrap(); - assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("_fonts")); - assert!(app.run("font.list", json!({})).unwrap().as_array().unwrap().iter().all(|f| f["missing"] == false)); - app.ui.dialog = None; - app.run("file.save", json!({"path":path})).unwrap(); - app.run("file.open", json!({"path":path})).unwrap(); - assert!(app.ui.dialog.is_none()); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn snap_view_uses_the_saved_switches() { - let mut ui = UiState::default(); - assert!(ui.snap_view().snap_to_guides); - assert!(!ui.snap_view().snap_to_document_grid); - assert_eq!(ui.snap_view().zone_px, 4.0); - ui.snap_to_guides = false; - ui.snap_zone = 0.0; - assert!(!ui.snap_view().snap_to_guides); - assert_eq!(ui.snap_view().zone_px, 0.0); - } - - #[test] - fn pdf_export_settings_round_trip() { - let ui = UiState::default(); - let json = serde_json::to_string(&ui).unwrap(); - let parsed: UiState = serde_json::from_str(&json).unwrap(); - assert_eq!(parsed.pdf_export, PdfExportSettings::default()); - } - - #[test] - fn pdf_export_settings_defaults() { - let settings = PdfExportSettings::default(); - assert_eq!(settings.preset, "Desktop Printing"); - assert_eq!(settings.standard, "none"); - assert!(!settings.compress_images); - assert_eq!(settings.flatten, ""); - assert!(!settings.spreads); - assert!(settings.bleed); - assert!(!settings.marks_crop); - assert!(!settings.marks_bleed); - assert!(!settings.marks_page_info); - assert_eq!(settings.marks_weight, "0.25"); - assert_eq!(settings.marks_offset, "6"); - assert!(settings.tagged); - } - - #[test] - fn pdf_export_settings_survive_missing_key() { - let json = r#"{ "language": "en" }"#; - let ui: UiState = serde_json::from_str(json).unwrap(); - assert_eq!(ui.pdf_export, PdfExportSettings::default()); - } - - /// A temporary file named `name` whose bytes aren't a document or a graphic. - fn unreadable_file(name: &str) -> std::path::PathBuf { - let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}", std::process::id())); - std::fs::write(&path, b"neither a document nor a graphic").unwrap(); - path - } - - /// The open alert dialog: (title, message). - fn alert(app: &DesignApp) -> (String, String) { - let d = app.ui.dialog.as_ref().expect("an alert is open"); - assert_eq!(d.id, "alert"); - (d.fields["title"].as_str().unwrap().to_string(), d.fields["message"].as_str().unwrap().to_string()) - } - - #[test] - fn dropped_documents_open_and_the_rest_is_placed() { - for name in ["a.designcraft", "B.IDML", "c.indd", "D.INDT"] { - assert!(opens_as_document(name), "{name}"); - } - for name in ["a.png", "b.pdf", "idml.txt", "c.idml.zip", "e.indd.zip"] { - assert!(!opens_as_document(name), "{name}"); - } - } - - /// Files without an extension: dropped, a document opens and anything else is placed; asked - /// for by the operating system, they wait for the window and then open as documents. - #[test] - fn extensionless_documents_open_by_content() { - let path = std::env::temp_dir().join(format!("designcraft-ui-{}-Brochure", std::process::id())); - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({})).unwrap(); - let bytes = designcraft_engine::cmd::base64_decode(app.run("file.serialize", json!({})).unwrap()["base64"].as_str().unwrap()); - std::fs::write(&path, bytes).unwrap(); - let p = path.to_string_lossy().to_string(); - app.open_dropped(&p).unwrap(); - assert_eq!(app.session.documents().len(), 2, "a document opens, it isn't placed"); - app.open_documents_later([p.clone()]); - assert_eq!(app.session.documents().len(), 2, "queued until the window is ready"); - app.open_os_documents(); - assert_eq!(app.session.documents().len(), 3); - assert_eq!(app.session.active().and_then(|d| d.path.clone()), Some(p)); - let _ = std::fs::remove_file(&path); - let notes = unreadable_file("notes"); - let e = app.open_dropped(¬es.to_string_lossy()).unwrap_err(); - let _ = std::fs::remove_file(¬es); - assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); - } - - #[test] - fn status_messages_follow_the_interface_language_but_engine_errors_stay_english() { - let mut app = DesignApp::new(Session::new(), Services::default()); - app.status_error("Table", "No table selected"); - assert_eq!(app.ui.status, "Table: No table selected"); - app.ui.language = "cs".into(); - app.status_error("Table", "No table selected"); - assert_eq!(app.ui.status, format!("{}: No table selected", crate::i18n::tr("cs", "Table"))); - } - - #[test] - fn dropping_an_unreadable_file_alerts() { - // A document opens, so it says it can't be opened. - let path = unreadable_file("broken.designcraft"); - let mut app = DesignApp::new(Session::new(), Services::default()); - let r = app.open_dropped(&path.to_string_lossy()); - let _ = std::fs::remove_file(&path); - let e = r.unwrap_err(); - let (title, message) = alert(&app); - assert_eq!(title, "Can't Open the File", "a document opens, it isn't placed"); - assert_eq!(message, e); - assert!(app.ui.status.contains(&e), "the status line says it too"); - assert!(app.session.documents().is_empty()); - dialogs::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "OK closes the alert"); - // Anything else is placed, so it says it can't be placed. - app.run("file.new", json!({})).unwrap(); - let path = unreadable_file("notes.xyz"); - let r = app.open_dropped(&path.to_string_lossy()); - let _ = std::fs::remove_file(&path); - let e = r.unwrap_err(); - assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); - } - - #[test] - fn a_dropped_indd_file_the_converter_rejects_alerts() { - let path = unreadable_file("brochure.indd"); - let mut app = DesignApp::new(Session::new(), Services::default()); - let r = app.open_dropped(&path.to_string_lossy()); - let _ = std::fs::remove_file(&path); - let e = r.unwrap_err(); - assert!(e.contains("InDesign file"), "{e}"); - assert_eq!(alert(&app), ("Can't Open the File".to_string(), e)); - assert!(app.session.documents().is_empty()); - } - - #[test] - fn dropping_an_ase_file_loads_its_swatches() { - let mut source = Session::new(); - source.execute("file.new", &json!({})).unwrap(); - source.execute("swatch.create", &json!({"name": "Dropped Teal", "color": "#108080"})).unwrap(); - let data = source.execute("swatch.save", &json!({"names": ["Dropped Teal"]})).unwrap(); - let bytes = designcraft_engine::cmd::base64_decode(data["base64"].as_str().unwrap()); - for name in ["palette.ase", "PALETTE.ASE"] { - let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}", std::process::id())); - std::fs::write(&path, &bytes).unwrap(); - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({})).unwrap(); - let r = app.open_dropped(&path.to_string_lossy()); - let _ = std::fs::remove_file(&path); - assert!(app.ui.dialog.is_none(), "{name}: {:?}", app.ui.dialog.as_ref().map(|d| &d.fields)); - assert_eq!(r, Ok(json!({"added": 1, "replaced": 0})), "{name}"); - let doc = &app.session.doc().unwrap().doc; - assert!(doc.swatches.iter().any(|s| s.name == "Dropped Teal"), "{name}"); - assert!(doc.assets.is_empty(), "{name} isn't placed"); - } - } - - #[test] - fn a_file_dropped_while_a_parent_is_open_lands_on_the_parent() { - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({"pages": 3})).unwrap(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); - app.run("layout.parents.edit", json!({"on": true})).unwrap(); - let _ = app.view_mut(); - let path = std::env::temp_dir().join(format!("designcraft-ui-{}-drop.png", std::process::id())); - std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); - let r = app.open_dropped(&path.to_string_lossy()); - let _ = std::fs::remove_file(&path); - r.unwrap(); - let d = &app.session.doc().unwrap().doc; - assert_eq!(d.parents[0].items.len(), 1, "the graphic is on the parent spread"); - assert!(d.spreads.iter().all(|s| s.items.is_empty()), "no document page gets it"); - } - - #[test] - fn file_open_failures_show_an_alert() { - let path = unreadable_file("open.designcraft"); - let picked = path.to_string_lossy().to_string(); - let services = Services { pick_open: Some(Box::new(move |_| Some(picked.clone()))), ..Default::default() }; - let mut app = DesignApp::new(Session::new(), services); - let e = app.run("app.openDialog", json!({})).unwrap_err(); - assert_eq!(alert(&app), ("Can't Open the File".to_string(), e)); - // Placing it says so too. - app.ui.dialog = None; - app.run("file.new", json!({})).unwrap(); - let e = app.run("app.placeDialog", json!({})).unwrap_err(); - let _ = std::fs::remove_file(&path); - assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); - } - - #[test] - fn other_command_errors_stay_in_the_status_line() { - let mut app = DesignApp::new(Session::new(), Services::default()); - assert!(app.run("file.open", json!({"path": "/nonexistent/x.designcraft"})).is_err()); - assert!(app.ui.dialog.is_none(), "a scripted file.open doesn't raise an alert"); - assert!(!app.ui.status.is_empty()); - // The control channel's app.open answers with the error; no alert waits for a click. - let (req, _rx) = control::ControlRequest::new("app.open", json!({"path": "/nonexistent/x.designcraft"})); - let control::Outcome::Done(r) = control::handle(&mut app, &egui::Context::default(), &req) else { panic!("app.open answers") }; - assert_eq!(r["ok"], json!(false), "{r}"); - assert!(app.ui.dialog.is_none(), "a control-channel app.open doesn't raise an alert"); - } - - /// Copied objects were pasted on the first spread whatever page was in view. - #[test] - fn paste_lands_on_the_spread_in_view() { - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({"pages": 3, "facingPages": false})).unwrap(); - let id = app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap()["id"].clone(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - app.run("edit.copy", json!({})).unwrap(); - let pasted_on = |app: &DesignApp| { - let st = app.session.active().unwrap(); - st.doc.find(st.selection.items[0]).unwrap().spread - }; - // Nothing is in view before the canvas is laid out: the first spread, as in a script. - app.run("edit.paste", json!({})).unwrap(); - assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Doc(0)); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); - canvas::go_to_page(&mut app, 2); - menus::activate(&mut app, "edit.pasteInPlace", &Value::Null); - assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Doc(2)); - canvas::go_to_page(&mut app, 1); - app.run("edit.paste", json!({})).unwrap(); - assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Doc(1)); - // A parent spread while parents are edited. - app.run("layout.parents.edit", json!({"on": true})).unwrap(); - app.run("edit.paste", json!({})).unwrap(); - assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Parent(0)); - // With an insertion point Paste still goes into the text, where the object is anchored. - let story = app.run("frame.create", json!({"rect": [36, 200, 300, 400], "content": "text", "text": "ab"})).unwrap()["story"].clone(); - app.run("text.select", json!({"story": story, "anchor": 2})).unwrap(); - assert_eq!(app.run("edit.paste", json!({})).unwrap()["anchored"], 1); - } - - // --------------------------------------------------------------------------------------- - // egui 0.37 lifecycle, hidden input and screenshot completion regressions. - // --------------------------------------------------------------------------------------- - - /// One frame of the real callback order the native and web hosts use. - fn shot_frame(app: &mut DesignApp, ctx: &egui::Context, size: egui::Vec2) -> egui::FullOutput { - shot_frame_at(app, ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, size), true) - } - - /// One frame at a chosen window rect. `inner_rect = false` is the web/egui_kittest shape: - /// `screen_rect` is set but `ViewportInfo::inner_rect` is not. - fn shot_frame_at(app: &mut DesignApp, ctx: &egui::Context, rect: egui::Rect, inner_rect: bool) -> egui::FullOutput { - let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; - raw.viewports.insert( - egui::ViewportId::ROOT, - egui::ViewportInfo { - inner_rect: inner_rect.then_some(rect), - native_pixels_per_point: Some(1.0), - minimized: Some(false), - occluded: Some(false), - ..Default::default() - }, - ); - let mut output = ctx.run_ui(raw, |ui| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }); - output.textures_delta.clear(); - output - } - - /// A hidden host iteration: the raw input is prepared and then only the logic callback runs. - fn hidden_tick(app: &mut DesignApp, ctx: &egui::Context, raw: &mut egui::RawInput) -> egui::LogicOutput { - app.raw_input_hook(ctx, raw); - ctx.run_logic(raw, |ctx| app.logic(ctx)) - } - - /// Build a 640x480 root viewport marked minimized and occluded. - fn hidden_raw() -> egui::RawInput { - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); - let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; - raw.viewports.insert( - egui::ViewportId::ROOT, - egui::ViewportInfo { - inner_rect: Some(rect), - native_pixels_per_point: Some(1.0), - minimized: Some(true), - occluded: Some(true), - ..Default::default() - }, - ); - raw - } - - /// Count root `RequestPaintWhileHidden` commands. - fn hidden_paints(output: &egui::LogicOutput) -> usize { - output - .viewport_commands - .get(&egui::ViewportId::ROOT) - .map_or(0, |commands| commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)).count()) - } - - /// Remove and return the root screenshot callback, replacing its command with `Focus`. - fn screenshot_callback(output: &mut egui::FullOutput) -> Option { - let viewport = output.viewport_output.get_mut(&egui::ViewportId::ROOT)?; - for command in &mut viewport.commands { - if matches!(command, egui::ViewportCommand::Screenshot(_)) { - let egui::ViewportCommand::Screenshot(callback) = std::mem::replace(command, egui::ViewportCommand::Focus) else { - return None; - }; - return Some(callback); - } - } - None - } - - /// Create a recording-write app with a new document and four settling frames. - fn screenshot_app() -> (DesignApp, egui::Context, std::sync::Arc>>) { - let writes: std::sync::Arc>> = Default::default(); - let sink = writes.clone(); - let mut app = DesignApp::new( - Session::new(), - Services { - write: Some(Box::new(move |path, bytes| { - sink.lock().unwrap().push((path.to_string(), bytes.len())); - Ok(()) - })), - ..Default::default() - }, - ); - app.run("file.new", json!({"title": "shots"})).unwrap(); - let ctx = egui::Context::default(); - for _ in 0..4 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - output.textures_delta.clear(); - } - (app, ctx, writes) - } - - /// The callback only fills a slot; the next logic pass writes and replies once and releases admission. - #[test] - fn screenshot_callback_stays_weak_and_writes_only_from_logic() { - let (mut app, ctx, writes) = screenshot_app(); - let (reply, replies) = std::sync::mpsc::channel(); - let path = std::env::temp_dir().join(format!("designcraft-shot-{}.png", std::process::id())); - app.admit_screenshot(Some(path.to_string_lossy().to_string()), reply).unwrap(); - app.queued_shots[0].1 = 0.0; - let mut callback = None; - for _ in 0..3 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - if let Some(cb) = screenshot_callback(&mut output) { - callback = Some(cb); - } - } - let callback = callback.expect("the settling frames issue one capture"); - assert!(writes.lock().unwrap().is_empty()); - // The callback only fills its slot; writing happens in the next logic pass. - callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - assert!(writes.lock().unwrap().is_empty(), "the callback must not write files"); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - let written = writes.lock().unwrap().clone(); - assert_eq!(written.len(), 1, "one file after the logic drain"); - assert_eq!(written[0].0, path.to_string_lossy()); - let reply = replies.recv().unwrap(); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(reply["result"]["width"], 640); - assert_eq!(reply["result"]["height"], 480); - assert!(app.pending_shots.is_empty(), "the reservation is released"); - } - - /// Admission enforces the request count, aggregate RGBA byte budget and per-image limit before capture. - #[test] - fn screenshot_admission_bounds_count_aggregate_and_image_bytes() { - let (mut app, ctx, _writes) = screenshot_app(); - let admit = |app: &mut DesignApp, path: &str| { - let (reply, _replies) = std::sync::mpsc::channel(); - app.admit_screenshot(Some(path.into()), reply) - }; - for i in 0..SCREENSHOT_MAX_REQUESTS { - assert!(admit(&mut app, &format!("shot-{i}.png")).is_ok(), "request {i}"); - } - let error = admit(&mut app, "too-many.png").unwrap_err(); - assert_eq!(error["ok"], false, "{error}"); - // Drain the admitted requests without replying so the byte-budget check is exercised. - app.pending_shots.clear(); - app.queued_shots.clear(); - for _ in 0..2 { - shot_frame(&mut app, &ctx, egui::vec2(5120.0, 5120.0)); - } - assert!(admit(&mut app, "hundred-a.png").is_ok()); - assert!(admit(&mut app, "hundred-b.png").is_ok()); - let error = admit(&mut app, "over-aggregate.png").unwrap_err(); - assert!(error["error"].as_str().unwrap_or_default().contains("budget"), "{error}"); - app.pending_shots.clear(); - app.queued_shots.clear(); - for _ in 0..2 { - shot_frame(&mut app, &ctx, egui::vec2(6000.0, 6000.0)); - } - let error = admit(&mut app, "too-large.png").unwrap_err(); - assert!(error["error"].as_str().unwrap_or_default().contains("image limit"), "{error}"); - } - - /// A resize invalidates in-flight pixels and retries within the deadline; a timeout errors and late callbacks are inert. - #[test] - fn screenshot_epoch_change_and_timeout_drop_stale_pixels() { - let (mut app, ctx, writes) = screenshot_app(); - let (reply, replies) = std::sync::mpsc::channel(); - app.admit_screenshot(Some("stale.png".into()), reply).unwrap(); - app.queued_shots[0].1 = 0.0; - let mut callback = None; - for _ in 0..3 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - if let Some(cb) = screenshot_callback(&mut output) { - callback = Some(cb); - } - } - let callback = callback.expect("issued"); - // Resize away and back: the epoch advances even though the size ends up the same. - shot_frame(&mut app, &ctx, egui::vec2(800.0, 600.0)); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - callback.clone().complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert!(replies.try_recv().is_err(), "stale pixels must not be replied"); - assert!(!app.queued_shots.is_empty(), "the request is retried inside its deadline"); - assert!(writes.lock().unwrap().is_empty()); - // Let the deadline pass: the retry reports an error and a later callback is inert. - app.pending_shots[0].deadline = 0.0; - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - let reply = replies.try_recv().unwrap(); - assert_eq!(reply["ok"], false, "{reply}"); - callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert!(replies.try_recv().is_err(), "no second reply from a late callback"); - assert!(writes.lock().unwrap().is_empty()); - assert!(app.pending_shots.is_empty()); - } - - /// A host without `inner_rect` uses `screen_rect` and can still admit and complete a capture. - #[test] - fn screenshot_geometry_uses_screen_rect_when_inner_rect_is_absent() { - let (mut app, ctx, writes) = screenshot_app(); - app.screenshot_geometry = None; - app.screenshot_epoch = 0; - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); - // Web eframe and egui_kittest set screen_rect but not ViewportInfo::inner_rect. - for _ in 0..2 { - shot_frame_at(&mut app, &ctx, rect, false); - } - let geometry = app.screenshot_geometry.expect("the screen rect is the logical viewport"); - assert_eq!((geometry.width, geometry.height), (640, 480), "the fallback is the same logical geometry"); - let (reply, replies) = std::sync::mpsc::channel(); - app.admit_screenshot(Some("web-like.png".into()), reply).expect("an inner-rect-less host admits screenshots"); - app.queued_shots[0].1 = 0.0; - let mut callback = None; - for _ in 0..3 { - if let Some(cb) = screenshot_callback(&mut shot_frame_at(&mut app, &ctx, rect, false)) { - callback = Some(cb); - } - } - callback.expect("the capture is issued").complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame_at(&mut app, &ctx, rect, false); - let reply = replies.recv().unwrap(); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(writes.lock().unwrap().len(), 1); - } - - /// Apply native pixels-per-point and UI zoom exactly once. - #[test] - fn screenshot_geometry_applies_native_dpi_and_zoom_once() { - let (mut app, ctx, _writes) = screenshot_app(); - app.ui.ui_scale = 1.5; - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 50.0)); - let raw = { - let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; - raw.viewports.insert( - egui::ViewportId::ROOT, - egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(2.0), minimized: Some(false), ..Default::default() }, - ); - raw - }; - // The first pass applies the zoom; the next logic tick measures the new geometry. - for _ in 0..2 { - let mut raw = raw.clone(); - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().inner_rect = Some(rect); - ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }) - .textures_delta - .clear(); - } - let geometry = app.screenshot_geometry.expect("geometry"); - // 100 x 50 points at 2 physical pixels per point and 1.5 UI zoom: apply each exactly once. - assert_eq!((geometry.width, geometry.height), (300, 150)); - } - - /// Moving the window leaves the capture epoch unchanged; resizing and resizing back advance it. - #[test] - fn screenshot_epoch_ignores_window_position_but_tracks_size_changes() { - let (mut app, ctx, _writes) = screenshot_app(); - let before = app.screenshot_epoch; - let moved = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(640.0, 480.0)); - shot_frame_at(&mut app, &ctx, moved, true); - assert_eq!(app.screenshot_epoch, before, "moving the window is not a capture-surface change"); - shot_frame_at(&mut app, &ctx, egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(800.0, 600.0)), true); - let resized = app.screenshot_epoch; - assert_ne!(resized, before, "a size change advances the epoch"); - shot_frame_at(&mut app, &ctx, egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(640.0, 480.0)), true); - assert_ne!(app.screenshot_epoch, resized, "and resizing back advances it again"); - } - - /// `ui.screenshot` is admitted, waits for capture, then writes once and replies with the dimensions. - #[test] - fn control_screenshot_replies_with_the_saved_capture() { - let (mut app, ctx, writes) = screenshot_app(); - let (requests, receiver) = std::sync::mpsc::channel(); - app = app.with_control(receiver); - let (reply, replies) = std::sync::mpsc::channel(); - requests.send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "control.png", "focus": false}), reply }).unwrap(); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert_eq!(app.pending_shots.len(), 1, "ui.screenshot is admitted, not issued from the queue"); - assert!(replies.try_recv().is_err(), "the reply waits for the capture"); - app.queued_shots[0].1 = 0.0; - let mut callback = None; - for _ in 0..3 { - if let Some(cb) = screenshot_callback(&mut shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0))) { - callback = Some(cb); - } - } - let callback = callback.expect("the settled frames issue one capture"); - callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - let reply = replies.recv().unwrap(); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(reply["result"]["width"], 640); - assert_eq!(reply["result"]["height"], 480); - let written = writes.lock().unwrap().clone(); - assert_eq!(written.len(), 1); - assert_eq!(written[0].0, "control.png"); - assert!(written[0].1 > 0); - assert!(app.pending_shots.is_empty(), "the reservation is released"); - assert!(app.queued_shots.is_empty()); - } - - /// A timed-out capture replies with a no-frame error and writes no file. - #[test] - fn control_screenshot_times_out_without_writing_a_file() { - let (mut app, ctx, writes) = screenshot_app(); - let (requests, receiver) = std::sync::mpsc::channel(); - app = app.with_control(receiver); - let (reply, replies) = std::sync::mpsc::channel(); - requests.send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "control.png", "focus": false}), reply }).unwrap(); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert_eq!(app.pending_shots.len(), 1); - app.pending_shots[0].deadline = 0.0; - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - let reply = replies.recv().unwrap(); - assert_eq!(reply["ok"], false, "{reply}"); - assert!(reply["error"].as_str().unwrap_or_default().contains("no frame"), "{reply}"); - assert!(writes.lock().unwrap().is_empty(), "a timed-out request writes no file"); - assert!(app.pending_shots.is_empty()); - } - - /// A multipass frame ticks for every pass but runs once-per-frame work once. - #[test] - fn discarded_pass_runs_the_frame_stage_once_but_ticks_every_pass() { - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({"title": "multipass"})).unwrap(); - let ctx = egui::Context::default(); - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0)); - let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; - raw.viewports - .insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), ..Default::default() }); - let mut passes = 0; - let mut output = ctx.run_ui(raw, |ui| { - passes += 1; - if passes == 1 { - // Requested before `app.ui` so the first pass is a discarded one and must not - // acknowledge injected input. - ui.ctx().request_discard("forced multipass regression"); - } - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }); - assert_eq!(output.platform_output.num_completed_passes, 2, "the frame really was multipass"); - // 0.37's TexturesDelta panics if dropped unapplied; this test only inspects the passes. - output.textures_delta.clear(); - assert_eq!(app.logic_tick_ticks, 2, "every pass ticks queues and deadlines"); - assert_eq!(app.logic_frame_ticks, 1, "once-per-frame work runs once"); - assert_eq!(app.input_ticks, 2); - } - - /// Hidden logic requests one paint per tick, injects one queued step at a time, treats unknown visibility as hidden, and lets one visible pass consume the step. - #[test] - fn hidden_logic_requests_exactly_one_paint_per_tick_until_a_settled_ui_pass() { - let (mut app, ctx, _writes) = screenshot_app(); - let mut raw = hidden_raw(); - // Three pointer steps queued: one batch may be in the host's pending raw input at a time. - app.control_synthetic = vec![ - egui::Event::PointerMoved(egui::pos2(10.0, 10.0)), - egui::Event::PointerMoved(egui::pos2(20.0, 20.0)), - egui::Event::PointerMoved(egui::pos2(30.0, 30.0)), - ]; - app.raw_input_hook(&ctx, &mut raw); - let injected = raw.events.clone(); - assert_eq!(app.injected_events.len(), 1, "one pointer event in the batch"); - assert_eq!(app.control_synthetic.len(), 2, "the rest wait for later host iterations"); - for tick in 0..3 { - let output = hidden_tick(&mut app, &ctx, &mut raw); - assert_eq!(hidden_paints(&output), 1, "tick {tick}: exactly one hidden paint request"); - assert!(app.synthetic_injected, "the injected step is still unapplied"); - assert!(app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "control provenance is retained while hidden"); - assert_eq!(raw.events, injected, "tick {tick}: no second batch accumulated into the pending raw input"); - assert_eq!(app.control_synthetic.len(), 2, "tick {tick}: the queue did not drain another step"); - } - // A real visible UI pass takes exactly the one pending event (no duplicated PointerMoved). - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().occluded = Some(false); - let mut seen = Vec::new(); - ctx.run_ui(raw, |ui| { - seen = ui.ctx().input(|i| i.events.clone()); - app.logic(&ui.ctx().clone()); - app.ui(ui); - }) - .textures_delta - .clear(); - assert_eq!(seen.iter().filter(|event| matches!(event, egui::Event::PointerMoved(_))).count(), 1); - assert!(!app.synthetic_injected, "a settled UI pass acknowledges delivery"); - assert!(app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "the pass's end guard still sees the provenance"); - app.control_synthetic.clear(); - app.raw_input_hook(&ctx, &mut egui::RawInput::default()); - assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "the next host iteration clears it"); - // Unknown visibility is treated like hidden, and the next queued step is injected. - let mut unknown = egui::RawInput::default(); - unknown.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default()); - app.control_synthetic.push(egui::Event::Text("x".into())); - app.raw_input_hook(&ctx, &mut unknown); - let output = ctx.run_logic(&unknown, |ctx| app.logic(ctx)); - assert_eq!(hidden_paints(&output), 1, "visible() == None is treated like hidden"); - } - - /// A font-gated first pass requeues injected input instead of acknowledging it; a later settled pass consumes it. - #[test] - fn font_gated_first_pass_requeues_injected_input_instead_of_acknowledging_it() { - let mut app = DesignApp::new(Session::new(), Services::default()); - app.run("file.new", json!({"title": "fonts"})).unwrap(); - let ctx = egui::Context::default(); - app.control_synthetic.push(egui::Event::Text("x".into())); - let mut raw = hidden_raw(); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_injected); - // The first real pass installs fonts and returns before any widget consumes input. - ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }) - .textures_delta - .clear(); - assert!(!app.synthetic_injected, "a font-gated pass is not an acknowledgement"); - assert_eq!(app.control_synthetic, vec![egui::Event::Text("x".into())], "the batch is back in its queue"); - assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed)); - // Once fonts are ready the same step is injected and a settled pass consumes it. - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert!(app.fonts_ready); - let mut raw = hidden_raw(); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_injected); - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); - ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }) - .textures_delta - .clear(); - assert!(!app.synthetic_injected); - assert!(app.control_synthetic.is_empty()); - } - - /// Injected input is acknowledged only by the settled multipass frame. - #[test] - fn discarded_pass_does_not_acknowledge_injected_input() { - let (mut app, ctx, _writes) = screenshot_app(); - app.control_synthetic.push(egui::Event::Text("d".into())); - let mut raw = hidden_raw(); - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_injected); - let mut passes = 0; - let output = ctx.run_ui(raw, |ui| { - passes += 1; - if passes == 1 { - ui.ctx().request_discard("injected input must survive a discarded pass"); - } - app.logic(&ui.ctx().clone()); - app.ui(ui); - }); - assert_eq!(output.platform_output.num_completed_passes, 2); - assert!(!app.synthetic_injected, "the settled second pass acknowledges it"); - assert!(app.control_synthetic.is_empty()); - } - - /// A document change drops the stale batch and removes its events from pending raw input. - #[test] - fn a_document_switch_before_the_ui_pass_drops_the_pending_batch() { - let (mut app, ctx, _writes) = screenshot_app(); - let pos = egui::pos2(10.0, 10.0); - app.control_synthetic.push(egui::Event::PointerMoved(pos)); - let mut raw = hidden_raw(); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_injected); - let _ = hidden_tick(&mut app, &ctx, &mut raw); - // A menu/control action switched documents before the forced paint. - app.run("file.new", json!({"title": "handoff"})).unwrap(); - app.raw_input_hook(&ctx, &mut raw); - assert!(!app.synthetic_injected, "the stale batch was discarded"); - assert!(app.injected_events.is_empty()); - assert!( - !raw.events.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)), - "the event was removed from pending input" - ); - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); - let mut seen = Vec::new(); - ctx.run_ui(raw, |ui| { - seen = ui.ctx().input(|i| i.events.clone()); - app.logic(&ui.ctx().clone()); - app.ui(ui); - }) - .textures_delta - .clear(); - assert!(!seen.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)), "the new document did not receive it"); - } - - /// Save a document, make an unsaved edit and return the temporary directory. - #[cfg(not(target_arch = "wasm32"))] - fn prepare_revert(app: &mut DesignApp) -> tempfile::TempDir { - let dir = tempfile::tempdir().unwrap(); - app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); - app.run("frame.create", json!({"rect": [72, 72, 144, 144], "content": "text", "text": "unsaved"})).unwrap(); - assert!(app.session.active().unwrap().is_dirty()); - dir - } - - /// Revert keeps the document uid, advances the identity epoch and clears dirty state. - #[cfg(not(target_arch = "wasm32"))] - fn revert_preserving_uid(app: &mut DesignApp) { - let before = app.session.active().unwrap(); - let (uid, epoch) = (before.uid, before.identity_epoch); - app.run("file.revert", json!({})).unwrap(); - let after = app.session.active().unwrap(); - assert_eq!(after.uid, uid, "Revert keeps the open document's stable identity"); - assert_ne!(after.identity_epoch, epoch, "Revert replaces the document state"); - assert!(!after.is_dirty()); - } - - /// Input captured before Revert is neither acknowledged nor delivered to the restored document. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_revert_discards_a_buffered_input_batch() { - let (mut app, ctx, _writes) = screenshot_app(); - let _dir = prepare_revert(&mut app); - let pos = egui::pos2(10.0, 10.0); - app.control_synthetic.push(egui::Event::PointerMoved(pos)); - let mut raw = hidden_raw(); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_injected); - revert_preserving_uid(&mut app); - app.raw_input_hook(&ctx, &mut raw); - assert!(!app.synthetic_injected, "input captured before Revert must not reach the restored document"); - assert!(app.injected_events.is_empty()); - assert!(!raw.events.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos))); - } - - /// Return `hidden_raw` with the root viewport marked visible. - #[cfg(not(target_arch = "wasm32"))] - fn visible_raw() -> egui::RawInput { - let mut raw = hidden_raw(); - let viewport = raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); - viewport.minimized = Some(false); - viewport.occluded = Some(false); - raw - } - - /// Build Cmd-key press and release events. - #[cfg(not(target_arch = "wasm32"))] - fn command_key(key: egui::Key) -> Vec { - let modifiers = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; - [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec() - } - - /// A different document with one selectable item, for an asynchronous open. - #[cfg(not(target_arch = "wasm32"))] - fn document_with_a_frame() -> Vec { - let mut session = Session::new(); - session.execute("file.new", &json!({"title": "Incoming"})).unwrap(); - session.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap(); - let serialized = session.execute("file.serialize", &json!({})).unwrap(); - designcraft_engine::cmd::base64_decode(serialized["base64"].as_str().unwrap()) - } - - /// One host iteration in eframe's order: `raw_input_hook`, then `run_ui` calling - /// `App::logic` and `App::ui` (eframe native `update`). - #[cfg(not(target_arch = "wasm32"))] - fn run_host_frame(app: &mut DesignApp, ctx: &egui::Context, mut raw: egui::RawInput) { - app.raw_input_hook(ctx, &mut raw); - ctx.run_ui(raw, |ui| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - if ctx.current_pass_index() == 0 { - app.poll_native_actions(&ctx, || None); - } - app.ui(ui); - }) - .textures_delta - .clear(); - } - - /// A native Revert runs only after the injected press/release settles; pointer state and user clipboard provenance are preserved. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_native_revert_waits_for_the_control_gesture() { - let (mut app, ctx, _writes) = screenshot_app(); - let _dir = prepare_revert(&mut app); - let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); - for pressed in [true, false] { - app.control_synthetic.push(egui::Event::PointerButton { - pos: egui::pos2(320.0, 240.0), - button: egui::PointerButton::Primary, - pressed, - modifiers: egui::Modifiers::NONE, - }); - } - for step in 0..3 { - let mut raw = visible_raw(); - app.raw_input_hook(&ctx, &mut raw); - ctx.run_ui(raw, |ui| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - if ctx.current_pass_index() == 0 { - app.poll_native_actions(&ctx, || actions.pop_front()); - } - app.ui(ui); - }) - .textures_delta - .clear(); - assert_eq!(app.session.active().unwrap().is_dirty(), step < 2, "Revert runs only after the release"); - assert_eq!(ctx.input(|input| input.pointer.primary_down()), step == 0, "pointer state is not reset by the boundary"); - } - assert!(actions.is_empty()); - assert!(app.session.active().unwrap().selection.is_empty()); - assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "native actions keep user clipboard provenance"); - } - - /// Close is cancelled and deferred while old-document input is pending, then the request survives to the next frame. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_close_waits_for_input_and_keeps_the_request() { - let (mut app, ctx, _writes) = screenshot_app(); - let _dir = prepare_revert(&mut app); - app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); - let mut raw = visible_raw(); - raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().events.push(egui::ViewportEvent::Close); - app.raw_input_hook(&ctx, &mut raw); - let mut out = ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - assert!(app.ui.dialog.is_none(), "the close dialog must not receive the old document's input"); - app.ui(ui); - }); - assert!(out.viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::CancelClose)); - out.textures_delta.clear(); - assert_eq!(app.session.documents().len(), 1); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(dialog_uid(&app), Some(app.session.active().unwrap().uid), "the close request survives the deferred frame"); - } - - /// A later control command cannot overtake queued input and eventually completes. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_control_command_waits_for_the_preceding_input() { - let (mut app, ctx, _writes) = screenshot_app(); - let (requests, receiver) = std::sync::mpsc::channel(); - app = app.with_control(receiver); - let (movement, first_reply) = ControlRequest::new("ui.move", json!({"x": 10, "y": 10})); - let (command, second_reply) = ControlRequest::new("engine.execute", json!({"command": "frame.create", "params": {"rect": [72,72,144,144]}})); - requests.send(movement).unwrap(); - requests.send(command).unwrap(); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(first_reply.try_recv().unwrap()["ok"], true); - assert!(second_reply.try_recv().is_err(), "later commands must not overtake queued input"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert!(second_reply.try_recv().is_err(), "the injected input must settle first"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(second_reply.try_recv().unwrap()["ok"], true, "the later command is eventually handled"); - } - - /// Revert targets the original document before deferred OS-open delivery resumes. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_native_revert_precedes_the_deferred_os_open() { - let (mut app, ctx, _writes) = screenshot_app(); - let dir = prepare_revert(&mut app); - let original = app.session.active().unwrap().uid; - let path = dir.path().join("incoming.designcraft"); - std::fs::write(&path, document_with_a_frame()).unwrap(); - app.open_documents_later([path.to_string_lossy().to_string()]); - app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); - let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); - let mut raw = visible_raw(); - app.raw_input_hook(&ctx, &mut raw); - ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - if ui.ctx().current_pass_index() == 0 { - app.poll_native_actions(ui.ctx(), || actions.pop_front()); - } - app.ui(ui); - }) - .textures_delta - .clear(); - assert_eq!(app.session.documents().len(), 1); - assert!(app.session.active().unwrap().is_dirty()); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.active().unwrap().uid, original); - assert!(!app.session.active().unwrap().is_dirty(), "Revert runs before delivery resumes"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 2); - assert_ne!(app.session.active().unwrap().uid, original); - assert!(!app.session.documents().iter().find(|doc| doc.uid == original).unwrap().is_dirty(), "Revert targeted the original document"); - } - - /// Preview cleanup cannot replace the input batch's document and runs after the batch settles. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_stale_preview_waits_for_the_input_batch() { - let (mut app, ctx, _writes) = screenshot_app(); - let original = app.session.active().unwrap().uid; - app.session.preview_new_document(&json!({"title": "Preview"})).unwrap(); - let preview = app.session.new_document_preview(); - assert!(preview.is_some()); - app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.new_document_preview(), preview, "preview cleanup cannot replace the input's document"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert!(app.session.new_document_preview().is_none()); - assert_eq!(app.session.active().unwrap().uid, original); - } - - /// Revert waits for Select All's forwarded text input to settle. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_native_choices_wait_for_forwarded_text_input() { - let (mut app, ctx, _writes) = screenshot_app(); - let _dir = prepare_revert(&mut app); - let mut text = String::from("native field"); - ctx.run_ui(visible_raw(), |ui| { - ui.text_edit_singleline(&mut text).request_focus(); - }) - .textures_delta - .clear(); - assert!(ctx.text_edit_focused(), "the native edit command must forward to an actual text field"); - let mut actions = std::collections::VecDeque::from([("edit.selectAll".to_owned(), Value::Null), ("file.revert".to_owned(), json!({}))]); - app.poll_native_actions(&ctx, || actions.pop_front()); - run_host_frame(&mut app, &ctx, visible_raw()); - assert!(app.session.active().unwrap().is_dirty(), "Revert waits for Select All's forwarded input"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert!(!app.session.active().unwrap().is_dirty()); - } - - /// A queued native menu event precedes and blocks deferred OS-open delivery without synthetic input. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_arriving_native_event_blocks_an_os_open_without_synthetic_input() { - let (mut app, ctx, _writes) = screenshot_app(); - let dir = prepare_revert(&mut app); - let original = app.session.active().unwrap().uid; - let path = dir.path().join("incoming.designcraft"); - std::fs::write(&path, document_with_a_frame()).unwrap(); - app.open_documents_later([path.to_string_lossy().to_string()]); - let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); - app.native_action_notifier(ctx.clone())(); - let mut raw = visible_raw(); - app.raw_input_hook(&ctx, &mut raw); - ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - assert_eq!(app.session.documents().len(), 1, "a menu event already queued by the host must precede the OS open"); - if ui.ctx().current_pass_index() == 0 { - app.poll_native_actions(ui.ctx(), || actions.pop_front()); - } - app.ui(ui); - }) - .textures_delta - .clear(); - assert!(!app.session.active().unwrap().is_dirty(), "the menu action ran in the real UI callback"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 2); - assert_ne!(app.session.active().unwrap().uid, original); - } - - /// Hidden logic-only ticks cannot execute native menu actions; a real UI pass can. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_deferred_native_action_waits_for_a_real_ui_pass() { - let (mut app, ctx, _writes) = screenshot_app(); - let _dir = prepare_revert(&mut app); - app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); - let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); - let mut raw = visible_raw(); - app.raw_input_hook(&ctx, &mut raw); - ctx.run_ui(raw, |ui| { - app.logic(&ui.ctx().clone()); - if ui.ctx().current_pass_index() == 0 { - app.poll_native_actions(ui.ctx(), || actions.pop_front()); - } - app.ui(ui); - }) - .textures_delta - .clear(); - assert!(app.session.active().unwrap().is_dirty()); - let mut raw = hidden_raw(); - app.raw_input_hook(&ctx, &mut raw); - let _ = ctx.run_logic(&raw, |ctx| app.logic(ctx)); - assert!(app.session.active().unwrap().is_dirty(), "a hidden logic-only tick must not execute native menu actions"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert!(!app.session.active().unwrap().is_dirty(), "the deferred action runs when a UI callback resumes"); - } - - /// An inbox delivery runs only after input sampled for the current document has settled, so - /// a pending Select All cannot select text in the opened document. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_inbox_open_must_not_receive_a_pending_shortcut() { - let (mut app, ctx, _writes) = screenshot_app(); - app.services.inbox = Some(Inbox::default()); - let request = app.import_request("open"); - let file = ImportedFile { request, name: "incoming.designcraft".into(), bytes: document_with_a_frame() }; - app.services.inbox.as_ref().unwrap().lock().unwrap().push(file); - app.control_synthetic.extend(command_key(egui::Key::A)); - run_host_frame(&mut app, &ctx, visible_raw()); - // A deferred delivery is handled by the next settled host iteration. - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 2, "the inbox file is still opened"); - assert!( - app.session.active().unwrap().selection.is_empty(), - "Select All sampled before the asynchronous open must not reach the opened document" - ); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_os_document_must_not_receive_a_pending_shortcut() { - let (mut app, ctx, _writes) = screenshot_app(); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("incoming.designcraft"); - std::fs::write(&path, document_with_a_frame()).unwrap(); - app.open_documents_later([path.to_string_lossy().to_string()]); - app.control_synthetic.extend(command_key(egui::Key::A)); - run_host_frame(&mut app, &ctx, visible_raw()); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 2, "the OS document is still opened"); - assert!(app.session.active().unwrap().selection.is_empty(), "Select All sampled before the OS open must not reach the opened document"); - } - - /// The intended boundary: an imported file waits while the batch that was sampled for the - /// current document is pending, and is handled once that batch has settled. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_inbox_delivery_waits_for_a_settled_batch_then_runs() { - let (mut app, ctx, _writes) = screenshot_app(); - app.services.inbox = Some(Inbox::default()); - let request = app.import_request("open"); - let file = ImportedFile { request, name: "incoming.designcraft".into(), bytes: document_with_a_frame() }; - app.services.inbox.as_ref().unwrap().lock().unwrap().push(file); - app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 1, "the delivery waited for the injected step"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 2, "the deferred delivery is not lost"); - } - - /// Deferred OS open waits for injected input and is not lost. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_host_order_os_document_waits_for_a_settled_batch_then_runs() { - let (mut app, ctx, _writes) = screenshot_app(); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("incoming.designcraft"); - std::fs::write(&path, document_with_a_frame()).unwrap(); - app.open_documents_later([path.to_string_lossy().to_string()]); - app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 1, "the OS open waited for the injected step"); - run_host_frame(&mut app, &ctx, visible_raw()); - assert_eq!(app.session.documents().len(), 2, "the deferred OS open is not lost"); - } - - /// Revert drops the buffered native drop so it cannot modify the restored document. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_revert_discards_a_buffered_native_drop() { - let (mut app, ctx) = drop_test_app(); - let dir = prepare_revert(&mut app); - let path = dir.path().join("drop.png"); - std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); - let mut raw = visible_raw_with_drop(&[&path]); - app.raw_input_hook(&ctx, &mut raw); - assert_eq!(app.pending_drops.len(), 1); - revert_preserving_uid(&mut app); - let assets_before = app.session.active().unwrap().doc.assets.len(); - run_ui_pass(&mut app, &ctx, raw); - assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "a stale native drop must not modify the restored document"); - assert!(app.pending_drops.is_empty()); - } - - /// Revert rejects pre-issue and in-flight screenshots with a document error, issues no retry and writes no pixels. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_revert_rejects_screenshots_before_issue_and_in_flight() { - for in_flight in [false, true] { - let (mut app, ctx, writes) = screenshot_app(); - let _dir = prepare_revert(&mut app); - let (reply, replies) = std::sync::mpsc::channel(); - app.admit_screenshot(Some("revert-stale.png".into()), reply).unwrap(); - app.queued_shots[0].1 = 0.0; - let mut callback = None; - if in_flight { - for _ in 0..3 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - if let Some(cb) = screenshot_callback(&mut output) { - callback = Some(cb); - } - } - assert!(callback.is_some(), "the in-flight case must actually issue a capture"); - } - revert_preserving_uid(&mut app); - if let Some(callback) = callback { - callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - } - for _ in 0..4 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert!(screenshot_callback(&mut output).is_none(), "Revert must not issue or retry an old capture (in_flight={in_flight})"); - } - let reply = replies.try_recv().expect("the replaced document's screenshot receives an error"); - assert_eq!(reply["ok"], false, "in_flight={in_flight}: {reply}"); - assert!(reply["error"].as_str().unwrap_or_default().contains("document")); - assert!(writes.lock().unwrap().is_empty(), "stale pixels must not be saved"); - assert!(app.pending_shots.is_empty()); - assert!(app.queued_shots.is_empty()); - } - } - - // --------------------------------------------------------------------------------------- - // Document-generation regressions: reused screenshot slots and buffered native drops must - // not cross a document/dialog/focus change. - // --------------------------------------------------------------------------------------- - - /// A document switch before issue errors the request and leaves no pending or queued capture. - #[test] - fn design_generation_screenshot_switch_before_issue_does_not_capture_the_new_document() { - let (mut app, ctx, writes) = screenshot_app(); - let document_a = app.session.active().unwrap().uid; - let (requests, receiver) = std::sync::mpsc::channel(); - app = app.with_control(receiver); - let (reply, replies) = std::sync::mpsc::channel(); - requests - .send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "switch-before-issue.png", "focus": false}), reply }) - .unwrap(); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - assert_eq!(app.pending_shots.len(), 1, "ui.screenshot is admitted"); - assert_eq!(app.pending_shots[0].geometry.document, document_a); - // A menu/control action switches documents before the settling rule issues the capture. - app.run("file.new", json!({"title": "handoff-before-issue"})).unwrap(); - let document_b = app.session.active().unwrap().uid; - assert_ne!(document_b, document_a); - if let Some(at) = app.queued_shots.first_mut() { - at.1 = 0.0; - } - let mut callback = None; - for _ in 0..3 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - if let Some(cb) = screenshot_callback(&mut output) { - callback = Some(cb); - } - } - if let Some(callback) = callback { - callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - } - assert!(writes.lock().unwrap().is_empty(), "the switched request must not write a file"); - let reply = replies.try_recv().expect("the switched request must receive an error receipt"); - assert_eq!(reply["ok"], false, "the old document's request must not succeed on the new one: {reply}"); - assert!(reply["error"].as_str().unwrap_or_default().contains("document"), "the error must name the document change: {reply}"); - assert!(app.pending_shots.is_empty(), "the stale request released its admission"); - assert!(app.queued_shots.is_empty(), "the stale request left no repaint token"); - } - - /// An in-flight old-document capture cannot complete or retry on the new document; the request and tokens are released. - #[test] - fn design_generation_screenshot_in_flight_after_switch_does_not_complete_on_the_new_document() { - let (mut app, ctx, writes) = screenshot_app(); - let document_a = app.session.active().unwrap().uid; - let (reply, replies) = std::sync::mpsc::channel(); - app.admit_screenshot(Some("switch-in-flight.png".into()), reply).unwrap(); - app.queued_shots[0].1 = 0.0; - let mut callback = None; - for _ in 0..3 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - if let Some(cb) = screenshot_callback(&mut output) { - callback = Some(cb); - } - } - let callback = callback.expect("the request is issued on the first document"); - assert_eq!(app.pending_shots[0].geometry.document, document_a); - // The capture is in flight on A when the app switches to B. - app.run("file.new", json!({"title": "handoff-in-flight"})).unwrap(); - assert_ne!(app.session.active().unwrap().uid, document_a); - callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - // Old code retries the stale request on B; follow any retry through a completion so the - // regression proves that B never receives the old capture. - if let Some(at) = app.queued_shots.first_mut() { - at.1 = 0.0; - } - let mut retried = None; - for _ in 0..3 { - let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - if let Some(cb) = screenshot_callback(&mut output) { - retried = Some(cb); - } - } - if let Some(retried) = retried { - retried.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); - shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); - } - assert!(writes.lock().unwrap().is_empty(), "the in-flight request must not write a file after the switch"); - let reply = replies.try_recv().expect("the in-flight request must receive an error receipt"); - assert_eq!(reply["ok"], false, "the in-flight request must not succeed on the new document: {reply}"); - assert!(reply["error"].as_str().unwrap_or_default().contains("document"), "the error must name the document change: {reply}"); - assert!(app.pending_shots.is_empty(), "the stale request released its admission"); - assert!(app.queued_shots.is_empty(), "the stale request left no repaint token"); - } - - /// Admission stamps the current session document, not cached geometry from the previous document. - #[test] - fn design_generation_screenshot_admission_uses_the_current_document_not_the_cached_geometry() { - let (mut app, _ctx, _writes) = screenshot_app(); - let document_a = app.session.active().unwrap().uid; - // `screenshot_app` populated the geometry cache for A. Switch documents without a frame - // between the switch and admission, as two control requests in one logic tick would. - app.run("file.new", json!({"title": "admission-current-document"})).unwrap(); - let document_b = app.session.active().unwrap().uid; - assert_ne!(document_b, document_a); - let (reply, replies) = std::sync::mpsc::channel(); - app.admit_screenshot(None, reply).unwrap(); - assert_eq!( - app.pending_shots[0].geometry.document, document_b, - "admission must use the current session document, not the last cached geometry" - ); - assert!(replies.try_recv().is_err(), "admission alone replies only when it fails"); - app.pending_shots.clear(); - app.queued_shots.clear(); - } - - #[cfg(not(target_arch = "wasm32"))] - #[derive(Debug)] - struct TestDroppedFile(std::path::PathBuf); - - #[cfg(not(target_arch = "wasm32"))] - impl egui::DroppedFile for TestDroppedFile { - fn path(&self) -> &std::path::Path { - &self.0 - } - - fn bytes(&self) -> Result, String> { - std::fs::read(&self.0).map_err(|error| error.to_string()) - } - } - - /// Wrap a path as an egui dropped-file handle backed by the test type. - #[cfg(not(target_arch = "wasm32"))] - fn dropped_file(path: &std::path::Path) -> egui::DroppedFileHandle { - std::sync::Arc::new(TestDroppedFile(path.to_path_buf())) - } - - /// Create a screenshot app with a fixed canvas rectangle and an initialized view for drop tests. - #[cfg(not(target_arch = "wasm32"))] - fn drop_test_app() -> (DesignApp, egui::Context) { - let (mut app, ctx, _writes) = screenshot_app(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); - let _ = app.view_mut(); - (app, ctx) - } - - /// Write a tiny unique PNG for drop tests. - #[cfg(not(target_arch = "wasm32"))] - fn temporary_png(name: &str) -> std::path::PathBuf { - let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}.png", std::process::id())); - std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); - path - } - - /// Build visible raw input with a pointer move and dropped-file handles. - #[cfg(not(target_arch = "wasm32"))] - fn visible_raw_with_drop(paths: &[&std::path::Path]) -> egui::RawInput { - let mut raw = hidden_raw(); - let viewport = raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); - viewport.minimized = Some(false); - viewport.occluded = Some(false); - raw.events.push(egui::Event::PointerMoved(egui::pos2(100.0, 100.0))); - raw.dropped_files.extend(paths.iter().map(|path| dropped_file(path))); - raw - } - - /// Run one logic-plus-UI frame and discard its texture deltas. - #[cfg(not(target_arch = "wasm32"))] - fn run_ui_pass(app: &mut DesignApp, ctx: &egui::Context, raw: egui::RawInput) { - ctx.run_ui(raw, |ui| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }) - .textures_delta - .clear(); - } - - /// A drop buffered before a document switch cannot add assets to the switched document. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_generation_native_drop_is_discarded_when_the_document_changes_before_ui() { - let (mut app, ctx) = drop_test_app(); - let path = temporary_png("drop-document-change"); - let mut raw = visible_raw_with_drop(&[&path]); - app.raw_input_hook(&ctx, &mut raw); - assert!(raw.dropped_files.is_empty(), "raw_input_hook captures the native drop"); - assert_eq!(app.pending_drops.len(), 1, "the raw drop is buffered for the UI pass"); - // A menu/control action switches documents before the settled UI pass consumes it. - app.run("file.new", json!({"title": "drop-target"})).unwrap(); - let assets_before = app.session.active().unwrap().doc.assets.len(); - run_ui_pass(&mut app, &ctx, raw); - assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land in the switched document"); - assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer"); - let _ = std::fs::remove_file(path); - } - - /// A drop buffered before a dialog opens cannot land behind it. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_generation_native_drop_is_discarded_when_a_dialog_opens_before_ui() { - let (mut app, ctx) = drop_test_app(); - let path = temporary_png("drop-dialog-change"); - let mut raw = visible_raw_with_drop(&[&path]); - app.raw_input_hook(&ctx, &mut raw); - assert_eq!(app.pending_drops.len(), 1); - app.run("app.preferences", json!({})).unwrap(); - assert!(app.ui.dialog.is_some(), "a real dialog changed the generation"); - let assets_before = app.session.active().unwrap().doc.assets.len(); - run_ui_pass(&mut app, &ctx, raw); - assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land behind the dialog"); - assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer"); - let _ = std::fs::remove_file(path); - } - - /// A keyboard-focus change invalidates a buffered drop. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_generation_native_drop_is_discarded_when_focus_changes_before_ui() { - let (mut app, ctx) = drop_test_app(); - let path = temporary_png("drop-focus-change"); - let mut raw = visible_raw_with_drop(&[&path]); - app.raw_input_hook(&ctx, &mut raw); - assert_eq!(app.pending_drops.len(), 1); - let focus = egui::Id::unique("design-generation-drop-focus"); - assert_ne!(app.input_generation().focus, Some(focus)); - ctx.memory_mut(|memory| memory.request_focus(focus)); - assert_eq!(app.input_generation().focus, Some(focus), "keyboard focus changed after the drop was buffered"); - let assets_before = app.session.active().unwrap().doc.assets.len(); - run_ui_pass(&mut app, &ctx, raw); - assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land after a focus change"); - assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer"); - let _ = std::fs::remove_file(path); - } - - /// With no generation change, every dropped file in a batch is placed. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn design_generation_native_drop_batch_without_a_change_still_places_every_file() { - let (mut app, ctx) = drop_test_app(); - let first = temporary_png("drop-batch-a"); - let second = temporary_png("drop-batch-b"); - let mut raw = visible_raw_with_drop(&[&first, &second]); - app.raw_input_hook(&ctx, &mut raw); - assert_eq!(app.pending_drops.len(), 2, "both files were captured from the raw input"); - let assets_before = app.session.active().unwrap().doc.assets.len(); - run_ui_pass(&mut app, &ctx, raw); - assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before + 2, "both files in the valid batch are placed"); - assert!(app.pending_drops.is_empty()); - let _ = std::fs::remove_file(first); - let _ = std::fs::remove_file(second); - } -} +mod tests; #[cfg(test)] mod import_warning_tests { diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs new file mode 100644 index 000000000..d554cf0dc --- /dev/null +++ b/crates/ui-egui/src/tests.rs @@ -0,0 +1,2047 @@ +use super::*; + +/// The Control panel's two-row groups were centred as if they were one row tall, so the second +/// row hung below the panel and was cut off. +#[test] +fn control_bar_shows_its_second_row() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + app.run("file.newSample", json!({})).unwrap(); + app.ui.control_bar = true; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + let bar = egui::containers::panel::PanelState::load(&h.ctx, h.ui_id().with("control_bar")).unwrap().outer_rect; + assert!(bar.height() > 40.0, "{bar:?}"); + // The X/Y/W/H group: its second row holds Y: and H:. + let group = h.ctx.read_response(egui::Id::unique(("object_control", "dimensions"))).unwrap().rect; + assert!(bar.contains(group.left_top()), "the X/Y/W/H group {group:?} is in the Control panel {bar:?}"); + assert!(group.bottom() <= bar.bottom(), "X/Y/W/H group {group:?} hangs below the Control panel {bar:?}"); +} + +#[test] +fn key_names_sent_as_text_are_dropped() { + let text = |t: &str| egui::Event::Text(t.to_string()); + let events = + || vec![text("AltGraph"), text("é"), text("Dead"), text("A"), text("Unidentified"), text("ß"), text("AudioVolumeUp"), text("ab"), text("Æ")]; + let mut raw = egui::RawInput { events: events(), ..Default::default() }; + drop_key_name_text(&mut raw, false); + assert_eq!(raw.events, vec![text("é"), text("A"), text("ß"), text("ab"), text("Æ")]); + assert!(is_key_name("F13") && is_key_name("Escape") && is_key_name("ZoomToggle") && !is_key_name("F") && !is_key_name("Fx")); + // Capitalised words (mobile autocompletion) are text. + let words = vec![text("Hello"), text("Tokyo"), text("OK"), text("Hi there")]; + let mut raw = egui::RawInput { events: words.clone(), ..Default::default() }; + drop_key_name_text(&mut raw, false); + assert_eq!(raw.events, words); + // A focused text field or a canvas text caret gets its text from the browser's input + // events, which hold whole words, key-name-like ones too ("Help"). + let mut raw = egui::RawInput { events: events(), ..Default::default() }; + drop_key_name_text(&mut raw, true); + assert_eq!(raw.events, events()); +} + +/// InDesign shows 100% K as pure black on screen unless Appearance of Black says otherwise +/// (Display All Blacks as Rich Black is its default); settings saved without the field get it too. +#[test] +fn black_shows_as_rich_black_by_default() { + assert!(UiState::default().rich_black); + let saved: UiState = serde_json::from_str("{}").unwrap(); + assert!(saved.rich_black); + let accurate: UiState = serde_json::from_str(r#"{"richBlack": false}"#).unwrap(); + assert!(!accurate.rich_black, "a saved choice is kept"); +} + +/// Tool readouts measured in picas whatever the document's units (the UI's unit is never set): +/// they follow the active document's ruler units. +#[test] +fn tool_readouts_measure_in_the_documents_units() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + assert_eq!(app.view_info().unit, Unit::Picas, "no document: the UI's default"); + app.run("file.new", json!({})).unwrap(); + app.run("document.preferences", json!({"horizontalUnits": "inches", "verticalUnits": "millimeters"})).unwrap(); + assert_eq!(app.view_info().unit, Unit::Inches); +} + +/// Save and Export PDF dialogs started in the home folder (#1653): they start beside a saved +/// document, and for one never saved in the folder of the last save or export. +#[test] +fn save_dialogs_start_beside_the_document_or_in_the_last_folder() { + use std::{cell::RefCell, rc::Rc}; + let home = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + let asked: Rc>> = Rc::default(); + let answer: Rc>> = Rc::default(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + let (seen, reply) = (asked.clone(), answer.clone()); + app.services.pick_save = Some(Box::new(move |name: &str| { + seen.borrow_mut().push(name.to_string()); + reply.borrow().clone() + })); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); + let last = |asked: &Rc>>| asked.borrow().last().cloned().unwrap_or_default(); + let export_pdf = |app: &mut DesignApp| { + app.ui.dialog = Some(dialogs::Dialog::new("pdfExport", json!({}))); + app.ui.dialog.as_mut().unwrap().fields.insert("title".into(), json!("Report")); + dialogs::confirm(app).unwrap(); + }; + + app.run("file.new", json!({})).unwrap(); + let untitled = format!("{}.designcraft", app.session.active().unwrap().doc.title); + app.run("app.saveDialog", json!({})).unwrap(); + assert_eq!(last(&asked), untitled, "never saved, nothing remembered: the system's own folder"); + + let saved = home.path().join("Brochure.designcraft"); + *answer.borrow_mut() = Some(saved.to_string_lossy().to_string()); + app.run("app.saveDialog", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(&*saved.to_string_lossy())); + // An export into another folder becomes the last folder used. + *answer.borrow_mut() = Some(elsewhere.path().join("Proof.pdf").to_string_lossy().to_string()); + export_pdf(&mut app); + *answer.borrow_mut() = None; + export_pdf(&mut app); + assert_eq!(last(&asked), home.path().join("Report.pdf").to_string_lossy(), "a saved document exports beside itself"); + + app.run("file.new", json!({})).unwrap(); + let untitled = format!("{}.designcraft", app.session.active().unwrap().doc.title); + app.run("app.saveDialog", json!({})).unwrap(); + assert_eq!(last(&asked), elsewhere.path().join(untitled).to_string_lossy(), "a new document starts in the last folder used"); +} + +/// No name (Save with no document) suggested the remembered folder itself as the file, and a +/// title with a slash moved the suggestion out of the document's folder. +#[test] +fn save_dialog_suggestions_keep_the_folder_and_only_a_file_name() { + use std::{cell::RefCell, rc::Rc}; + let folder = tempfile::tempdir().unwrap(); + let asked: Rc>> = Rc::default(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + let seen = asked.clone(); + app.services.pick_save = Some(Box::new(move |name: &str| { + seen.borrow_mut().push(name.to_string()); + None + })); + app.ui.last_save_folder = Some(folder.path().join("Docs").to_string_lossy().to_string()); + app.pick_save(""); + app.pick_save("Q1/Q2.pdf"); + assert_eq!(*asked.borrow(), ["".to_string(), folder.path().join("Docs").join("Q2.pdf").to_string_lossy().to_string()]); +} + +/// An app with one document that has an unsaved edit. +fn app_with_unsaved_document() -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + assert!(!app.session.documents()[0].is_dirty(), "a new document has nothing to save"); + app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap(); + assert!(app.session.documents()[0].is_dirty()); + app +} + +/// File ▸ Close (and its shortcut) closed a document with unsaved changes without asking, and +/// closing discards the document's recovery data too. +#[test] +fn closing_an_unsaved_document_asks_first() { + let mut app = app_with_unsaved_document(); + menus::activate(&mut app, "file.close", &Value::Null); + assert_eq!(app.session.documents().len(), 1, "the document stays open until the user answers"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("closeDocument")); + // Cancel: nothing happens. + app.ui.dialog = None; + assert!(app.session.documents()[0].is_dirty()); + // The tab's × asks too. + menus::close_document(&mut app, Some(0)); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("closeDocument")); + assert_eq!(app.session.documents().len(), 1); +} + +#[test] +fn closing_without_saving_discards_the_document() { + let mut app = app_with_unsaved_document(); + menus::close_document(&mut app, None); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn closing_with_save_writes_the_file_then_closes() { + let mut app = app_with_unsaved_document(); + let path = std::env::temp_dir().join(format!("designcraft-close-test-{}.designcraft", std::process::id())); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let saved = std::fs::metadata(&path).unwrap().len(); + app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap(); + menus::close_document(&mut app, None); + dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents().is_empty()); + let written = std::fs::metadata(&path).unwrap().len(); + std::fs::remove_file(&path).unwrap(); + assert!(written > saved, "the second frame was saved ({saved} → {written} bytes)"); +} + +/// Save on a document that has no file opens the file picker; cancelling it must not close the +/// document. (No picker service here: the same as cancelling.) +#[test] +fn a_cancelled_save_keeps_the_document_open() { + let mut app = app_with_unsaved_document(); + menus::close_document(&mut app, None); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.documents().len(), 1); + assert!(app.session.documents()[0].is_dirty()); +} + +#[test] +fn closing_a_saved_document_does_not_ask() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + menus::activate(&mut app, "file.close", &Value::Null); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialog.is_none()); +} + +/// One frame of the quit handling, with the window asked to close when `close`; returns the +/// commands sent to the window. +fn quit_frame(app: &mut DesignApp, ctx: &egui::Context, close: bool) -> Vec { + let mut raw = egui::RawInput::default(); + if close { + raw.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + } + let mut out = ctx.run_ui(raw, |ui| app.handle_quit(ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default() +} + +fn dialog_uid(app: &DesignApp) -> Option { + app.ui.dialog.as_ref().filter(|d| d.id == "closeDocument").and_then(|d| d.fields.get("uid")?.as_u64()) +} + +/// Quitting closed the window at once, losing unsaved changes (#544). +#[test] +fn quitting_with_unsaved_changes_asks_and_cancel_keeps_everything() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + let cmds = quit_frame(&mut app, &ctx, true); + assert!(cmds.contains(&egui::ViewportCommand::CancelClose), "{cmds:?}"); + assert_eq!(dialog_uid(&app), Some(app.session.documents()[0].uid)); + // Cancel: the window and the document stay as they were. + app.ui.dialog = None; + for _ in 0..2 { + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + } + assert_eq!(app.session.documents().len(), 1); + assert!(app.session.documents()[0].is_dirty()); + // A Save whose file picker is cancelled stops quitting too. + quit_frame(&mut app, &ctx, true); + dialogs::confirm(&mut app).unwrap(); + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert!(app.session.documents()[0].is_dirty()); +} + +#[test] +fn quitting_asks_about_each_unsaved_document_then_closes() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap(); + app.run("file.new", json!({})).unwrap(); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); + for (n, uid) in uids.iter().take(2).enumerate() { + assert_eq!(dialog_uid(&app), Some(*uid), "question {n}"); + assert_eq!(app.session.active().map(|d| d.uid), Some(*uid), "the document asked about is shown"); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + dialogs::confirm(&mut app).unwrap(); + let cmds = quit_frame(&mut app, &ctx, false); + assert_eq!(cmds.contains(&egui::ViewportCommand::Close), n == 1, "{cmds:?}"); + } + // All documents stay open until the backend's final close commits the decision. + assert_eq!(app.session.documents().len(), 3); + assert!(quit_frame(&mut app, &ctx, true).is_empty()); + assert!(app.session.documents().is_empty()); +} + +/// A later Cancel must not destroy documents already approved for discard. +#[test] +fn quitting_later_cancel_retains_every_document_and_active_tab() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [20, 20, 120, 120]})).unwrap(); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + let active = app.session.active().unwrap().uid; + let revisions: Vec = app.session.documents().iter().map(|d| d.revision).collect(); + let docs: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + quit_frame(&mut app, &ctx, true); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + dialogs::confirm(&mut app).unwrap(); + quit_frame(&mut app, &ctx, false); + assert_eq!(dialog_uid(&app), Some(uids[1])); + app.ui.dialog = None; + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), uids); + assert_eq!(app.session.active().unwrap().uid, active); + assert_eq!(app.session.documents().iter().map(|d| d.revision).collect::>(), revisions); + for (d, original) in app.session.documents().iter().zip(docs) { + assert!(std::sync::Arc::ptr_eq(&d.doc, &original)); + assert!(d.is_dirty()); + assert!(!d.history.undo.is_empty()); + } +} + +fn second_unsaved_document(app: &mut DesignApp) { + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [20, 20, 120, 120]})).unwrap(); +} + +fn discard_quit_dialog(app: &mut DesignApp) { + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + dialogs::confirm(app).unwrap(); +} + +#[test] +fn native_quit_prompts_restore_window_visibility_without_focusing_completed_quits() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + let commands = quit_frame(&mut app, &ctx, true); + assert!(commands.contains(&egui::ViewportCommand::CancelClose)); + for command in [egui::ViewportCommand::Visible(true), egui::ViewportCommand::Minimized(false), egui::ViewportCommand::Focus] { + assert!(commands.contains(&command), "unsaved prompt must restore the window: {commands:?}"); + } + discard_quit_dialog(&mut app); + let approved = quit_frame(&mut app, &ctx, false); + assert!(approved.contains(&egui::ViewportCommand::Close)); + let completed = quit_frame(&mut app, &ctx, true); + assert!(app.session.documents().is_empty()); + + let mut clean = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + clean.run("file.new", json!({})).unwrap(); + let clean_close = quit_frame(&mut clean, &ctx, true); + let mut control = app_with_unsaved_document(); + control.quit_without_asking = true; + let control_close = quit_frame(&mut control, &ctx, true); + for commands in [&approved, &completed, &clean_close, &control_close] { + assert!( + !commands.iter().any(|command| matches!( + command, + egui::ViewportCommand::Visible(true) | egui::ViewportCommand::Minimized(false) | egui::ViewportCommand::Focus + )), + "completed and immediate quits must not activate the window: {commands:?}" + ); + } +} + +/// Dock Quit may arrive again while the first request's dialogs are still open. +#[test] +fn repeated_native_quit_requests_preserve_partial_approvals_and_cancel() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let original_active = app.session.active().unwrap().uid; + let uids: Vec<_> = app.session.documents().iter().map(|d| d.uid).collect(); + let docs: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let directory = tempfile::tempdir().unwrap(); + app.session.recovery_dir = Some(directory.path().to_path_buf()); + app.run("file.recovery.save", json!({})).unwrap(); + assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); + assert_eq!(dialog_uid(&app), Some(uids[0])); + discard_quit_dialog(&mut app); + quit_frame(&mut app, &ctx, false); + assert_eq!(dialog_uid(&app), Some(uids[1])); + for _ in 0..3 { + assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); + assert_eq!(dialog_uid(&app), Some(uids[1])); + } + app.ui.dialog = None; // Cancel the second document, retaining the first Don't Save answer. + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.active().unwrap().uid, original_active); + assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), uids); + for (document, original) in app.session.documents().iter().zip(docs) { + assert!(std::sync::Arc::ptr_eq(&document.doc, &original)); + assert!(document.is_dirty()); + assert!(!document.history.undo.is_empty()); + assert!(directory.path().join(format!("{}.designcraft", document.uid)).exists()); + } + // A fresh Dock Quit must ask about the first document again after cancellation. + assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); + assert_eq!(dialog_uid(&app), Some(uids[0])); +} + +#[test] +fn repeated_native_quit_requests_save_and_discard_only_after_all_answers() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let uids: Vec<_> = app.session.documents().iter().map(|d| d.uid).collect(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("saved.designcraft"); + let chosen = path.to_string_lossy().to_string(); + app.services.pick_save = Some(Box::new(move |_| Some(chosen.clone()))); + app.session.recovery_dir = Some(directory.path().join("recovery")); + app.run("file.recovery.save", json!({})).unwrap(); + quit_frame(&mut app, &ctx, true); + assert_eq!(dialog_uid(&app), Some(uids[0])); + dialogs::confirm(&mut app).unwrap(); // Save the first document. + assert!(!app.session.documents()[0].is_dirty()); + quit_frame(&mut app, &ctx, false); + assert_eq!(dialog_uid(&app), Some(uids[1])); + assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); + assert_eq!(dialog_uid(&app), Some(uids[1])); + discard_quit_dialog(&mut app); + assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.documents().len(), 2); + assert!(app.session.recovery_dir.as_ref().unwrap().join(format!("{}.designcraft", uids[1])).exists()); + assert!(quit_frame(&mut app, &ctx, true).is_empty()); + assert!(app.session.documents().is_empty()); + assert!(path.exists()); + assert_eq!(designcraft_engine::Session::new().execute("file.open", &json!({"path": path})).unwrap()["index"], 0); + assert_eq!(std::fs::read_dir(app.session.recovery_dir.as_ref().unwrap()).unwrap().count(), 0); +} + +#[test] +fn quitting_first_cancel_restores_original_clean_active_document() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + app.run("file.new", json!({})).unwrap(); + let original_active = app.session.active().unwrap().uid; + quit_frame(&mut app, &ctx, true); + assert_ne!(app.session.active().unwrap().uid, original_active); + app.ui.dialog = None; + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.active().unwrap().uid, original_active); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn quitting_save_as_cancel_after_discard_keeps_all_documents() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let active = app.session.active().unwrap().uid; + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + quit_frame(&mut app, &ctx, false); + dialogs::confirm(&mut app).unwrap(); // No picker: Save As was cancelled. + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.documents().len(), 2); + assert!(app.session.documents().iter().all(|d| d.is_dirty())); + assert_eq!(app.session.active().unwrap().uid, active); +} + +#[test] +fn quitting_save_failure_after_discard_keeps_documents_and_can_retry() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let path = std::env::temp_dir() + .join(format!("designcraft-quit-missing-{}-{}", std::process::id(), app.session.active().unwrap().uid)) + .join("missing") + .join("document.designcraft"); + assert!(!path.parent().unwrap().exists()); + let picked = path.to_string_lossy().to_string(); + app.services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + quit_frame(&mut app, &ctx, false); + assert!(dialogs::confirm(&mut app).is_err()); + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.documents().len(), 2); + assert!(app.session.documents().iter().all(|d| d.is_dirty())); + // Starting over must ask about the previously discarded first document again. + quit_frame(&mut app, &ctx, true); + assert_eq!(dialog_uid(&app), Some(app.session.documents()[0].uid)); +} + +#[test] +fn quitting_save_then_later_cancel_keeps_saved_document_open() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let first = app.session.documents()[0].uid; + let path = std::env::temp_dir().join(format!("designcraft-quit-save-{}-{first}.designcraft", std::process::id())); + let picked = path.to_string_lossy().to_string(); + app.services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); + quit_frame(&mut app, &ctx, true); + dialogs::confirm(&mut app).unwrap(); + quit_frame(&mut app, &ctx, false); + assert_eq!(app.session.documents().len(), 2); + assert!(!app.session.documents()[0].is_dirty()); + assert!(path.exists()); + app.ui.dialog = None; + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.documents()[0].uid, first); + assert!(app.session.documents()[1].is_dirty()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn quitting_rechecks_discard_approval_after_a_later_edit() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let first = app.session.documents()[0].uid; + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + quit_frame(&mut app, &ctx, false); + app.run("file.activate", json!({"index": 0})).unwrap(); + app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap(); + discard_quit_dialog(&mut app); // Approval is bound to the second UID, despite the switch. + assert!(!quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(dialog_uid(&app), Some(first), "new edit needs a fresh decision"); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn quitting_final_close_rechecks_new_unsaved_document() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + second_unsaved_document(&mut app); // Arrives after Close was queued, before its event. + let new_uid = app.session.active().unwrap().uid; + assert!(quit_frame(&mut app, &ctx, true).contains(&egui::ViewportCommand::CancelClose)); + assert_eq!(dialog_uid(&app), Some(new_uid)); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn quitting_pending_save_uses_dialog_uid_after_tab_switch() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + second_unsaved_document(&mut app); + let first = app.session.documents()[0].uid; + let path = std::env::temp_dir().join(format!("designcraft-quit-uid-{}-{first}.designcraft", std::process::id())); + let picked = path.to_string_lossy().to_string(); + app.services.pick_save = Some(Box::new(move |_| Some(picked.clone()))); + quit_frame(&mut app, &ctx, true); + app.run("file.activate", json!({"index": 1})).unwrap(); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.documents()[0].path.as_deref(), path.to_str()); + assert!(!app.session.documents()[0].is_dirty()); + assert!(app.session.documents()[1].is_dirty()); + quit_frame(&mut app, &ctx, false); + assert_eq!(dialog_uid(&app), Some(app.session.documents()[1].uid)); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn quitting_discard_preserves_recovery_until_final_commit() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + let uid = app.session.active().unwrap().uid; + let dir = std::env::temp_dir().join(format!("designcraft-quit-recovery-{}-{uid}", std::process::id())); + app.session.recovery_dir = Some(dir.clone()); + app.run("file.recovery.save", json!({})).unwrap(); + let entry = dir.join(format!("{uid}.designcraft")); + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert!(entry.exists(), "a queued close is not a committed close"); + assert!(quit_frame(&mut app, &ctx, true).is_empty()); + assert!(!entry.exists(), "accepted Don't Save must not be recovered on restart"); + assert!(app.session.documents().is_empty()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn quitting_native_exit_commits_completed_approvals_before_close_event() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.session.documents().len(), 1); + app.finish_confirmed_quit().unwrap(); + assert!(app.session.documents().is_empty()); +} + +#[test] +fn quitting_native_exit_retains_incomplete_stale_and_new_document_plans() { + for case in ["incomplete", "stale", "new document"] { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + if case == "incomplete" { + second_unsaved_document(&mut app); + } + quit_frame(&mut app, &ctx, true); + discard_quit_dialog(&mut app); + quit_frame(&mut app, &ctx, false); + if case == "stale" { + app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap(); + } else if case == "new document" { + second_unsaved_document(&mut app); + } + let active = app.session.active().unwrap().uid; + let before: Vec<_> = app + .session + .documents() + .iter() + .map(|d| (d.uid, d.revision, d.doc.clone(), d.selection.items.clone(), d.history.undo.len(), d.history.redo.len())) + .collect(); + app.finish_confirmed_quit().unwrap(); + assert_eq!(app.session.documents().len(), before.len(), "{case}"); + assert_eq!(app.session.active().unwrap().uid, active, "{case}"); + for (d, (uid, revision, doc, selection, undo, redo)) in app.session.documents().iter().zip(before) { + assert_eq!( + (d.uid, d.revision, &d.selection.items, d.history.undo.len(), d.history.redo.len()), + (uid, revision, &selection, undo, redo), + "{case}" + ); + assert!(std::sync::Arc::ptr_eq(&d.doc, &doc), "{case}"); + } + } +} + +#[test] +fn quitting_without_unsaved_changes_closes_at_once() { + let ctx = egui::Context::default(); + let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + // Quit (⌘Q) closes the window like its close button. + app.run("app.quit", json!({})).unwrap(); + assert!(quit_frame(&mut app, &ctx, false).contains(&egui::ViewportCommand::Close)); + assert!(quit_frame(&mut app, &ctx, true).is_empty()); + assert!(app.ui.dialog.is_none()); +} + +/// Scripts must not hang on a question: the control channel's quit never asks. +#[test] +fn control_channel_quit_does_not_ask() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + let (req, _rx) = control::ControlRequest::new("app.quit", json!({})); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + control::handle(&mut app, ui.ctx(), &req); + }); + out.textures_delta.clear(); + assert!(quit_frame(&mut app, &ctx, true).is_empty()); + assert!(app.ui.dialog.is_none()); +} + +/// The Control panel's two-row groups were centred as if they were one row tall, so the second +/// row hung below the panel and was cut off. +#[test] +fn opening_missing_fonts_offers_repeated_replacement_and_keeps_errors_visible() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect":[0,0,200,200], "content":"text", "text":"Sample"})).unwrap(); + let d = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let sid = *d.stories.keys().next().unwrap(); + d.story_mut(sid).unwrap().format_chars(0..6, |f| { + f.over.font_family = Some("Unavailable Test Family".into()); + f.over.font_style = Some("Regular".into()); + }); + let path = std::env::temp_dir().join(format!("designcraft-font-open-{}.designcraft", std::process::id())); + app.run("file.save", json!({"path":path})).unwrap(); + app.run("file.open", json!({"path":path})).unwrap(); + let dialog = app.ui.dialog.as_mut().unwrap(); + assert_eq!(dialog.id, "findFont"); + assert_eq!(dialog.fields["onOpen"], true); + dialog.fields.insert("family".into(), json!("Unavailable Test Family")); + dialog.fields.insert("style".into(), json!("Regular")); + dialog.fields.insert("toFamily".into(), json!("Unavailable Target")); + dialog.fields.insert("toStyle".into(), json!("Regular")); + assert!(dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("error")); + app.ui.dialog.as_mut().unwrap().fields.insert("toFamily".into(), json!("Source Sans 3")); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("_fonts")); + assert!(app.run("font.list", json!({})).unwrap().as_array().unwrap().iter().all(|f| f["missing"] == false)); + app.ui.dialog = None; + app.run("file.save", json!({"path":path})).unwrap(); + app.run("file.open", json!({"path":path})).unwrap(); + assert!(app.ui.dialog.is_none()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn snap_view_uses_the_saved_switches() { + let mut ui = UiState::default(); + assert!(ui.snap_view().snap_to_guides); + assert!(!ui.snap_view().snap_to_document_grid); + assert_eq!(ui.snap_view().zone_px, 4.0); + ui.snap_to_guides = false; + ui.snap_zone = 0.0; + assert!(!ui.snap_view().snap_to_guides); + assert_eq!(ui.snap_view().zone_px, 0.0); +} + +#[test] +fn pdf_export_settings_round_trip() { + let ui = UiState::default(); + let json = serde_json::to_string(&ui).unwrap(); + let parsed: UiState = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed.pdf_export, PdfExportSettings::default()); +} + +#[test] +fn pdf_export_settings_defaults() { + let settings = PdfExportSettings::default(); + assert_eq!(settings.preset, "Desktop Printing"); + assert_eq!(settings.standard, "none"); + assert!(!settings.compress_images); + assert_eq!(settings.flatten, ""); + assert!(!settings.spreads); + assert!(settings.bleed); + assert!(!settings.marks_crop); + assert!(!settings.marks_bleed); + assert!(!settings.marks_page_info); + assert_eq!(settings.marks_weight, "0.25"); + assert_eq!(settings.marks_offset, "6"); + assert!(settings.tagged); +} + +#[test] +fn pdf_export_settings_survive_missing_key() { + let json = r#"{ "language": "en" }"#; + let ui: UiState = serde_json::from_str(json).unwrap(); + assert_eq!(ui.pdf_export, PdfExportSettings::default()); +} + +/// A temporary file named `name` whose bytes aren't a document or a graphic. +fn unreadable_file(name: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}", std::process::id())); + std::fs::write(&path, b"neither a document nor a graphic").unwrap(); + path +} + +/// The open alert dialog: (title, message). +fn alert(app: &DesignApp) -> (String, String) { + let d = app.ui.dialog.as_ref().expect("an alert is open"); + assert_eq!(d.id, "alert"); + (d.fields["title"].as_str().unwrap().to_string(), d.fields["message"].as_str().unwrap().to_string()) +} + +#[test] +fn dropped_documents_open_and_the_rest_is_placed() { + for name in ["a.designcraft", "B.IDML", "c.indd", "D.INDT"] { + assert!(opens_as_document(name), "{name}"); + } + for name in ["a.png", "b.pdf", "idml.txt", "c.idml.zip", "e.indd.zip"] { + assert!(!opens_as_document(name), "{name}"); + } +} + +/// Files without an extension: dropped, a document opens and anything else is placed; asked +/// for by the operating system, they wait for the window and then open as documents. +#[test] +fn extensionless_documents_open_by_content() { + let path = std::env::temp_dir().join(format!("designcraft-ui-{}-Brochure", std::process::id())); + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + let bytes = designcraft_engine::cmd::base64_decode(app.run("file.serialize", json!({})).unwrap()["base64"].as_str().unwrap()); + std::fs::write(&path, bytes).unwrap(); + let p = path.to_string_lossy().to_string(); + app.open_dropped(&p).unwrap(); + assert_eq!(app.session.documents().len(), 2, "a document opens, it isn't placed"); + app.open_documents_later([p.clone()]); + assert_eq!(app.session.documents().len(), 2, "queued until the window is ready"); + app.open_os_documents(); + assert_eq!(app.session.documents().len(), 3); + assert_eq!(app.session.active().and_then(|d| d.path.clone()), Some(p)); + let _ = std::fs::remove_file(&path); + let notes = unreadable_file("notes"); + let e = app.open_dropped(¬es.to_string_lossy()).unwrap_err(); + let _ = std::fs::remove_file(¬es); + assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); +} + +#[test] +fn status_messages_follow_the_interface_language_but_engine_errors_stay_english() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.status_error("Table", "No table selected"); + assert_eq!(app.ui.status, "Table: No table selected"); + app.ui.language = "cs".into(); + app.status_error("Table", "No table selected"); + assert_eq!(app.ui.status, format!("{}: No table selected", crate::i18n::tr("cs", "Table"))); +} + +#[test] +fn dropping_an_unreadable_file_alerts() { + // A document opens, so it says it can't be opened. + let path = unreadable_file("broken.designcraft"); + let mut app = DesignApp::new(Session::new(), Services::default()); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + let e = r.unwrap_err(); + let (title, message) = alert(&app); + assert_eq!(title, "Can't Open the File", "a document opens, it isn't placed"); + assert_eq!(message, e); + assert!(app.ui.status.contains(&e), "the status line says it too"); + assert!(app.session.documents().is_empty()); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "OK closes the alert"); + // Anything else is placed, so it says it can't be placed. + app.run("file.new", json!({})).unwrap(); + let path = unreadable_file("notes.xyz"); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + let e = r.unwrap_err(); + assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); +} + +#[test] +fn a_dropped_indd_file_the_converter_rejects_alerts() { + let path = unreadable_file("brochure.indd"); + let mut app = DesignApp::new(Session::new(), Services::default()); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + let e = r.unwrap_err(); + assert!(e.contains("InDesign file"), "{e}"); + assert_eq!(alert(&app), ("Can't Open the File".to_string(), e)); + assert!(app.session.documents().is_empty()); +} + +#[test] +fn dropping_an_ase_file_loads_its_swatches() { + let mut source = Session::new(); + source.execute("file.new", &json!({})).unwrap(); + source.execute("swatch.create", &json!({"name": "Dropped Teal", "color": "#108080"})).unwrap(); + let data = source.execute("swatch.save", &json!({"names": ["Dropped Teal"]})).unwrap(); + let bytes = designcraft_engine::cmd::base64_decode(data["base64"].as_str().unwrap()); + for name in ["palette.ase", "PALETTE.ASE"] { + let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + assert!(app.ui.dialog.is_none(), "{name}: {:?}", app.ui.dialog.as_ref().map(|d| &d.fields)); + assert_eq!(r, Ok(json!({"added": 1, "replaced": 0})), "{name}"); + let doc = &app.session.doc().unwrap().doc; + assert!(doc.swatches.iter().any(|s| s.name == "Dropped Teal"), "{name}"); + assert!(doc.assets.is_empty(), "{name} isn't placed"); + } +} + +#[test] +fn a_file_dropped_while_a_parent_is_open_lands_on_the_parent() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + app.run("layout.parents.edit", json!({"on": true})).unwrap(); + let _ = app.view_mut(); + let path = std::env::temp_dir().join(format!("designcraft-ui-{}-drop.png", std::process::id())); + std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + r.unwrap(); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.parents[0].items.len(), 1, "the graphic is on the parent spread"); + assert!(d.spreads.iter().all(|s| s.items.is_empty()), "no document page gets it"); +} + +#[test] +fn file_open_failures_show_an_alert() { + let path = unreadable_file("open.designcraft"); + let picked = path.to_string_lossy().to_string(); + let services = Services { pick_open: Some(Box::new(move |_| Some(picked.clone()))), ..Default::default() }; + let mut app = DesignApp::new(Session::new(), services); + let e = app.run("app.openDialog", json!({})).unwrap_err(); + assert_eq!(alert(&app), ("Can't Open the File".to_string(), e)); + // Placing it says so too. + app.ui.dialog = None; + app.run("file.new", json!({})).unwrap(); + let e = app.run("app.placeDialog", json!({})).unwrap_err(); + let _ = std::fs::remove_file(&path); + assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); +} + +#[test] +fn other_command_errors_stay_in_the_status_line() { + let mut app = DesignApp::new(Session::new(), Services::default()); + assert!(app.run("file.open", json!({"path": "/nonexistent/x.designcraft"})).is_err()); + assert!(app.ui.dialog.is_none(), "a scripted file.open doesn't raise an alert"); + assert!(!app.ui.status.is_empty()); + // The control channel's app.open answers with the error; no alert waits for a click. + let (req, _rx) = control::ControlRequest::new("app.open", json!({"path": "/nonexistent/x.designcraft"})); + let control::Outcome::Done(r) = control::handle(&mut app, &egui::Context::default(), &req) else { panic!("app.open answers") }; + assert_eq!(r["ok"], json!(false), "{r}"); + assert!(app.ui.dialog.is_none(), "a control-channel app.open doesn't raise an alert"); +} + +/// Copied objects were pasted on the first spread whatever page was in view. +#[test] +fn paste_lands_on_the_spread_in_view() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"pages": 3, "facingPages": false})).unwrap(); + let id = app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + let pasted_on = |app: &DesignApp| { + let st = app.session.active().unwrap(); + st.doc.find(st.selection.items[0]).unwrap().spread + }; + // Nothing is in view before the canvas is laid out: the first spread, as in a script. + app.run("edit.paste", json!({})).unwrap(); + assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Doc(0)); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + canvas::go_to_page(&mut app, 2); + menus::activate(&mut app, "edit.pasteInPlace", &Value::Null); + assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Doc(2)); + canvas::go_to_page(&mut app, 1); + app.run("edit.paste", json!({})).unwrap(); + assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Doc(1)); + // A parent spread while parents are edited. + app.run("layout.parents.edit", json!({"on": true})).unwrap(); + app.run("edit.paste", json!({})).unwrap(); + assert_eq!(pasted_on(&app), designcraft_doc::SpreadRef::Parent(0)); + // With an insertion point Paste still goes into the text, where the object is anchored. + let story = app.run("frame.create", json!({"rect": [36, 200, 300, 400], "content": "text", "text": "ab"})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 2})).unwrap(); + assert_eq!(app.run("edit.paste", json!({})).unwrap()["anchored"], 1); +} + +// --------------------------------------------------------------------------------------- +// egui 0.37 lifecycle, hidden input and screenshot completion regressions. +// --------------------------------------------------------------------------------------- + +/// One frame of the real callback order the native and web hosts use. +fn shot_frame(app: &mut DesignApp, ctx: &egui::Context, size: egui::Vec2) -> egui::FullOutput { + shot_frame_at(app, ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, size), true) +} + +/// One frame at a chosen window rect. `inner_rect = false` is the web/egui_kittest shape: +/// `screen_rect` is set but `ViewportInfo::inner_rect` is not. +fn shot_frame_at(app: &mut DesignApp, ctx: &egui::Context, rect: egui::Rect, inner_rect: bool) -> egui::FullOutput { + let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + raw.viewports.insert( + egui::ViewportId::ROOT, + egui::ViewportInfo { + inner_rect: inner_rect.then_some(rect), + native_pixels_per_point: Some(1.0), + minimized: Some(false), + occluded: Some(false), + ..Default::default() + }, + ); + let mut output = ctx.run_ui(raw, |ui| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }); + output.textures_delta.clear(); + output +} + +/// A hidden host iteration: the raw input is prepared and then only the logic callback runs. +fn hidden_tick(app: &mut DesignApp, ctx: &egui::Context, raw: &mut egui::RawInput) -> egui::LogicOutput { + app.raw_input_hook(ctx, raw); + ctx.run_logic(raw, |ctx| app.logic(ctx)) +} + +/// Build a 640x480 root viewport marked minimized and occluded. +fn hidden_raw() -> egui::RawInput { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); + let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + raw.viewports.insert( + egui::ViewportId::ROOT, + egui::ViewportInfo { + inner_rect: Some(rect), + native_pixels_per_point: Some(1.0), + minimized: Some(true), + occluded: Some(true), + ..Default::default() + }, + ); + raw +} + +/// Count root `RequestPaintWhileHidden` commands. +fn hidden_paints(output: &egui::LogicOutput) -> usize { + output + .viewport_commands + .get(&egui::ViewportId::ROOT) + .map_or(0, |commands| commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)).count()) +} + +/// Remove and return the root screenshot callback, replacing its command with `Focus`. +fn screenshot_callback(output: &mut egui::FullOutput) -> Option { + let viewport = output.viewport_output.get_mut(&egui::ViewportId::ROOT)?; + for command in &mut viewport.commands { + if matches!(command, egui::ViewportCommand::Screenshot(_)) { + let egui::ViewportCommand::Screenshot(callback) = std::mem::replace(command, egui::ViewportCommand::Focus) else { + return None; + }; + return Some(callback); + } + } + None +} + +/// Create a recording-write app with a new document and four settling frames. +fn screenshot_app() -> (DesignApp, egui::Context, std::sync::Arc>>) { + let writes: std::sync::Arc>> = Default::default(); + let sink = writes.clone(); + let mut app = DesignApp::new( + Session::new(), + Services { + write: Some(Box::new(move |path, bytes| { + sink.lock().unwrap().push((path.to_string(), bytes.len())); + Ok(()) + })), + ..Default::default() + }, + ); + app.run("file.new", json!({"title": "shots"})).unwrap(); + let ctx = egui::Context::default(); + for _ in 0..4 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + output.textures_delta.clear(); + } + (app, ctx, writes) +} + +/// The callback only fills a slot; the next logic pass writes and replies once and releases admission. +#[test] +fn screenshot_callback_stays_weak_and_writes_only_from_logic() { + let (mut app, ctx, writes) = screenshot_app(); + let (reply, replies) = std::sync::mpsc::channel(); + let path = std::env::temp_dir().join(format!("designcraft-shot-{}.png", std::process::id())); + app.admit_screenshot(Some(path.to_string_lossy().to_string()), reply).unwrap(); + app.queued_shots[0].1 = 0.0; + let mut callback = None; + for _ in 0..3 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + if let Some(cb) = screenshot_callback(&mut output) { + callback = Some(cb); + } + } + let callback = callback.expect("the settling frames issue one capture"); + assert!(writes.lock().unwrap().is_empty()); + // The callback only fills its slot; writing happens in the next logic pass. + callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + assert!(writes.lock().unwrap().is_empty(), "the callback must not write files"); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + let written = writes.lock().unwrap().clone(); + assert_eq!(written.len(), 1, "one file after the logic drain"); + assert_eq!(written[0].0, path.to_string_lossy()); + let reply = replies.recv().unwrap(); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["width"], 640); + assert_eq!(reply["result"]["height"], 480); + assert!(app.pending_shots.is_empty(), "the reservation is released"); +} + +/// Admission enforces the request count, aggregate RGBA byte budget and per-image limit before capture. +#[test] +fn screenshot_admission_bounds_count_aggregate_and_image_bytes() { + let (mut app, ctx, _writes) = screenshot_app(); + let admit = |app: &mut DesignApp, path: &str| { + let (reply, _replies) = std::sync::mpsc::channel(); + app.admit_screenshot(Some(path.into()), reply) + }; + for i in 0..SCREENSHOT_MAX_REQUESTS { + assert!(admit(&mut app, &format!("shot-{i}.png")).is_ok(), "request {i}"); + } + let error = admit(&mut app, "too-many.png").unwrap_err(); + assert_eq!(error["ok"], false, "{error}"); + // Drain the admitted requests without replying so the byte-budget check is exercised. + app.pending_shots.clear(); + app.queued_shots.clear(); + for _ in 0..2 { + shot_frame(&mut app, &ctx, egui::vec2(5120.0, 5120.0)); + } + assert!(admit(&mut app, "hundred-a.png").is_ok()); + assert!(admit(&mut app, "hundred-b.png").is_ok()); + let error = admit(&mut app, "over-aggregate.png").unwrap_err(); + assert!(error["error"].as_str().unwrap_or_default().contains("budget"), "{error}"); + app.pending_shots.clear(); + app.queued_shots.clear(); + for _ in 0..2 { + shot_frame(&mut app, &ctx, egui::vec2(6000.0, 6000.0)); + } + let error = admit(&mut app, "too-large.png").unwrap_err(); + assert!(error["error"].as_str().unwrap_or_default().contains("image limit"), "{error}"); +} + +/// A resize invalidates in-flight pixels and retries within the deadline; a timeout errors and late callbacks are inert. +#[test] +fn screenshot_epoch_change_and_timeout_drop_stale_pixels() { + let (mut app, ctx, writes) = screenshot_app(); + let (reply, replies) = std::sync::mpsc::channel(); + app.admit_screenshot(Some("stale.png".into()), reply).unwrap(); + app.queued_shots[0].1 = 0.0; + let mut callback = None; + for _ in 0..3 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + if let Some(cb) = screenshot_callback(&mut output) { + callback = Some(cb); + } + } + let callback = callback.expect("issued"); + // Resize away and back: the epoch advances even though the size ends up the same. + shot_frame(&mut app, &ctx, egui::vec2(800.0, 600.0)); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + callback.clone().complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert!(replies.try_recv().is_err(), "stale pixels must not be replied"); + assert!(!app.queued_shots.is_empty(), "the request is retried inside its deadline"); + assert!(writes.lock().unwrap().is_empty()); + // Let the deadline pass: the retry reports an error and a later callback is inert. + app.pending_shots[0].deadline = 0.0; + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + let reply = replies.try_recv().unwrap(); + assert_eq!(reply["ok"], false, "{reply}"); + callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert!(replies.try_recv().is_err(), "no second reply from a late callback"); + assert!(writes.lock().unwrap().is_empty()); + assert!(app.pending_shots.is_empty()); +} + +/// A host without `inner_rect` uses `screen_rect` and can still admit and complete a capture. +#[test] +fn screenshot_geometry_uses_screen_rect_when_inner_rect_is_absent() { + let (mut app, ctx, writes) = screenshot_app(); + app.screenshot_geometry = None; + app.screenshot_epoch = 0; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); + // Web eframe and egui_kittest set screen_rect but not ViewportInfo::inner_rect. + for _ in 0..2 { + shot_frame_at(&mut app, &ctx, rect, false); + } + let geometry = app.screenshot_geometry.expect("the screen rect is the logical viewport"); + assert_eq!((geometry.width, geometry.height), (640, 480), "the fallback is the same logical geometry"); + let (reply, replies) = std::sync::mpsc::channel(); + app.admit_screenshot(Some("web-like.png".into()), reply).expect("an inner-rect-less host admits screenshots"); + app.queued_shots[0].1 = 0.0; + let mut callback = None; + for _ in 0..3 { + if let Some(cb) = screenshot_callback(&mut shot_frame_at(&mut app, &ctx, rect, false)) { + callback = Some(cb); + } + } + callback.expect("the capture is issued").complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame_at(&mut app, &ctx, rect, false); + let reply = replies.recv().unwrap(); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(writes.lock().unwrap().len(), 1); +} + +/// Apply native pixels-per-point and UI zoom exactly once. +#[test] +fn screenshot_geometry_applies_native_dpi_and_zoom_once() { + let (mut app, ctx, _writes) = screenshot_app(); + app.ui.ui_scale = 1.5; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 50.0)); + let raw = { + let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + raw.viewports.insert( + egui::ViewportId::ROOT, + egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(2.0), minimized: Some(false), ..Default::default() }, + ); + raw + }; + // The first pass applies the zoom; the next logic tick measures the new geometry. + for _ in 0..2 { + let mut raw = raw.clone(); + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().inner_rect = Some(rect); + ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }) + .textures_delta + .clear(); + } + let geometry = app.screenshot_geometry.expect("geometry"); + // 100 x 50 points at 2 physical pixels per point and 1.5 UI zoom: apply each exactly once. + assert_eq!((geometry.width, geometry.height), (300, 150)); +} + +/// Moving the window leaves the capture epoch unchanged; resizing and resizing back advance it. +#[test] +fn screenshot_epoch_ignores_window_position_but_tracks_size_changes() { + let (mut app, ctx, _writes) = screenshot_app(); + let before = app.screenshot_epoch; + let moved = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(640.0, 480.0)); + shot_frame_at(&mut app, &ctx, moved, true); + assert_eq!(app.screenshot_epoch, before, "moving the window is not a capture-surface change"); + shot_frame_at(&mut app, &ctx, egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(800.0, 600.0)), true); + let resized = app.screenshot_epoch; + assert_ne!(resized, before, "a size change advances the epoch"); + shot_frame_at(&mut app, &ctx, egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(640.0, 480.0)), true); + assert_ne!(app.screenshot_epoch, resized, "and resizing back advances it again"); +} + +/// `ui.screenshot` is admitted, waits for capture, then writes once and replies with the dimensions. +#[test] +fn control_screenshot_replies_with_the_saved_capture() { + let (mut app, ctx, writes) = screenshot_app(); + let (requests, receiver) = std::sync::mpsc::channel(); + app = app.with_control(receiver); + let (reply, replies) = std::sync::mpsc::channel(); + requests.send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "control.png", "focus": false}), reply }).unwrap(); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert_eq!(app.pending_shots.len(), 1, "ui.screenshot is admitted, not issued from the queue"); + assert!(replies.try_recv().is_err(), "the reply waits for the capture"); + app.queued_shots[0].1 = 0.0; + let mut callback = None; + for _ in 0..3 { + if let Some(cb) = screenshot_callback(&mut shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0))) { + callback = Some(cb); + } + } + let callback = callback.expect("the settled frames issue one capture"); + callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + let reply = replies.recv().unwrap(); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["width"], 640); + assert_eq!(reply["result"]["height"], 480); + let written = writes.lock().unwrap().clone(); + assert_eq!(written.len(), 1); + assert_eq!(written[0].0, "control.png"); + assert!(written[0].1 > 0); + assert!(app.pending_shots.is_empty(), "the reservation is released"); + assert!(app.queued_shots.is_empty()); +} + +/// A timed-out capture replies with a no-frame error and writes no file. +#[test] +fn control_screenshot_times_out_without_writing_a_file() { + let (mut app, ctx, writes) = screenshot_app(); + let (requests, receiver) = std::sync::mpsc::channel(); + app = app.with_control(receiver); + let (reply, replies) = std::sync::mpsc::channel(); + requests.send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "control.png", "focus": false}), reply }).unwrap(); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert_eq!(app.pending_shots.len(), 1); + app.pending_shots[0].deadline = 0.0; + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + let reply = replies.recv().unwrap(); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("no frame"), "{reply}"); + assert!(writes.lock().unwrap().is_empty(), "a timed-out request writes no file"); + assert!(app.pending_shots.is_empty()); +} + +/// A multipass frame ticks for every pass but runs once-per-frame work once. +#[test] +fn discarded_pass_runs_the_frame_stage_once_but_ticks_every_pass() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"title": "multipass"})).unwrap(); + let ctx = egui::Context::default(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0)); + let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + raw.viewports + .insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), ..Default::default() }); + let mut passes = 0; + let mut output = ctx.run_ui(raw, |ui| { + passes += 1; + if passes == 1 { + // Requested before `app.ui` so the first pass is a discarded one and must not + // acknowledge injected input. + ui.ctx().request_discard("forced multipass regression"); + } + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }); + assert_eq!(output.platform_output.num_completed_passes, 2, "the frame really was multipass"); + // 0.37's TexturesDelta panics if dropped unapplied; this test only inspects the passes. + output.textures_delta.clear(); + assert_eq!(app.logic_tick_ticks, 2, "every pass ticks queues and deadlines"); + assert_eq!(app.logic_frame_ticks, 1, "once-per-frame work runs once"); + assert_eq!(app.input_ticks, 2); +} + +/// Hidden logic requests one paint per tick, injects one queued step at a time, treats unknown visibility as hidden, and lets one visible pass consume the step. +#[test] +fn hidden_logic_requests_exactly_one_paint_per_tick_until_a_settled_ui_pass() { + let (mut app, ctx, _writes) = screenshot_app(); + let mut raw = hidden_raw(); + // Three pointer steps queued: one batch may be in the host's pending raw input at a time. + app.control_synthetic = vec![ + egui::Event::PointerMoved(egui::pos2(10.0, 10.0)), + egui::Event::PointerMoved(egui::pos2(20.0, 20.0)), + egui::Event::PointerMoved(egui::pos2(30.0, 30.0)), + ]; + app.raw_input_hook(&ctx, &mut raw); + let injected = raw.events.clone(); + assert_eq!(app.injected_events.len(), 1, "one pointer event in the batch"); + assert_eq!(app.control_synthetic.len(), 2, "the rest wait for later host iterations"); + for tick in 0..3 { + let output = hidden_tick(&mut app, &ctx, &mut raw); + assert_eq!(hidden_paints(&output), 1, "tick {tick}: exactly one hidden paint request"); + assert!(app.synthetic_injected, "the injected step is still unapplied"); + assert!(app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "control provenance is retained while hidden"); + assert_eq!(raw.events, injected, "tick {tick}: no second batch accumulated into the pending raw input"); + assert_eq!(app.control_synthetic.len(), 2, "tick {tick}: the queue did not drain another step"); + } + // A real visible UI pass takes exactly the one pending event (no duplicated PointerMoved). + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().occluded = Some(false); + let mut seen = Vec::new(); + ctx.run_ui(raw, |ui| { + seen = ui.ctx().input(|i| i.events.clone()); + app.logic(&ui.ctx().clone()); + app.ui(ui); + }) + .textures_delta + .clear(); + assert_eq!(seen.iter().filter(|event| matches!(event, egui::Event::PointerMoved(_))).count(), 1); + assert!(!app.synthetic_injected, "a settled UI pass acknowledges delivery"); + assert!(app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "the pass's end guard still sees the provenance"); + app.control_synthetic.clear(); + app.raw_input_hook(&ctx, &mut egui::RawInput::default()); + assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "the next host iteration clears it"); + // Unknown visibility is treated like hidden, and the next queued step is injected. + let mut unknown = egui::RawInput::default(); + unknown.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default()); + app.control_synthetic.push(egui::Event::Text("x".into())); + app.raw_input_hook(&ctx, &mut unknown); + let output = ctx.run_logic(&unknown, |ctx| app.logic(ctx)); + assert_eq!(hidden_paints(&output), 1, "visible() == None is treated like hidden"); +} + +/// A font-gated first pass requeues injected input instead of acknowledging it; a later settled pass consumes it. +#[test] +fn font_gated_first_pass_requeues_injected_input_instead_of_acknowledging_it() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"title": "fonts"})).unwrap(); + let ctx = egui::Context::default(); + app.control_synthetic.push(egui::Event::Text("x".into())); + let mut raw = hidden_raw(); + app.raw_input_hook(&ctx, &mut raw); + assert!(app.synthetic_injected); + // The first real pass installs fonts and returns before any widget consumes input. + ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }) + .textures_delta + .clear(); + assert!(!app.synthetic_injected, "a font-gated pass is not an acknowledgement"); + assert_eq!(app.control_synthetic, vec![egui::Event::Text("x".into())], "the batch is back in its queue"); + assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed)); + // Once fonts are ready the same step is injected and a settled pass consumes it. + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert!(app.fonts_ready); + let mut raw = hidden_raw(); + app.raw_input_hook(&ctx, &mut raw); + assert!(app.synthetic_injected); + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); + ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }) + .textures_delta + .clear(); + assert!(!app.synthetic_injected); + assert!(app.control_synthetic.is_empty()); +} + +/// Injected input is acknowledged only by the settled multipass frame. +#[test] +fn discarded_pass_does_not_acknowledge_injected_input() { + let (mut app, ctx, _writes) = screenshot_app(); + app.control_synthetic.push(egui::Event::Text("d".into())); + let mut raw = hidden_raw(); + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); + app.raw_input_hook(&ctx, &mut raw); + assert!(app.synthetic_injected); + let mut passes = 0; + let output = ctx.run_ui(raw, |ui| { + passes += 1; + if passes == 1 { + ui.ctx().request_discard("injected input must survive a discarded pass"); + } + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + assert_eq!(output.platform_output.num_completed_passes, 2); + assert!(!app.synthetic_injected, "the settled second pass acknowledges it"); + assert!(app.control_synthetic.is_empty()); +} + +/// A document change drops the stale batch and removes its events from pending raw input. +#[test] +fn a_document_switch_before_the_ui_pass_drops_the_pending_batch() { + let (mut app, ctx, _writes) = screenshot_app(); + let pos = egui::pos2(10.0, 10.0); + app.control_synthetic.push(egui::Event::PointerMoved(pos)); + let mut raw = hidden_raw(); + app.raw_input_hook(&ctx, &mut raw); + assert!(app.synthetic_injected); + let _ = hidden_tick(&mut app, &ctx, &mut raw); + // A menu/control action switched documents before the forced paint. + app.run("file.new", json!({"title": "handoff"})).unwrap(); + app.raw_input_hook(&ctx, &mut raw); + assert!(!app.synthetic_injected, "the stale batch was discarded"); + assert!(app.injected_events.is_empty()); + assert!(!raw.events.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)), "the event was removed from pending input"); + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false); + let mut seen = Vec::new(); + ctx.run_ui(raw, |ui| { + seen = ui.ctx().input(|i| i.events.clone()); + app.logic(&ui.ctx().clone()); + app.ui(ui); + }) + .textures_delta + .clear(); + assert!(!seen.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)), "the new document did not receive it"); +} + +/// Save a document, make an unsaved edit and return the temporary directory. +#[cfg(not(target_arch = "wasm32"))] +fn prepare_revert(app: &mut DesignApp) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 144, 144], "content": "text", "text": "unsaved"})).unwrap(); + assert!(app.session.active().unwrap().is_dirty()); + dir +} + +/// Revert keeps the document uid, advances the identity epoch and clears dirty state. +#[cfg(not(target_arch = "wasm32"))] +fn revert_preserving_uid(app: &mut DesignApp) { + let before = app.session.active().unwrap(); + let (uid, epoch) = (before.uid, before.identity_epoch); + app.run("file.revert", json!({})).unwrap(); + let after = app.session.active().unwrap(); + assert_eq!(after.uid, uid, "Revert keeps the open document's stable identity"); + assert_ne!(after.identity_epoch, epoch, "Revert replaces the document state"); + assert!(!after.is_dirty()); +} + +/// Input captured before Revert is neither acknowledged nor delivered to the restored document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_revert_discards_a_buffered_input_batch() { + let (mut app, ctx, _writes) = screenshot_app(); + let _dir = prepare_revert(&mut app); + let pos = egui::pos2(10.0, 10.0); + app.control_synthetic.push(egui::Event::PointerMoved(pos)); + let mut raw = hidden_raw(); + app.raw_input_hook(&ctx, &mut raw); + assert!(app.synthetic_injected); + revert_preserving_uid(&mut app); + app.raw_input_hook(&ctx, &mut raw); + assert!(!app.synthetic_injected, "input captured before Revert must not reach the restored document"); + assert!(app.injected_events.is_empty()); + assert!(!raw.events.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos))); +} + +/// Return `hidden_raw` with the root viewport marked visible. +#[cfg(not(target_arch = "wasm32"))] +fn visible_raw() -> egui::RawInput { + let mut raw = hidden_raw(); + let viewport = raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); + viewport.minimized = Some(false); + viewport.occluded = Some(false); + raw +} + +/// Build Cmd-key press and release events. +#[cfg(not(target_arch = "wasm32"))] +fn command_key(key: egui::Key) -> Vec { + let modifiers = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; + [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec() +} + +/// A different document with one selectable item, for an asynchronous open. +#[cfg(not(target_arch = "wasm32"))] +fn document_with_a_frame() -> Vec { + let mut session = Session::new(); + session.execute("file.new", &json!({"title": "Incoming"})).unwrap(); + session.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap(); + let serialized = session.execute("file.serialize", &json!({})).unwrap(); + designcraft_engine::cmd::base64_decode(serialized["base64"].as_str().unwrap()) +} + +/// One host iteration in eframe's order: `raw_input_hook`, then `run_ui` calling +/// `App::logic` and `App::ui` (eframe native `update`). +#[cfg(not(target_arch = "wasm32"))] +fn run_host_frame(app: &mut DesignApp, ctx: &egui::Context, mut raw: egui::RawInput) { + app.raw_input_hook(ctx, &mut raw); + ctx.run_ui(raw, |ui| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + if ctx.current_pass_index() == 0 { + app.poll_native_actions(&ctx, || None); + } + app.ui(ui); + }) + .textures_delta + .clear(); +} + +/// A native Revert runs only after the injected press/release settles; pointer state and user clipboard provenance are preserved. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_native_revert_waits_for_the_control_gesture() { + let (mut app, ctx, _writes) = screenshot_app(); + let _dir = prepare_revert(&mut app); + let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); + for pressed in [true, false] { + app.control_synthetic.push(egui::Event::PointerButton { + pos: egui::pos2(320.0, 240.0), + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + for step in 0..3 { + let mut raw = visible_raw(); + app.raw_input_hook(&ctx, &mut raw); + ctx.run_ui(raw, |ui| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + if ctx.current_pass_index() == 0 { + app.poll_native_actions(&ctx, || actions.pop_front()); + } + app.ui(ui); + }) + .textures_delta + .clear(); + assert_eq!(app.session.active().unwrap().is_dirty(), step < 2, "Revert runs only after the release"); + assert_eq!(ctx.input(|input| input.pointer.primary_down()), step == 0, "pointer state is not reset by the boundary"); + } + assert!(actions.is_empty()); + assert!(app.session.active().unwrap().selection.is_empty()); + assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "native actions keep user clipboard provenance"); +} + +/// Close is cancelled and deferred while old-document input is pending, then the request survives to the next frame. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_close_waits_for_input_and_keeps_the_request() { + let (mut app, ctx, _writes) = screenshot_app(); + let _dir = prepare_revert(&mut app); + app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); + let mut raw = visible_raw(); + raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().events.push(egui::ViewportEvent::Close); + app.raw_input_hook(&ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + assert!(app.ui.dialog.is_none(), "the close dialog must not receive the old document's input"); + app.ui(ui); + }); + assert!(out.viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::CancelClose)); + out.textures_delta.clear(); + assert_eq!(app.session.documents().len(), 1); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(dialog_uid(&app), Some(app.session.active().unwrap().uid), "the close request survives the deferred frame"); +} + +/// A later control command cannot overtake queued input and eventually completes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_control_command_waits_for_the_preceding_input() { + let (mut app, ctx, _writes) = screenshot_app(); + let (requests, receiver) = std::sync::mpsc::channel(); + app = app.with_control(receiver); + let (movement, first_reply) = ControlRequest::new("ui.move", json!({"x": 10, "y": 10})); + let (command, second_reply) = ControlRequest::new("engine.execute", json!({"command": "frame.create", "params": {"rect": [72,72,144,144]}})); + requests.send(movement).unwrap(); + requests.send(command).unwrap(); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(first_reply.try_recv().unwrap()["ok"], true); + assert!(second_reply.try_recv().is_err(), "later commands must not overtake queued input"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert!(second_reply.try_recv().is_err(), "the injected input must settle first"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(second_reply.try_recv().unwrap()["ok"], true, "the later command is eventually handled"); +} + +/// Revert targets the original document before deferred OS-open delivery resumes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_native_revert_precedes_the_deferred_os_open() { + let (mut app, ctx, _writes) = screenshot_app(); + let dir = prepare_revert(&mut app); + let original = app.session.active().unwrap().uid; + let path = dir.path().join("incoming.designcraft"); + std::fs::write(&path, document_with_a_frame()).unwrap(); + app.open_documents_later([path.to_string_lossy().to_string()]); + app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); + let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); + let mut raw = visible_raw(); + app.raw_input_hook(&ctx, &mut raw); + ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + if ui.ctx().current_pass_index() == 0 { + app.poll_native_actions(ui.ctx(), || actions.pop_front()); + } + app.ui(ui); + }) + .textures_delta + .clear(); + assert_eq!(app.session.documents().len(), 1); + assert!(app.session.active().unwrap().is_dirty()); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.active().unwrap().uid, original); + assert!(!app.session.active().unwrap().is_dirty(), "Revert runs before delivery resumes"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 2); + assert_ne!(app.session.active().unwrap().uid, original); + assert!(!app.session.documents().iter().find(|doc| doc.uid == original).unwrap().is_dirty(), "Revert targeted the original document"); +} + +/// Preview cleanup cannot replace the input batch's document and runs after the batch settles. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_stale_preview_waits_for_the_input_batch() { + let (mut app, ctx, _writes) = screenshot_app(); + let original = app.session.active().unwrap().uid; + app.session.preview_new_document(&json!({"title": "Preview"})).unwrap(); + let preview = app.session.new_document_preview(); + assert!(preview.is_some()); + app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.new_document_preview(), preview, "preview cleanup cannot replace the input's document"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert!(app.session.new_document_preview().is_none()); + assert_eq!(app.session.active().unwrap().uid, original); +} + +/// Revert waits for Select All's forwarded text input to settle. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_native_choices_wait_for_forwarded_text_input() { + let (mut app, ctx, _writes) = screenshot_app(); + let _dir = prepare_revert(&mut app); + let mut text = String::from("native field"); + ctx.run_ui(visible_raw(), |ui| { + ui.text_edit_singleline(&mut text).request_focus(); + }) + .textures_delta + .clear(); + assert!(ctx.text_edit_focused(), "the native edit command must forward to an actual text field"); + let mut actions = std::collections::VecDeque::from([("edit.selectAll".to_owned(), Value::Null), ("file.revert".to_owned(), json!({}))]); + app.poll_native_actions(&ctx, || actions.pop_front()); + run_host_frame(&mut app, &ctx, visible_raw()); + assert!(app.session.active().unwrap().is_dirty(), "Revert waits for Select All's forwarded input"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert!(!app.session.active().unwrap().is_dirty()); +} + +/// A queued native menu event precedes and blocks deferred OS-open delivery without synthetic input. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_arriving_native_event_blocks_an_os_open_without_synthetic_input() { + let (mut app, ctx, _writes) = screenshot_app(); + let dir = prepare_revert(&mut app); + let original = app.session.active().unwrap().uid; + let path = dir.path().join("incoming.designcraft"); + std::fs::write(&path, document_with_a_frame()).unwrap(); + app.open_documents_later([path.to_string_lossy().to_string()]); + let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); + app.native_action_notifier(ctx.clone())(); + let mut raw = visible_raw(); + app.raw_input_hook(&ctx, &mut raw); + ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + assert_eq!(app.session.documents().len(), 1, "a menu event already queued by the host must precede the OS open"); + if ui.ctx().current_pass_index() == 0 { + app.poll_native_actions(ui.ctx(), || actions.pop_front()); + } + app.ui(ui); + }) + .textures_delta + .clear(); + assert!(!app.session.active().unwrap().is_dirty(), "the menu action ran in the real UI callback"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 2); + assert_ne!(app.session.active().unwrap().uid, original); +} + +/// Hidden logic-only ticks cannot execute native menu actions; a real UI pass can. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_deferred_native_action_waits_for_a_real_ui_pass() { + let (mut app, ctx, _writes) = screenshot_app(); + let _dir = prepare_revert(&mut app); + app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); + let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]); + let mut raw = visible_raw(); + app.raw_input_hook(&ctx, &mut raw); + ctx.run_ui(raw, |ui| { + app.logic(&ui.ctx().clone()); + if ui.ctx().current_pass_index() == 0 { + app.poll_native_actions(ui.ctx(), || actions.pop_front()); + } + app.ui(ui); + }) + .textures_delta + .clear(); + assert!(app.session.active().unwrap().is_dirty()); + let mut raw = hidden_raw(); + app.raw_input_hook(&ctx, &mut raw); + let _ = ctx.run_logic(&raw, |ctx| app.logic(ctx)); + assert!(app.session.active().unwrap().is_dirty(), "a hidden logic-only tick must not execute native menu actions"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert!(!app.session.active().unwrap().is_dirty(), "the deferred action runs when a UI callback resumes"); +} + +/// An inbox delivery runs only after input sampled for the current document has settled, so +/// a pending Select All cannot select text in the opened document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_inbox_open_must_not_receive_a_pending_shortcut() { + let (mut app, ctx, _writes) = screenshot_app(); + app.services.inbox = Some(Inbox::default()); + let request = app.import_request("open"); + let file = ImportedFile { request, name: "incoming.designcraft".into(), bytes: document_with_a_frame() }; + app.services.inbox.as_ref().unwrap().lock().unwrap().push(file); + app.control_synthetic.extend(command_key(egui::Key::A)); + run_host_frame(&mut app, &ctx, visible_raw()); + // A deferred delivery is handled by the next settled host iteration. + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 2, "the inbox file is still opened"); + assert!(app.session.active().unwrap().selection.is_empty(), "Select All sampled before the asynchronous open must not reach the opened document"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_os_document_must_not_receive_a_pending_shortcut() { + let (mut app, ctx, _writes) = screenshot_app(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("incoming.designcraft"); + std::fs::write(&path, document_with_a_frame()).unwrap(); + app.open_documents_later([path.to_string_lossy().to_string()]); + app.control_synthetic.extend(command_key(egui::Key::A)); + run_host_frame(&mut app, &ctx, visible_raw()); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 2, "the OS document is still opened"); + assert!(app.session.active().unwrap().selection.is_empty(), "Select All sampled before the OS open must not reach the opened document"); +} + +/// The intended boundary: an imported file waits while the batch that was sampled for the +/// current document is pending, and is handled once that batch has settled. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_inbox_delivery_waits_for_a_settled_batch_then_runs() { + let (mut app, ctx, _writes) = screenshot_app(); + app.services.inbox = Some(Inbox::default()); + let request = app.import_request("open"); + let file = ImportedFile { request, name: "incoming.designcraft".into(), bytes: document_with_a_frame() }; + app.services.inbox.as_ref().unwrap().lock().unwrap().push(file); + app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 1, "the delivery waited for the injected step"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 2, "the deferred delivery is not lost"); +} + +/// Deferred OS open waits for injected input and is not lost. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_host_order_os_document_waits_for_a_settled_batch_then_runs() { + let (mut app, ctx, _writes) = screenshot_app(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("incoming.designcraft"); + std::fs::write(&path, document_with_a_frame()).unwrap(); + app.open_documents_later([path.to_string_lossy().to_string()]); + app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0))); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 1, "the OS open waited for the injected step"); + run_host_frame(&mut app, &ctx, visible_raw()); + assert_eq!(app.session.documents().len(), 2, "the deferred OS open is not lost"); +} + +/// Revert drops the buffered native drop so it cannot modify the restored document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_revert_discards_a_buffered_native_drop() { + let (mut app, ctx) = drop_test_app(); + let dir = prepare_revert(&mut app); + let path = dir.path().join("drop.png"); + std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); + let mut raw = visible_raw_with_drop(&[&path]); + app.raw_input_hook(&ctx, &mut raw); + assert_eq!(app.pending_drops.len(), 1); + revert_preserving_uid(&mut app); + let assets_before = app.session.active().unwrap().doc.assets.len(); + run_ui_pass(&mut app, &ctx, raw); + assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "a stale native drop must not modify the restored document"); + assert!(app.pending_drops.is_empty()); +} + +/// Revert rejects pre-issue and in-flight screenshots with a document error, issues no retry and writes no pixels. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_revert_rejects_screenshots_before_issue_and_in_flight() { + for in_flight in [false, true] { + let (mut app, ctx, writes) = screenshot_app(); + let _dir = prepare_revert(&mut app); + let (reply, replies) = std::sync::mpsc::channel(); + app.admit_screenshot(Some("revert-stale.png".into()), reply).unwrap(); + app.queued_shots[0].1 = 0.0; + let mut callback = None; + if in_flight { + for _ in 0..3 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + if let Some(cb) = screenshot_callback(&mut output) { + callback = Some(cb); + } + } + assert!(callback.is_some(), "the in-flight case must actually issue a capture"); + } + revert_preserving_uid(&mut app); + if let Some(callback) = callback { + callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + } + for _ in 0..4 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert!(screenshot_callback(&mut output).is_none(), "Revert must not issue or retry an old capture (in_flight={in_flight})"); + } + let reply = replies.try_recv().expect("the replaced document's screenshot receives an error"); + assert_eq!(reply["ok"], false, "in_flight={in_flight}: {reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("document")); + assert!(writes.lock().unwrap().is_empty(), "stale pixels must not be saved"); + assert!(app.pending_shots.is_empty()); + assert!(app.queued_shots.is_empty()); + } +} + +// --------------------------------------------------------------------------------------- +// Document-generation regressions: reused screenshot slots and buffered native drops must +// not cross a document/dialog/focus change. +// --------------------------------------------------------------------------------------- + +/// A document switch before issue errors the request and leaves no pending or queued capture. +#[test] +fn design_generation_screenshot_switch_before_issue_does_not_capture_the_new_document() { + let (mut app, ctx, writes) = screenshot_app(); + let document_a = app.session.active().unwrap().uid; + let (requests, receiver) = std::sync::mpsc::channel(); + app = app.with_control(receiver); + let (reply, replies) = std::sync::mpsc::channel(); + requests + .send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "switch-before-issue.png", "focus": false}), reply }) + .unwrap(); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + assert_eq!(app.pending_shots.len(), 1, "ui.screenshot is admitted"); + assert_eq!(app.pending_shots[0].geometry.document, document_a); + // A menu/control action switches documents before the settling rule issues the capture. + app.run("file.new", json!({"title": "handoff-before-issue"})).unwrap(); + let document_b = app.session.active().unwrap().uid; + assert_ne!(document_b, document_a); + if let Some(at) = app.queued_shots.first_mut() { + at.1 = 0.0; + } + let mut callback = None; + for _ in 0..3 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + if let Some(cb) = screenshot_callback(&mut output) { + callback = Some(cb); + } + } + if let Some(callback) = callback { + callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + } + assert!(writes.lock().unwrap().is_empty(), "the switched request must not write a file"); + let reply = replies.try_recv().expect("the switched request must receive an error receipt"); + assert_eq!(reply["ok"], false, "the old document's request must not succeed on the new one: {reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("document"), "the error must name the document change: {reply}"); + assert!(app.pending_shots.is_empty(), "the stale request released its admission"); + assert!(app.queued_shots.is_empty(), "the stale request left no repaint token"); +} + +/// An in-flight old-document capture cannot complete or retry on the new document; the request and tokens are released. +#[test] +fn design_generation_screenshot_in_flight_after_switch_does_not_complete_on_the_new_document() { + let (mut app, ctx, writes) = screenshot_app(); + let document_a = app.session.active().unwrap().uid; + let (reply, replies) = std::sync::mpsc::channel(); + app.admit_screenshot(Some("switch-in-flight.png".into()), reply).unwrap(); + app.queued_shots[0].1 = 0.0; + let mut callback = None; + for _ in 0..3 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + if let Some(cb) = screenshot_callback(&mut output) { + callback = Some(cb); + } + } + let callback = callback.expect("the request is issued on the first document"); + assert_eq!(app.pending_shots[0].geometry.document, document_a); + // The capture is in flight on A when the app switches to B. + app.run("file.new", json!({"title": "handoff-in-flight"})).unwrap(); + assert_ne!(app.session.active().unwrap().uid, document_a); + callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + // Old code retries the stale request on B; follow any retry through a completion so the + // regression proves that B never receives the old capture. + if let Some(at) = app.queued_shots.first_mut() { + at.1 = 0.0; + } + let mut retried = None; + for _ in 0..3 { + let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + if let Some(cb) = screenshot_callback(&mut output) { + retried = Some(cb); + } + } + if let Some(retried) = retried { + retried.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK))); + shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0)); + } + assert!(writes.lock().unwrap().is_empty(), "the in-flight request must not write a file after the switch"); + let reply = replies.try_recv().expect("the in-flight request must receive an error receipt"); + assert_eq!(reply["ok"], false, "the in-flight request must not succeed on the new document: {reply}"); + assert!(reply["error"].as_str().unwrap_or_default().contains("document"), "the error must name the document change: {reply}"); + assert!(app.pending_shots.is_empty(), "the stale request released its admission"); + assert!(app.queued_shots.is_empty(), "the stale request left no repaint token"); +} + +/// Admission stamps the current session document, not cached geometry from the previous document. +#[test] +fn design_generation_screenshot_admission_uses_the_current_document_not_the_cached_geometry() { + let (mut app, _ctx, _writes) = screenshot_app(); + let document_a = app.session.active().unwrap().uid; + // `screenshot_app` populated the geometry cache for A. Switch documents without a frame + // between the switch and admission, as two control requests in one logic tick would. + app.run("file.new", json!({"title": "admission-current-document"})).unwrap(); + let document_b = app.session.active().unwrap().uid; + assert_ne!(document_b, document_a); + let (reply, replies) = std::sync::mpsc::channel(); + app.admit_screenshot(None, reply).unwrap(); + assert_eq!(app.pending_shots[0].geometry.document, document_b, "admission must use the current session document, not the last cached geometry"); + assert!(replies.try_recv().is_err(), "admission alone replies only when it fails"); + app.pending_shots.clear(); + app.queued_shots.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +struct TestDroppedFile(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl egui::DroppedFile for TestDroppedFile { + fn path(&self) -> &std::path::Path { + &self.0 + } + + fn bytes(&self) -> Result, String> { + std::fs::read(&self.0).map_err(|error| error.to_string()) + } +} + +/// Wrap a path as an egui dropped-file handle backed by the test type. +#[cfg(not(target_arch = "wasm32"))] +fn dropped_file(path: &std::path::Path) -> egui::DroppedFileHandle { + std::sync::Arc::new(TestDroppedFile(path.to_path_buf())) +} + +/// Create a screenshot app with a fixed canvas rectangle and an initialized view for drop tests. +#[cfg(not(target_arch = "wasm32"))] +fn drop_test_app() -> (DesignApp, egui::Context) { + let (mut app, ctx, _writes) = screenshot_app(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + let _ = app.view_mut(); + (app, ctx) +} + +/// Write a tiny unique PNG for drop tests. +#[cfg(not(target_arch = "wasm32"))] +fn temporary_png(name: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}.png", std::process::id())); + std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap(); + path +} + +/// Build visible raw input with a pointer move and dropped-file handles. +#[cfg(not(target_arch = "wasm32"))] +fn visible_raw_with_drop(paths: &[&std::path::Path]) -> egui::RawInput { + let mut raw = hidden_raw(); + let viewport = raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); + viewport.minimized = Some(false); + viewport.occluded = Some(false); + raw.events.push(egui::Event::PointerMoved(egui::pos2(100.0, 100.0))); + raw.dropped_files.extend(paths.iter().map(|path| dropped_file(path))); + raw +} + +/// Run one logic-plus-UI frame and discard its texture deltas. +#[cfg(not(target_arch = "wasm32"))] +fn run_ui_pass(app: &mut DesignApp, ctx: &egui::Context, raw: egui::RawInput) { + ctx.run_ui(raw, |ui| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }) + .textures_delta + .clear(); +} + +/// A drop buffered before a document switch cannot add assets to the switched document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_generation_native_drop_is_discarded_when_the_document_changes_before_ui() { + let (mut app, ctx) = drop_test_app(); + let path = temporary_png("drop-document-change"); + let mut raw = visible_raw_with_drop(&[&path]); + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.dropped_files.is_empty(), "raw_input_hook captures the native drop"); + assert_eq!(app.pending_drops.len(), 1, "the raw drop is buffered for the UI pass"); + // A menu/control action switches documents before the settled UI pass consumes it. + app.run("file.new", json!({"title": "drop-target"})).unwrap(); + let assets_before = app.session.active().unwrap().doc.assets.len(); + run_ui_pass(&mut app, &ctx, raw); + assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land in the switched document"); + assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer"); + let _ = std::fs::remove_file(path); +} + +/// A drop buffered before a dialog opens cannot land behind it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_generation_native_drop_is_discarded_when_a_dialog_opens_before_ui() { + let (mut app, ctx) = drop_test_app(); + let path = temporary_png("drop-dialog-change"); + let mut raw = visible_raw_with_drop(&[&path]); + app.raw_input_hook(&ctx, &mut raw); + assert_eq!(app.pending_drops.len(), 1); + app.run("app.preferences", json!({})).unwrap(); + assert!(app.ui.dialog.is_some(), "a real dialog changed the generation"); + let assets_before = app.session.active().unwrap().doc.assets.len(); + run_ui_pass(&mut app, &ctx, raw); + assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land behind the dialog"); + assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer"); + let _ = std::fs::remove_file(path); +} + +/// A keyboard-focus change invalidates a buffered drop. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_generation_native_drop_is_discarded_when_focus_changes_before_ui() { + let (mut app, ctx) = drop_test_app(); + let path = temporary_png("drop-focus-change"); + let mut raw = visible_raw_with_drop(&[&path]); + app.raw_input_hook(&ctx, &mut raw); + assert_eq!(app.pending_drops.len(), 1); + let focus = egui::Id::unique("design-generation-drop-focus"); + assert_ne!(app.input_generation().focus, Some(focus)); + ctx.memory_mut(|memory| memory.request_focus(focus)); + assert_eq!(app.input_generation().focus, Some(focus), "keyboard focus changed after the drop was buffered"); + let assets_before = app.session.active().unwrap().doc.assets.len(); + run_ui_pass(&mut app, &ctx, raw); + assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land after a focus change"); + assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer"); + let _ = std::fs::remove_file(path); +} + +/// With no generation change, every dropped file in a batch is placed. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn design_generation_native_drop_batch_without_a_change_still_places_every_file() { + let (mut app, ctx) = drop_test_app(); + let first = temporary_png("drop-batch-a"); + let second = temporary_png("drop-batch-b"); + let mut raw = visible_raw_with_drop(&[&first, &second]); + app.raw_input_hook(&ctx, &mut raw); + assert_eq!(app.pending_drops.len(), 2, "both files were captured from the raw input"); + let assets_before = app.session.active().unwrap().doc.assets.len(); + run_ui_pass(&mut app, &ctx, raw); + assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before + 2, "both files in the valid batch are placed"); + assert!(app.pending_drops.is_empty()); + let _ = std::fs::remove_file(first); + let _ = std::fs::remove_file(second); +} From 39da80d79282947d9e1cbe78de61c8d9e5bb4e36 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:24 +0000 Subject: [PATCH 10/70] refactor(epub): move the tests module of lib.rs to tests.rs --- crates/epub/src/lib.rs | 932 +-------------------------------------- crates/epub/src/tests.rs | 924 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 925 insertions(+), 931 deletions(-) create mode 100644 crates/epub/src/tests.rs diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs index c3150966f..025cdbf3e 100644 --- a/crates/epub/src/lib.rs +++ b/crates/epub/src/lib.rs @@ -1504,934 +1504,4 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr } #[cfg(test)] -mod tests { - use super::*; - use designcraft_doc::build::NewDocument; - use designcraft_doc::geom::{Affine, Rect, shapes}; - use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, ParaFormat, Shape, SpreadRef, Story, StoryId, Table}; - use std::io::Read; - use std::sync::Arc; - - #[test] - fn exports_valid_package_in_reading_order() { - let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() }); - let lid = d.default_layer(); - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 400.0, 300.0, 500.0), lid, "Second & co", ParaFormat::default()).unwrap(); - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "First\nline two", ParaFormat::default()).unwrap(); - let bytes = export_epub(&d, &EpubOptions::default()).unwrap(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - assert_eq!(z.by_index(0).unwrap().name(), "mimetype"); - let mut html = String::new(); - z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap(); - let a = html.find("First").unwrap(); - let b = html.find("Second <b> & co").unwrap(); - assert!(a < b, "reading order"); - assert!(html.contains("

")); - let mut css = String::new(); - z.by_name("OEBPS/style.css").unwrap().read_to_string(&mut css).unwrap(); - assert!(css.contains("p.basic-paragraph")); - assert!(z.by_name("OEBPS/nav.xhtml").is_ok()); - } - - /// #766: anchored graphics are exported where they are anchored (inline in the text, an - /// above-line object as a block of its own), and their images go into the package. - #[test] - fn anchored_objects_are_exported_in_place() { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 200.0), lid, "AB\nCD", ParaFormat::default()).unwrap(); - let aid = AssetId(d.alloc()); - d.assets.insert( - aid, - Arc::new(Asset { - page: 0, - id: aid, - name: "dot.png".into(), - mime: "image/png".into(), - link: None, - data: Arc::new(vec![7]), - pixels: Some((1, 1)), - ..Default::default() - }), - ); - let graphic = |d: &mut Document, alt: &str| { - let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))); - item.alt_text = alt.into(); - item.content = Content::Graphic(Graphic { - layer_options: None, - asset: aid, - size: (1.0, 1.0), - xf: Affine::IDENTITY, - auto_fit: Default::default(), - fit_align: 4, - crop: [0.0; 4], - clip: None, - wrap: Default::default(), - fill: Default::default(), - }); - item - }; - let inline = designcraft_doc::AnchoredObject::new(graphic(&mut d, "inline"), designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 }); - let above = designcraft_doc::AnchoredObject::new( - graphic(&mut d, "above"), - designcraft_doc::AnchorPosition::AboveLine { align: designcraft_doc::anchored::AnchorAlign::Center, space_before: 0.0, space_after: 0.0 }, - ); - let st = d.story_mut(sid).unwrap(); - st.insert_object(1, inline); - // Byte offsets: "A" (1), the mark (3), "B\nC" (3): the second object goes between C and D. - st.insert_object(7, above); - // An anchored image without alt text is decorative and reported, like a placed one. - let bare = designcraft_doc::AnchoredObject::new(graphic(&mut d, ""), designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 }); - let end = d.story(sid).unwrap().text.len(); - d.story_mut(sid).unwrap().insert_object(end, bare); - assert_eq!(images_without_alt(&d), vec!["dot.png".to_string()]); - let bytes = export_epub(&d, &EpubOptions::default()).unwrap(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut html = String::new(); - z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap(); - let img = |alt: &str| format!("\"{alt}\"/", aid.0); - assert!(html.contains(&format!("A{}B

", img("inline"))), "{html}"); - assert!(html.contains(&format!("C{}D", img("above"))), "{html}"); - assert!(z.by_name(&format!("OEBPS/images/dot-{}.png", aid.0)).is_ok(), "the image is in the package"); - let page = export_html(&d, &HtmlOptions::default()); - assert!(page.contains("alt=\"inline\"") && page.contains("alt=\"above\""), "{page}"); - // story_html on its own still leaves objects out. - assert!(!story_html(&d, sid).contains(" = z.file_names().map(str::to_string).collect(); - (s, names) - }; - let id_of = |opf: &str| opf.split("").nth(1).and_then(|r| r.split('<').next()).unwrap_or_default().to_string(); - let mut a = Document::new(&NewDocument::default()); - a.title = "Same".into(); - a.created = 1_700_000_000; - let mut b = a.clone(); - b.created = 1_700_000_001; - let (oa, _) = opf(&a, &EpubOptions::default()); - let (oa2, _) = opf(&a, &EpubOptions::default()); - let (ob, _) = opf(&b, &EpubOptions::default()); - assert!(id_of(&oa).starts_with("urn:uuid:") && id_of(&oa).len() == 45, "{}", id_of(&oa)); - assert_eq!(id_of(&oa), id_of(&oa2), "stable from export to export"); - assert_ne!(id_of(&oa), id_of(&ob), "not shared by two books with the same title"); - // Modified: the given time, else the document's save (or creation) time. - assert!(oa.contains("2023-11-14T22:13:20Z"), "{oa}"); - let at = EpubOptions { modified: Some(1_791_891_000), ..Default::default() }; - assert!(opf(&a, &at).0.contains("2026-10-13T11:30:00Z")); - // A JPEG cover is packaged as such. - let jpeg = EpubOptions { cover: Some(vec![0xFF, 0xD8, 0xFF, 0xE0, 1, 2]), ..Default::default() }; - let (o, names) = opf(&a, &jpeg); - assert!(o.contains("href=\"images/cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\""), "{o}"); - assert!(names.contains(&"OEBPS/images/cover.jpg".to_string()), "{names:?}"); - } - - fn st_typed(d: &mut Document, sid: StoryId) { - if let Some(st) = d.story_mut(sid) { - st.paras[8].style = "Typed".into(); - } - } - - /// #767: consecutive `li` paragraphs share one list (`ol` for a numbered style), and - /// consecutive `pre` paragraphs of one style one block with their lines on separate lines. - #[test] - fn lists_and_preformatted_blocks_are_grouped() { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - for (name, tag, list) in [ - ("Bullet", "li", Some(designcraft_doc::ListType::Bullets)), - ("Number", "li", Some(designcraft_doc::ListType::Numbers)), - ("Typed", "li", None), - ("Code", "pre", None), - ] { - let para = designcraft_doc::ParaAttrs { list_type: list, ..Default::default() }; - d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { - name: name.into(), - based_on: None, - next_style: None, - para, - chars: CharAttrs::default(), - shortcut: String::new(), - }); - d.styles_mut() - .export_tags - .insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new(), ..Default::default() }); - } - let text = "Intro\nfirst\nsecond\none\ntwo\nx = 1\ny = 2\nEnd\n• typed"; - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap(); - let st = d.story_mut(sid).unwrap(); - for (i, style) in ["Bullet", "Bullet", "Number", "Number", "Code", "Code"].into_iter().enumerate() { - st.paras[i + 1].style = style.into(); - } - let html = story_html(&d, sid); - let li = |c: &str, t: &str| format!("
  • {t}
  • "); - assert!( - html.contains(&format!( - "
      \n{}\n{}\n
    \n
      \n{}\n{}\n
    \n", - li("bullet", "first"), - li("bullet", "second"), - li("number", "one"), - li("number", "two") - )), - "{html}" - ); - assert!(html.contains("
    x = 1\ny = 2
    \n

    End

    "), "{html}"); - assert_eq!(html.matches("\n
  • • typed
  • \n\n"), "{html}"); - } - - /// #769, #770: the navigation lists the h1–h3 headings (nested by level) and links to them, - /// with its title in the book's language; without headings, each story's first paragraph. - #[test] - fn navigation_follows_the_headings() { - let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() }); - let lid = d.default_layer(); - for (name, tag) in [("Chapter", "h1"), ("Section", "h2")] { - d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { - name: name.into(), - based_on: None, - next_style: None, - para: Default::default(), - chars: CharAttrs::default(), - shortcut: String::new(), - }); - d.styles_mut() - .export_tags - .insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new(), ..Default::default() }); - } - let text = "One\nBody\nOne point one\nMore\nTwo\nText"; - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap(); - let st = d.story_mut(sid).unwrap(); - for (i, style) in [(0, "Chapter"), (2, "Section"), (4, "Chapter")] { - st.paras[i].style = style.into(); - } - // A story that starts with body text adds nothing to the table of contents. - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 400.0, 300.0, 500.0), lid, "Text after the figure.", ParaFormat::default()).unwrap(); - let read = |d: &Document, opts: &EpubOptions, path: &str| { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap(); - let mut s = String::new(); - z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); - s - }; - let nl = EpubOptions { language: "nl".into(), ..Default::default() }; - let nav = read(&d, &nl, "OEBPS/nav.xhtml"); - let link = |f: &str, t: &str, l: &str| format!("{l}"); - // Split Document is off: every heading is in the one content file. - let want = format!( - "

    Inhoud

    1. {}
      1. {}
    2. {}
    ", - link("content.xhtml", "s0-p0", "One"), - link("content.xhtml", "s0-p2", "One point one"), - link("content.xhtml", "s0-p4", "Two") - ); - assert!(nav.contains(&want), "{nav}"); - assert!(!nav.contains("Text after the figure"), "{nav}"); - let content = read(&d, &nl, "OEBPS/content.xhtml"); - assert!(content.contains("

    One

    ") && content.contains("

    In dit boek

    ")); - // Without headings: one entry per story, its first paragraph. - let mut plain = Document::new(&NewDocument::default()); - let lid = plain.default_layer(); - plain.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Opening\nrest", ParaFormat::default()).unwrap(); - let nav = read(&plain, &EpubOptions::default(), "OEBPS/nav.xhtml"); - assert!(nav.contains(&format!("

    Contents

    1. {}
    ", link("content.xhtml", "s0", "Opening"))), "{nav}"); - // A heading shallower than the one before it but deeper than its parent stays under the - // parent: h1 A, h3 B, h2 C nest B and C under A. - let files: BTreeMap = "ABCD".chars().map(|c| (c.to_string(), c.to_string())).collect(); - let e = |t: &str, l: u8| (t.to_string(), t.to_string(), l); - assert_eq!( - nav_list(&[e("A", 1), e("B", 3), e("C", 2), e("D", 1)], &files), - format!( - "
  • {}
    1. {}
    2. {}
  • {}
  • ", - link("A", "A", "A"), - link("B", "B", "B"), - link("C", "C", "C"), - link("D", "D", "D") - ) - ); - assert_eq!( - nav_list(&[e("A", 1), e("B", 2), e("C", 3), e("D", 1)], &files), - format!( - "
  • {}
    1. {}
      1. {}
  • {}
  • ", - link("A", "A", "A"), - link("B", "B", "B"), - link("C", "C", "C"), - link("D", "D", "D") - ) - ); - } - - /// Split Document off (the default) gives one content file, h1s and all. Single Paragraph - /// Style starts a file before each paragraph of that style, with well-formed sections; the - /// spine and manifest list the files in order. - #[test] - fn chapters_split_before_a_single_paragraph_style() { - let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() }); - let lid = d.default_layer(); - d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { - name: "Chapter".into(), - based_on: None, - next_style: None, - para: Default::default(), - chars: CharAttrs::default(), - shortcut: String::new(), - }); - d.styles_mut() - .export_tags - .insert("p:Chapter".into(), designcraft_doc::ExportTag { tag: "h1".into(), class: String::new(), ..Default::default() }); - // A title page without a heading, then a story that opens with a chapter and has a - // second one in the middle. - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Title page", ParaFormat::default()).unwrap(); - let (_, sid) = d - .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 400.0), lid, "One\nFirst text\nTwo\nSecond text", ParaFormat::default()) - .unwrap(); - let st = d.story_mut(sid).unwrap(); - st.paras[0].style = "Chapter".into(); - st.paras[2].style = "Chapter".into(); - let one_file = |d: &Document, opts: &EpubOptions| { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap(); - let mut c = String::new(); - z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut c).unwrap(); - z.by_name("OEBPS/content2.xhtml").is_err() && c.contains("Title page") && c.contains("Second text") && !c.contains(CHAPTER_MARK) - }; - assert!(one_file(&d, &EpubOptions::default()), "off by default"); - d.settings.epub_split = EpubSplit::Style("Chapter".into()); - assert!(one_file(&d, &EpubOptions { split: Some(EpubSplit::Off), ..Default::default() }), "the export's own setting wins"); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap(); - let mut read = |path: &str| { - let mut s = String::new(); - z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); - s - }; - let (c1, c2, c3) = (read("OEBPS/content.xhtml"), read("OEBPS/content2.xhtml"), read("OEBPS/content3.xhtml")); - assert!(c1.contains("Title page") && !c1.contains("One"), "{c1}"); - assert!(c2.contains("
    \n

    \n

    ").count(), "{c}"); - assert!(!c.contains(CHAPTER_MARK)); - } - let opf = read("OEBPS/content.opf"); - assert!(opf.contains("\n\n\n"), "{opf}"); - assert!(opf.contains("").count(), "{c}"); - } - let nav = read("OEBPS/nav.xhtml"); - assert!(nav.contains("href=\"content2.xhtml#s1-p1\"") && nav.contains("href=\"content3.xhtml#s1-p4\""), "{nav}"); - assert!(c2.contains("href=\"content3.xhtml#en-1\""), "{c2}"); - assert!(c3.contains("href=\"content2.xhtml#enref-1\""), "the endnote links back across files: {c3}"); - assert!(z.by_name("OEBPS/content4.xhtml").is_err()); - } - - /// Note links stay working across chapter files: endnotes end the book, in the last file. - #[test] - fn note_links_point_at_the_chapter_file_of_their_target() { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { - name: "Chapter".into(), - based_on: None, - next_style: None, - para: Default::default(), - chars: CharAttrs::default(), - shortcut: String::new(), - }); - d.styles_mut() - .export_tags - .insert("p:Chapter".into(), designcraft_doc::ExportTag { tag: "h1".into(), class: String::new(), ..Default::default() }); - let (_, sid) = d - .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 400.0), lid, "One\nFirst text\nTwo\nSecond text", ParaFormat::default()) - .unwrap(); - let st = d.story_mut(sid).unwrap(); - st.paras[0].style = "Chapter".into(); - st.paras[2].style = "Chapter".into(); - // After "First": an endnote and a footnote. - st.insert_endnote(9, "End note", ParaFormat::default()); - st.insert_note(9, "Foot note", ParaFormat::default()); - d.settings.epub_split = EpubSplit::Style("Chapter".into()); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap(); - let mut read = |path: &str| { - let mut s = String::new(); - z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); - s - }; - let (first, last) = (read("OEBPS/content.xhtml"), read("OEBPS/content2.xhtml")); - assert!(first.contains("id=\"enref-1\" href=\"content2.xhtml#en-1\""), "{first}"); - assert!(first.contains("href=\"#fn-1\"") && first.contains("href=\"#fnref-1\""), "a footnote stays in its chapter: {first}"); - assert!(last.contains("Second text") && last.contains(""), "{last}"); - } - - /// A split before a list item or a preformatted line closes the open list or block first and - /// reopens it in the new file, so every file is balanced. - #[test] - fn chapter_files_split_inside_lists_and_pre_stay_balanced() { - let mut d = Document::new(&NewDocument::default()); - d.settings.epub_split = EpubSplit::ExportTags; - let lid = d.default_layer(); - for (name, tag) in [("Item", "li"), ("Code", "pre")] { - d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { - name: name.into(), - based_on: None, - next_style: None, - para: Default::default(), - chars: CharAttrs::default(), - shortcut: String::new(), - }); - d.styles_mut().export_tags.insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), split: true, ..Default::default() }); - } - let (_, sid) = d - .add_text_frame( - SpreadRef::Doc(0), - Rect::new(36.0, 36.0, 300.0, 300.0), - lid, - "Intro -one -two -x = 1 -y = 2 -End", - ParaFormat::default(), - ) - .unwrap(); - let st = d.story_mut(sid).unwrap(); - for (i, style) in [(1, "Item"), (2, "Item"), (3, "Code"), (4, "Code")] { - st.paras[i].style = style.into(); - } - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap(); - let mut read = |path: &str| { - let mut s = String::new(); - z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); - s - }; - let files: Vec = - ["content", "content2", "content3", "content4", "content5"].iter().map(|f| read(&format!("OEBPS/{f}.xhtml"))).collect(); - for (c, text) in files.iter().zip(["Intro", "one", "two", "x = 1", "y = 2"]) { - assert!(c.contains(text), "{text}: {c}"); - for (open, close) in [(""), (""), ("")] { - assert_eq!(c.matches(open).count(), c.matches(close).count(), "{open}: {c}"); - } - } - assert!(files[1].contains("\n

    a

    \n

    \n"), vec!["
    \n

    a

    \n
    \n"]); - assert_eq!( - split_chapters(&format!("
    \n{m}

    A

    \n
    \n")), - vec!["
    \n

    A

    \n
    \n"] - ); - assert_eq!( - split_chapters(&format!("
    \n

    a

    \n{m}

    B

    \n
    \n")), - vec!["
    \n

    a

    \n
    \n", "
    \n

    B

    \n
    \n"] - ); - assert_eq!(split_chapters(""), vec![String::new()]); - } - - #[test] - fn styles_whose_names_slug_alike_keep_their_own_classes() { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - for (name, size) in [("見出し", 30.0), ("本文", 10.0), ("Body Text", 12.0), ("Body-Text", 20.0)] { - d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { - name: name.into(), - based_on: None, - next_style: None, - para: Default::default(), - chars: CharAttrs { size: Some(size), ..Default::default() }, - shortcut: String::new(), - }); - } - for (k, name) in ["見出し", "本文", "Body Text", "Body-Text"].into_iter().enumerate() { - let y = 36.0 + 100.0 * k as f64; - let pf = ParaFormat { style: name.into(), ..Default::default() }; - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, y, 300.0, y + 50.0), lid, &format!("P{k}"), pf).unwrap(); - } - let bytes = export_epub(&d, &EpubOptions::default()).unwrap(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut html = String::new(); - z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap(); - let mut css = String::new(); - z.by_name("OEBPS/style.css").unwrap().read_to_string(&mut css).unwrap(); - let class_of = |text: &str| { - let end = html.find(&format!("\">{text}

    ")).unwrap(); - let start = html[..end].rfind("class=\"").unwrap() + 7; - html[start..end].to_string() - }; - let classes: Vec = (0..4).map(|k| class_of(&format!("P{k}"))).collect(); - for (k, c) in classes.iter().enumerate() { - assert!(!classes[..k].contains(c), "class `{c}` shared: {classes:?}"); - assert_eq!(css.matches(&format!("p.{c} {{")).count(), 1, "one rule for `{c}`:\n{css}"); - } - } - - #[test] - fn slugs() { - assert_eq!(slug("[Basic Paragraph]"), "basic-paragraph"); - assert_eq!(slug("Body First"), "body-first"); - assert_eq!(slug("1 Head"), "s-1-head"); - } - - #[test] - fn html_is_one_self_contained_page() { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Hello ", ParaFormat::default()).unwrap(); - let html = export_html(&d, &HtmlOptions { title: Some("T".into()), language: None, ..Default::default() }); - assert!(html.starts_with("") && html.contains("T") && html.contains("Hello <web>")); - assert!(html.contains("p.basic-paragraph"), "styles inline"); - assert_eq!(base64(b"Man"), "TWFu"); - assert_eq!(base64(b"Ma"), "TWE="); - assert_eq!(base64(b"M"), "TQ=="); - } - - /// #774: an image without alt text is decorative (`alt=""`) and reported, and package names - /// come from the original file names. - #[test] - fn images_get_readable_names_and_no_file_name_alt() { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - let place = |d: &mut Document, name: &str, mime: &str, alt: &str, y: f64| { - let aid = AssetId(d.alloc()); - d.assets.insert( - aid, - Arc::new(Asset { - page: 0, - id: aid, - name: name.into(), - mime: mime.into(), - link: None, - data: Arc::new(vec![1]), - pixels: Some((1, 1)), - ..Default::default() - }), - ); - let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(36.0, y, 72.0, y + 36.0))); - item.alt_text = alt.into(); - item.content = Content::Graphic(Graphic { - layer_options: None, - asset: aid, - size: (1.0, 1.0), - xf: Affine::IDENTITY, - auto_fit: Default::default(), - fit_align: 4, - crop: [0.0; 4], - clip: None, - wrap: Default::default(), - fill: Default::default(), - }); - d.insert_item(SpreadRef::Doc(0), item, None).unwrap(); - aid.0 - }; - let a = place(&mut d, "/tmp/Anim Frame (1).GIF", "image/gif", "", 36.0); - let b = place(&mut d, "photo.jpg", "image/jpeg", "A heron", 120.0); - let c = place(&mut d, "???.png", "image/png", "Mark", 200.0); - assert_eq!(images_without_alt(&d), vec!["/tmp/Anim Frame (1).GIF".to_string()]); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap(); - let mut x = String::new(); - z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut x).unwrap(); - assert!(x.contains(&format!("\"\"/")), "{x}"); - assert!(x.contains(&format!("\"A")), "{x}"); - assert!(x.contains(&format!("\"Mark\"/")), "{x}"); - assert!(z.by_name(&format!("OEBPS/images/anim-frame-1-{a}.gif")).is_ok()); - } - - /// #775: the generic fallback follows the font, and embedded fonts are packaged and declared. - #[test] - fn generic_fallbacks_and_embedded_fonts() { - let none = BTreeMap::new(); - for (family, want) in [ - ("Source Serif 4", "serif"), - ("Source Sans 3", "sans-serif"), - ("Microsoft Sans Serif", "sans-serif"), - ("JetBrains Mono", "monospace"), - ("Courier New", "monospace"), - ("Franklin Gothic", "sans-serif"), - ("Garamond", "serif"), - ] { - assert_eq!(generic_family(family, &none), want, "{family}"); - } - let known: BTreeMap = - [("Montserrat".to_string(), "sans-serif".to_string()), ("Odd".to_string(), "nonsense".to_string())].into(); - assert_eq!(generic_family("Montserrat", &known), "sans-serif"); - assert_eq!(generic_family("Odd", &known), "serif", "only CSS generic families are used"); - assert_eq!(css_weight_style("Semibold Italic"), (600, "italic")); - assert_eq!(css_weight_style("Bold"), (700, "normal")); - assert_eq!(css_weight_style("Extra Bold"), (800, "normal")); - assert_eq!(css_weight_style("Regular"), (400, "normal")); - assert_eq!(css_weight_style("Light"), (300, "normal")); - assert_eq!(css_weight_style("Thin Oblique"), (100, "italic")); - assert_eq!(css_weight_style("Black"), (900, "normal")); - - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap(); - if let Some(basic) = d.styles_mut().paragraph.iter_mut().find(|s| s.name == story::BASIC_PARAGRAPH) { - basic.chars.font_family = Some("Montserrat".into()); - basic.chars.font_style = Some("Bold Italic".into()); - } - assert_eq!(stylesheet_fonts(&d), vec![("Montserrat".to_string(), "Bold Italic".to_string())]); - let opts = EpubOptions { - generic_families: known, - fonts: vec![EmbeddedFont { family: "Montserrat".into(), style: "Bold Italic".into(), data: b"OTTO font".to_vec() }], - ..Default::default() - }; - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &opts).unwrap())).unwrap(); - let mut read = |path: &str| { - let mut s = String::new(); - z.by_name(path).unwrap().read_to_string(&mut s).unwrap(); - s - }; - let css = read("OEBPS/style.css"); - assert!( - css.starts_with( - "@font-face { font-family: \"Montserrat\"; src: url(\"fonts/0-montserrat-bold-italic.otf\"); font-weight: 700; font-style: italic; }" - ), - "{css}" - ); - assert!(css.contains("font-family: \"Montserrat\", sans-serif;"), "{css}"); - let opf = read("OEBPS/content.opf"); - assert!(opf.contains(""), "{opf}"); - assert_eq!(read("OEBPS/fonts/0-montserrat-bold-italic.otf"), "OTTO font"); - // HTML takes the generic families too, and embeds nothing. - let html = export_html(&d, &HtmlOptions { generic_families: opts.generic_families.clone(), ..Default::default() }); - assert!(html.contains("\"Montserrat\", sans-serif;") && !html.contains("@font-face"), "{html}"); - } - - #[test] - fn metadata_is_serialized_for_its_output_context() { - let mut d = Document::new(&NewDocument::default()); - d.title = "Field Notes & ".into(); - let lid = d.default_layer(); - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "A&B \"D\"", ParaFormat::default()).unwrap(); - d.styles_mut().export_tags.insert( - format!("p:{}", story::BASIC_PARAGRAPH), - designcraft_doc::ExportTag { tag: "h2".into(), class: "Primary \"Copy\"".into(), ..Default::default() }, - ); - if let Some(basic) = d.styles_mut().paragraph.iter_mut().find(|s| s.name == story::BASIC_PARAGRAPH) { - basic.chars.font_family = Some("Quoted \"Serif\" ".into()); - } - - let aid = AssetId(d.alloc()); - d.assets.insert( - aid, - Arc::new(Asset { - id: aid, - name: "Cover & Notes".into(), - mime: "image/png; profile=screen".into(), - data: Arc::new(vec![1]), - pixels: Some((1, 1)), - ..Default::default() - }), - ); - let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(36.0, 120.0, 72.0, 156.0))); - item.alt_text = "Cover \"A\" & B".into(); - item.content = Content::Graphic(Graphic { - layer_options: None, - asset: aid, - size: (1.0, 1.0), - xf: Affine::IDENTITY, - clip: None, - auto_fit: Default::default(), - fit_align: 4, - crop: [0.0; 4], - wrap: Default::default(), - fill: Default::default(), - }); - d.insert_item(SpreadRef::Doc(0), item, None).unwrap(); - - let story = story_html(&d, sid); - assert!(story.contains("

    A&B <C> "D"

    ")); - let html = export_html(&d, &HtmlOptions { title: None, language: Some("English (US)".into()), ..Default::default() }); - assert!(html.contains("")); - assert!(html.contains("Field Notes & <Edition>")); - assert!(html.contains("alt=\"Cover "A" & B\"")); - assert!(html.contains("src=\"data:image/png;base64,AQ==\"")); - assert!(!html.contains("image/png; profile=screen")); - assert!(!stylesheet(&d).contains("")); - assert!(stylesheet(&d).contains("\\3c Alt\\3e ")); - - let bytes = export_epub( - &d, - &EpubOptions { - title: None, - author: Some("A & B".into()), - language: "English (US)".into(), - identifier: Some("notes&edition".into()), - cover: None, - ..Default::default() - }, - ) - .unwrap(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut opf = String::new(); - z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); - assert!(opf.contains("xml:lang=\"und\"")); - assert!(opf.contains("notes&edition")); - assert!(opf.contains("A & B")); - assert!(opf.contains("media-type=\"image/png\"")); - } - - /// File › File Info's Document Title and Author name the EPUB and the HTML page; the export - /// options' title and author replace them. - #[test] - fn file_info_titles_the_epub_and_the_html_page() { - let mut d = Document::new(&NewDocument { title: "flyer-v3".into(), ..Default::default() }); - d.file_info.document_title = "Spring & Summer".into(); - d.file_info.author = "Ana Ruiz".into(); - let opf = |d: &Document, opts: &EpubOptions| { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap(); - let mut opf = String::new(); - z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); - opf - }; - let o = opf(&d, &EpubOptions::default()); - assert!(o.contains("Spring & Summer") && o.contains("Ana Ruiz"), "{o}"); - let o = opf(&d, &EpubOptions { title: Some("Proof".into()), author: Some("Studio".into()), ..Default::default() }); - assert!(o.contains("Proof") && o.contains("Studio"), "{o}"); - let html = export_html(&d, &HtmlOptions::default()); - assert!(html.contains("Spring & Summer")); - d.file_info = Default::default(); - let o = opf(&d, &EpubOptions::default()); - assert!(o.contains("flyer-v3") && !o.contains(""), "{o}"); - } - - /// "Body¹ text", a 2×2 table, then "Closing" with an endnote. - fn tables_and_notes() -> Document { - let mut d = Document::new(&NewDocument::default()); - let lid = d.default_layer(); - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 400.0), lid, "Body text", ParaFormat::default()).unwrap(); - let st = d.story_mut(sid).unwrap(); - st.insert_note(4, "Foot note text", ParaFormat::default()); - let mut t = Table::new(1, 2, 2, 0, 0, 200.0); - for (r, c, s) in [(0, 0, "Cell A1"), (0, 1, "Cell B1"), (1, 0, "Cell A2"), (1, 1, "Cell B2")] { - t.cell_mut(r, c).unwrap().text = Story::with_text(StoryId(0), s, ParaFormat::default()); - } - let end = st.len(); - st.insert_table(end, t); - let end = st.len(); - st.insert(end, "Closing"); - let end = st.len(); - st.insert_endnote(end, "End note text", ParaFormat::default()); - d - } - - #[test] - fn tables_footnotes_and_endnotes_are_exported() { - let d = tables_and_notes(); - let bytes = export_epub(&d, &EpubOptions::default()).unwrap(); - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut html = String::new(); - z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap(); - let (t0, t1) = (html.find("").unwrap(), html.find("
    ").unwrap()); - for cell in ["Cell A1", "Cell B1", "Cell A2", "Cell B2"] { - let at = html.find(&format!("

    {cell}

    \n")).unwrap_or_else(|| panic!("{cell} in a cell:\n{html}")); - assert!(t0 < at && at < t1); - } - assert_eq!(html.matches("").count(), 2); - - let noteref = "Body
    1 text"; - assert!(html.contains(noteref), "footnote reference:\n{html}"); - let aside = html.find("").unwrap(); - assert!(html[aside..aside_end].contains("1 Foot note text")); - assert!(aside < t0, "the footnote follows its paragraph"); - - assert!(html.contains("Closing1")); - let section = html.find("
    ").unwrap(); - assert!(section > html.find("Closing").unwrap()); - assert!(html[section..].contains("
  • ")); - assert!(html[section..].contains("1 End note text")); - let mut nav = String::new(); - z.by_name("OEBPS/nav.xhtml").unwrap().read_to_string(&mut nav).unwrap(); - assert!(nav.contains("href=\"content.xhtml#endnotes\"")); - - let page = export_html(&d, &HtmlOptions::default()); - assert!(page.contains("