Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge quit-unsaved: quitting asks to save documents with unsaved changes (#544)

aionggc0b28a44780a
diff --cc apps/designcraft/src/native_menu.rs
index 9cacd03fc,f51db197a..d9a0aad90
--- a/apps/designcraft/src/native_menu.rs
+++ b/apps/designcraft/src/native_menu.rs
@@@ -43,28 -35,30 +43,27 @@@ impl NativeMenu
let menu = Menu::new();
let mut items = HashMap::new();
let mut counter = 0usize;
- // Application menu.
+ // Application menu: our own About splash (with the community links) instead of the stock
+ // panel, and Settings… (Edit › Preferences… on the other platforms).
let app_menu = Submenu::new("DesignCraft", true);
- // Our own About splash (with the community links) instead of the stock panel.
- let about = MenuItem::with_id("dc-about", "About DesignCraft", true, None);
- let discord = MenuItem::with_id("dc-discord", "Join the ArtCraft Discord…", true, None);
- // Not the predefined Quit: it terminates the app at once, past the unsaved-changes prompt.
- let quit = MenuItem::with_id("dc-quit", designcraft_ui_egui::i18n::tr(&app.ui.language, "Quit DesignCraft"), true, accel("Cmd+Q"));
- let _ = app_menu.append_items(&[
- &about,
- &discord,
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::services(None),
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::hide(None),
- &PredefinedMenuItem::hide_others(None),
- &PredefinedMenuItem::show_all(None),
- &PredefinedMenuItem::separator(),
- &quit,
- ]);
- items.insert("dc-about".into(), ("help.about".into(), serde_json::Value::Null, Handle::Plain(about)));
- items.insert("dc-discord".into(), ("help.discord".into(), serde_json::Value::Null, Handle::Plain(discord)));
- items.insert("dc-quit".into(), ("app.quit".into(), serde_json::Value::Null, Handle::Plain(quit)));
+ for entry in menus::MAC_APP_MENU {
+ let _ = match *entry {
+ AppMenuItem::Cmd { id, label, command } => {
+ let sc = shortcut(command).and_then(accel);
+ let item = MenuItem::with_id(id, designcraft_ui_egui::i18n::tr(&app.ui.language, label), true, sc);
+ let appended = app_menu.append(&item);
+ items.insert(id.into(), (command.into(), Value::Null, Handle::Plain(item)));
+ appended
+ }
+ AppMenuItem::Sep => app_menu.append(&PredefinedMenuItem::separator()),
+ AppMenuItem::Services => app_menu.append(&PredefinedMenuItem::services(None)),
+ AppMenuItem::Hide => app_menu.append(&PredefinedMenuItem::hide(None)),
+ AppMenuItem::HideOthers => app_menu.append(&PredefinedMenuItem::hide_others(None)),
+ AppMenuItem::ShowAll => app_menu.append(&PredefinedMenuItem::show_all(None)),
- AppMenuItem::Quit => app_menu.append(&PredefinedMenuItem::quit(None)),
+ };
+ }
let _ = menu.append(&app_menu);
- for (title, entries) in menus::menu_tree() {
+ for (title, entries) in menus::native_menu_tree() {
let sub = Submenu::new(designcraft_ui_egui::i18n::tr(&app.ui.language, title), true);
build(app, &sub, &entries, &mut items, &mut counter);
let _ = menu.append(&sub);
diff --cc crates/ui-egui/src/lib.rs
index e5356ca77,240d2166b..2db78c90f
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -539,25 -510,12 +539,31 @@@ pub struct DesignApp
last_time: f64,
/// When recovery data was last written (seconds, egui time).
pub last_recovery: f64,
+ /// The egui context (set by the first frame): copied text goes to the system clipboard through it.
+ egui_ctx: Option<egui::Context>,
+ /// A control-channel request is being handled: commands it runs never read or write the
+ /// user's system clipboard (a control client must not see or replace it).
+ pub(crate) in_control: bool,
+ /// The system clipboard's text that stands for the last object copy: what that copy put there
+ /// (no native menu: without it the paste keys produce no paste event), or what it held then
+ /// (native menu). It is never pasted as text: Paste with it pastes the copied objects.
+ object_clip_text: Option<String>,
+ /// The marked text the system IME last sent (`None` once it commits or clears). When the
+ /// composition ends some other way (a click, a tool switch), the IME is told to drop it.
+ pub(crate) ime_marked: Option<String>,
+ /// The system IME must drop its marked text (see [`Self::take_ime_discard`]).
+ pub(crate) ime_discard: bool,
+ /// The canvas asked for the system IME in the last frame (the web build's text input has the
+ /// keyboard then).
+ pub(crate) canvas_ime: bool,
+ /// The tool cursor bitmaps handed to the OS.
+ pub cursors: cursors::Images,
+ /// Quit was chosen: close the window on the next frame, as its close button does.
+ quit_requested: bool,
+ /// Close the window without asking about unsaved changes (the control channel's `app.quit`).
+ pub(crate) quit_without_asking: bool,
+ /// Quitting waits for the user's answer about the unsaved document with this uid.
+ quitting: Option<u64>,
}
impl DesignApp {
@@@ -597,13 -553,9 +603,16 @@@
native_shortcuts: Default::default(),
last_time: 0.0,
last_recovery: 0.0,
+ egui_ctx: None,
+ in_control: false,
+ object_clip_text: None,
+ ime_marked: None,
+ ime_discard: false,
+ canvas_ime: false,
+ cursors: cursors::Images::default(),
+ quit_requested: false,
+ quit_without_asking: false,
+ quitting: None,
}
}
@@@ -1005,14 -811,61 +1014,64 @@@
let _ = self.open_dropped(&p);
}
}
+ self.handle_quit(ctx);
+ }
+
+ /// Quit: close the window the way its close button does, so unsaved documents ask first.
+ pub fn request_quit(&mut self) {
+ self.quit_requested = true;
+ }
+
+ /// Closing the window (close button, Quit) with unsaved documents: keep it open and ask about
+ /// each of them in turn with the dialog File › Close uses. Save and Don't Save go on to the
+ /// next one and the window closes after the last; Cancel, or a cancelled Save As, stops.
+ fn handle_quit(&mut self, ctx: &egui::Context) {
+ if std::mem::take(&mut self.quit_requested) {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ }
+ if ctx.input(|i| i.viewport().close_requested()) {
+ if self.quit_without_asking || !self.session.documents().iter().any(|d| d.is_dirty()) {
+ self.quitting = None;
+ return;
+ }
+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
+ let asking = self.quitting.is_some() && self.ui.dialog.as_ref().is_some_and(|d| d.id == "closeDocument");
+ if !asking {
+ self.ask_next_unsaved(ctx);
+ }
+ return;
+ }
+ let Some(uid) = self.quitting else { return };
+ if self.ui.dialog.is_some() {
+ return;
+ }
+ // Still open: the user cancelled, or the save didn't happen.
+ if self.session.documents().iter().any(|d| d.uid == uid) {
+ self.quitting = None;
+ return;
+ }
+ self.ask_next_unsaved(ctx);
+ }
+
+ /// Ask about the first document with unsaved changes (shown, so the user sees which one),
+ /// or close the window when none is left.
+ fn ask_next_unsaved(&mut self, ctx: &egui::Context) {
+ let Some((i, uid)) = self.session.documents().iter().enumerate().find(|(_, d)| d.is_dirty()).map(|(i, d)| (i, d.uid)) else {
+ self.quitting = None;
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ return;
+ };
+ let _ = self.run("file.activate", json!({"index": i}));
+ menus::close_document(self, Some(i));
+ self.quitting = Some(uid);
}
- /// A file dropped on the window: documents open, anything else is placed.
+ /// A file dropped on the window: documents open, anything else is placed. A file without an
+ /// extension opens when its content is a DesignCraft or IDML document.
pub fn open_dropped(&mut self, path: &str) -> Result<Value, String> {
- let cmd = if opens_as_document(path) { "file.open" } else { "file.place" };
+ let document = opens_as_document(path)
+ || (std::path::Path::new(path).extension().is_none() && std::fs::read(path).is_ok_and(|b| designcraft_engine::cmd::is_document(&b)));
+ let cmd = if document { "file.open" } else { "file.place" };
self.open_file(cmd, json!({"path": path}))
}
@@@ -1469,38 -1217,128 +1528,125 @@@ mod tests
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<egui::ViewportCommand> {
+ 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<u64> {
+ 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<u64> = 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:?}");
+ }
+ // Only the saved document is left: the close goes through.
+ assert!(quit_frame(&mut app, &ctx, true).is_empty());
+ }
+
+ #[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 control_bar_shows_its_second_row() {
- use egui_kittest::kittest::Queryable as _;
- 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, egui::Id::new("control_bar")).unwrap().outer_rect;
- assert!(bar.height() > 40.0, "{bar:?}");
- let rows: Vec<egui::Rect> = h.query_all_by_label("Y:").map(|n| n.rect()).filter(|r| bar.contains(r.left_top())).collect();
- assert_eq!(rows.len(), 1, "the Y: caption of the Control panel");
- assert!(rows[0].bottom() <= bar.bottom(), "Y: caption {:?} hangs below the Control panel {bar:?}", rows[0]);
- }
-
- #[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("Æ")]);
- // A focused text field gets its text from input events, which can be whole words.
- let mut raw = egui::RawInput { events: events(), ..Default::default() };
- drop_key_name_text(&mut raw, true);
- assert_eq!(raw.events, events());
+ 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]
diff --cc crates/ui-egui/src/menus.rs
index 78bfb6238,cb1422394..9a29f4af1
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -1922,76 -1757,6 +1927,76 @@@ pub fn menu_tree() -> Vec<(&'static str
MENUS.iter().map(|(m, e)| (*m, parse_entries(e))).collect()
}
+/// A row of the macOS application menu (the menu named after the app).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AppMenuItem {
+ /// Runs `command` (no parameters); `id` is the native menu item id, `label` goes through `i18n::tr`.
+ Cmd {
+ id: &'static str,
+ label: &'static str,
+ command: &'static str,
+ },
+ Sep,
+ Services,
+ Hide,
+ HideOthers,
+ ShowAll,
- Quit,
+}
+
+/// The macOS application menu. Settings… is `app.preferences`, which `native_menu_tree` leaves out of Edit.
+pub const MAC_APP_MENU: &[AppMenuItem] = &[
+ AppMenuItem::Cmd { id: "dc-about", label: "About DesignCraft", command: "help.about" },
+ AppMenuItem::Cmd { id: "dc-discord", label: "Join the ArtCraft Discord…", command: "help.discord" },
+ AppMenuItem::Sep,
+ AppMenuItem::Cmd { id: "dc-settings", label: "Settings…", command: "app.preferences" },
+ AppMenuItem::Sep,
+ AppMenuItem::Services,
+ AppMenuItem::Sep,
+ AppMenuItem::Hide,
+ AppMenuItem::HideOthers,
+ AppMenuItem::ShowAll,
+ AppMenuItem::Sep,
- AppMenuItem::Quit,
++ // Not the predefined Quit: it terminates the app at once, past the unsaved-changes prompt.
++ AppMenuItem::Cmd { id: "dc-quit", label: "Quit DesignCraft", command: "app.quit" },
+];
+
+/// The menu tree for the macOS menu bar: `menu_tree` without the commands `MAC_APP_MENU` holds,
+/// so each command (and its shortcut) appears once.
+pub fn native_menu_tree() -> Vec<(&'static str, Vec<Item>)> {
+ let in_app_menu = |id: &str| MAC_APP_MENU.iter().any(|m| matches!(m, AppMenuItem::Cmd { command, .. } if *command == id));
+ let mut tree = menu_tree();
+ for (_, entries) in &mut tree {
+ without_commands(entries, &in_app_menu);
+ }
+ tree
+}
+
+/// Drops the parameterless commands `drop` matches from `entries` (recursively), then any separator
+/// the removal left at an end or next to another.
+fn without_commands(entries: &mut Vec<Item>, drop: &dyn Fn(&str) -> bool) {
+ let before = entries.len();
+ entries.retain(|e| !matches!(e, Item::Cmd { id, params, .. } if params.is_null() && drop(id)));
+ for e in entries.iter_mut() {
+ if let Item::Sub(_, children) = e {
+ without_commands(children, drop);
+ }
+ }
+ if entries.len() == before {
+ return;
+ }
+ let mut tidy: Vec<Item> = Vec::with_capacity(entries.len());
+ for e in entries.drain(..) {
+ if matches!(e, Item::Sep) && tidy.last().is_none_or(|l| matches!(l, Item::Sep)) {
+ continue;
+ }
+ tidy.push(e);
+ }
+ if matches!(tidy.last(), Some(Item::Sep)) {
+ tidy.pop();
+ }
+ *entries = tidy;
+}
+
/// Check state of a toggle command (None = not a toggle).
pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option<bool> {
Some(match id {