DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #80: Alert dialog when Open/Place/drop/CLI/app.open fails; one opens_as_document rule for drops
aiongg664408e9ac02
diff --cc crates/ui-egui/src/dialogs.rsindex 756662eff,450e64c2f..87bfa4292--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -839,7 -839,11 +841,12 @@@ pub fn show(app: &mut DesignApp, ctx: &};egui::Modal::new(egui::Id::new("dialog")).show(ctx, |ui| {ui.set_min_width(380.0);- ui.set_max_width(if d.id == "closeDocument" || (d.id == "newDocument" && crate::i18n::is_rtl(&app.ui.language)) { 380.0 } else { 640.0 });+ ui.set_max_width(match d.id.as_str() {+ "alert" => 440.0,++ "closeDocument" => 380.0,+ "newDocument" if crate::i18n::is_rtl(&app.ui.language) => 380.0,+ _ => 640.0,+ });if crate::i18n::is_rtl(&app.ui.language) {ui.horizontal(|ui| {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {@@@ -1389,13 -1395,11 +1404,15 @@@{result = Some(true);}- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Cancel"))).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ // An alert only has OK.+ let cancel = d.id != "alert" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Cancel"))).clicked();+ if cancel || ui.input(|i| i.key_pressed(egui::Key::Escape)) {result = Some(false);}+ if d.id == "closeDocument" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Don't Save"))).clicked() {+ d.fields.insert("discard".into(), json!(true));+ result = Some(true);+ }});});});@@@ -1660,25 -1617,7 +1677,25 @@@ pub fn confirm(app: &mut DesignApp) ->app.run("document.preferences", doc)}"newWorkspace" => app.run("window.newWorkspace", json!({"name": d.s("name")})),+ "closeDocument" => {+ // The document may have moved in the tab row (or gone) while the dialog was open.+ let uid = d.fields.get("uid").and_then(Value::as_u64);+ let index = |app: &DesignApp| app.session.documents().iter().position(|doc| Some(doc.uid) == uid);+ let Some(i) = index(app) else { return Ok(Value::Null) };+ if !d.b("discard") {+ app.run("file.activate", json!({"index": i}))?;+ app.run("app.save", json!({}))?;+ // Still unsaved: the save was cancelled (no file chosen). Keep the document open.+ if app.session.documents().get(i).is_none_or(|doc| doc.is_dirty()) {+ return Ok(Value::Null);+ }+ }+ match index(app) {+ Some(i) => app.run("file.close", json!({"index": i})),+ None => Ok(Value::Null),+ }+ }- "importOptions" => app.run(+ "importOptions" => app.open_file("file.place",json!({"path": d.s("path"), "removeStyles": d.b("removeStyles"), "styleConflicts": d.s("styleConflicts"), "styleMap": d.fields.get("map").cloned().unwrap_or(json!({}))}),),diff --cc crates/ui-egui/src/lib.rsindex a6c4fa9e8,43a08167f..aa304bd61--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -1020,63 -906,81 +1043,140 @@@ mod testsassert!(!ui.snap_view().snap_to_guides);assert_eq!(ui.snap_view().zone_px, 0.0);}++ /// 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"] {+ assert!(opens_as_document(name), "{name}");+ }+ for name in ["a.png", "b.pdf", "idml.txt", "c.idml.zip"] {+ assert!(!opens_as_document(name), "{name}");+ }+ }++ #[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 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");+ }}++/// The whole window in a headless test harness, at a chosen window size.+#[cfg(test)]+pub(crate) mod test_window {+ use egui_kittest::Harness;++ pub struct Window {+ pub app: crate::DesignApp,+ ready: bool,+ }++ /// The window at `size` with a new document open.+ pub fn open(mut app: crate::DesignApp, size: egui::Vec2) -> Harness<'static, Window> {+ if app.session.active().is_none() {+ app.run("file.new", serde_json::json!({})).unwrap();+ }+ let mut h = Harness::builder().with_size(size).with_max_steps(1000).build_ui_state(+ |ui, w: &mut Window| {+ // The builder runs a frame before the texture size can be raised: skip it.+ if !w.ready {+ return;+ }+ let ctx = ui.ctx().clone();+ w.app.logic(&ctx);+ w.app.ui(ui);+ },+ Window { app, ready: false },+ );+ h.input_mut().max_texture_side = Some(8192);+ h.state_mut().ready = true;+ h.run_steps(6);+ h+ }++ /// The mouse wheel turned over `pos`: positive `delta` moves the content right and down.+ pub fn wheel(h: &mut Harness<'static, Window>, pos: egui::Pos2, delta: egui::Vec2) {+ h.hover_at(pos);+ h.event(egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta,+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ });+ h.run_steps(10);+ }++ /// The outer rect of a side or top panel, from egui's memory.+ pub fn panel_rect(h: &Harness<'static, Window>, id: &str) -> egui::Rect {+ egui::containers::panel::PanelState::load(&h.ctx, egui::Id::new(id)).map(|s| s.outer_rect).unwrap()+ }++ /// A primary click at `pos`, then a few frames.+ pub fn click_at(h: &mut Harness<'static, Window>, pos: egui::Pos2) {+ h.hover_at(pos);+ h.drag_at(pos);+ h.drop_at(pos);+ h.run_steps(4);+ }+}