Merge pull request #89 from SteamSmith/fix/confirm-unsaved-work

fix(ui): ask before unsaved work is thrown away
This commit is contained in:
Rafael Mendes authored and GitHub committed 2026-11-05 15:31:09 -03:00
commit 797fe4d1c4
11 files changed
+444 -5

No files matched your search

+1
View File
@@ -289,6 +289,7 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p:
Ok(mut ui) => {
ui.graph_camera = ui.graph_camera.sanitized();
ui.image_camera = ui.image_camera.sanitized();
ui.windows.unsaved = app.ui.windows.unsaved.clone();
app.ui = ui;
ok(Value::Null)
}
+8
View File
@@ -26,6 +26,7 @@ pub mod state;
pub mod theme;
pub mod thumbs;
pub mod toolbar;
pub mod unsaved;
pub mod view2d;
pub mod view3d;
pub mod web_files;
@@ -70,6 +71,10 @@ pub struct MaterialCraftApp {
pub ui_ms: f32,
/// The last status message (bottom left).
pub status: String,
/// A package picked in the browser, waiting on the "unsaved changes" dialog: (name, bytes).
pub pending_load: Option<(String, Vec<u8>)>,
/// The user chose to discard (or saved): the window may close.
pub quit_confirmed: bool,
last_time: f64,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
next_autosave: f64,
@@ -113,6 +118,8 @@ impl MaterialCraftApp {
fps: 0.0,
ui_ms: 0.0,
status: String::new(),
pending_load: None,
quit_confirmed: false,
last_time: 0.0,
next_autosave,
styled: None,
@@ -237,6 +244,7 @@ impl MaterialCraftApp {
if (ctx.zoom_factor() - scale).abs() > 1e-3 && !ctx.input(|i| i.pointer.any_down()) {
ctx.set_zoom_factor(scale);
}
unsaved::handle_close(self, ctx);
control::poll(self, ctx);
web_files::poll(self);
for f in ctx.input(|i| i.raw.dropped_files.clone()) {
+50
View File
@@ -22,3 +22,53 @@ mod lib_tests {
assert!(execute_guarded(&mut s, "graph.node.add", &json!({"def": "levels"})).is_ok());
}
}
#[cfg(test)]
mod unsaved_state_tests {
use crate::unsaved::{Choice, Guarded, guard};
use crate::{MaterialCraftApp, state::UiState};
fn app(modified: bool) -> MaterialCraftApp {
let mut s = materialcraft_engine::sample_session();
s.modified = modified;
MaterialCraftApp::headless(s, UiState::default())
}
#[test]
fn closing_all_over_unsaved_work_waits_for_an_answer() {
let mut a = app(true);
let before = a.session.pkg.name.clone();
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
assert!(a.ui.windows.unsaved.is_some());
assert_eq!(a.session.pkg.name, before, "nothing was replaced yet");
// The held action is visible as serde state (control channel `ui.inspect`).
let v = serde_json::to_value(&a.ui).unwrap();
assert_eq!(v["windows"]["unsaved"]["kind"], "menu");
}
#[test]
fn closing_all_over_a_clean_package_just_happens() {
let mut a = app(false);
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
assert!(a.ui.windows.unsaved.is_none());
assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("New_graph"), "the empty package replaced it");
}
#[test]
fn discard_runs_the_held_action_and_cancel_keeps_the_work() {
let mut a = app(true);
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
let step = crate::unsaved::answer(&mut a.ui.windows.unsaved, Choice::Cancel);
assert_eq!(step, crate::unsaved::Step::Stop);
assert!(a.session.modified);
}
#[test]
fn a_pending_dialog_is_not_restored_from_saved_state() {
let mut a = app(true);
guard(&mut a, Guarded::Quit);
let saved = serde_json::to_string(&a.ui).unwrap();
let back: UiState = serde_json::from_str(&saved).unwrap();
assert!(back.windows.unsaved.is_none());
}
}
+2 -3
View File
@@ -125,9 +125,8 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
"ui.preferences" => app.ui.windows.preferences = true,
"ui.view.graph" => {}
"ui.resetLayout" => app.ui.dock = crate::docking::Dock::default(),
"ui.closeAll" => {
app.run("file.newPackage", Value::Null);
}
// These replace the open package: ask first when it has unsaved changes.
"ui.closeAll" | "file.newPackage" => crate::unsaved::guard(app, crate::unsaved::Guarded::Menu { id: id.to_string() }),
"ui.reloadResources" | "ui.clearCache" => {
if let Ok(mut c) = app.session.cache.lock() {
c.clear();
+4
View File
@@ -57,6 +57,10 @@ pub struct Windows {
pub preferences: bool,
pub shortcuts: bool,
pub home: bool,
/// The action waiting on the "unsaved changes" dialog (readable over the control channel;
/// never restored from a saved layout).
#[serde(skip_deserializing)]
pub unsaved: Option<crate::unsaved::Guarded>,
}
/// The graph view's camera: the graph point at the view's top-left corner, and the zoom.
+176
View File
@@ -0,0 +1,176 @@
//! Ask before unsaved work is thrown away.
//!
//! Opening a package, closing all, making an empty package, dropping a file on the window and
//! closing the window or quitting all replace or end the open package. When it has unsaved
//! changes, those paths ask first (Save / Discard / Cancel). Only these UI paths ask: engine
//! commands run by the control channel, MCP, the CLI and scripts never open a dialog.
//!
//! The decision is a pure state machine ([`request`], [`answer`], [`after_save`]) over the
//! serde [`Guarded`] action held in `Windows::unsaved`, so tests and the control channel
//! (`ui.inspect`) can see it. The glue below runs the held action once it is allowed.
use egui::{Align2, Context, RichText, Window};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::MaterialCraftApp;
use crate::i18n::tr;
/// An action that would throw the open package's unsaved work away.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Guarded {
/// A menu item: `ui.closeAll` or `file.newPackage`.
Menu { id: String },
/// Open the package at `path` (desktop).
OpenPath { path: String },
/// Open the package whose bytes wait in `MaterialCraftApp::pending_load` (browser).
LoadBytes { name: String },
/// Close the window.
Quit,
}
/// What the user picked in the dialog.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Choice {
Save,
Discard,
Cancel,
}
/// What to do after an answer.
#[derive(Clone, Debug, PartialEq)]
pub enum Step {
/// Run the action now.
Run(Guarded),
/// Save first, then run the action if the package is no longer modified.
Save(Guarded),
/// Do nothing.
Stop,
}
/// Does throwing this session away lose work?
pub fn needs_confirmation(session: &materialcraft_engine::Session) -> bool {
session.modified
}
/// Ask to run `action`. Returns it when it can run now; otherwise holds it in `pending` for the
/// dialog (an action already waiting is kept) and returns `None`.
pub fn request(pending: &mut Option<Guarded>, modified: bool, action: Guarded) -> Option<Guarded> {
if pending.is_some() {
return None;
}
if !modified {
return Some(action);
}
if pending.is_none() {
*pending = Some(action);
}
None
}
/// Apply the user's answer to the held action.
pub fn answer(pending: &mut Option<Guarded>, choice: Choice) -> Step {
match (pending.take(), choice) {
(Some(a), Choice::Discard) => Step::Run(a),
(Some(a), Choice::Save) => Step::Save(a),
_ => Step::Stop,
}
}
/// After a save attempt, the action may run only when the package really was saved.
pub fn after_save(still_modified: bool, action: Guarded) -> Option<Guarded> {
(!still_modified).then_some(action)
}
/// Should a window-close request be held back for the dialog?
pub fn holds_close(modified: bool, confirmed: bool) -> bool {
modified && !confirmed
}
/// Run `action`, asking first when the package has unsaved changes.
pub fn guard(app: &mut MaterialCraftApp, action: Guarded) {
let modified = needs_confirmation(&app.session);
if let Some(a) = request(&mut app.ui.windows.unsaved, modified, action) {
perform(app, a);
}
}
/// Run an allowed action.
fn perform(app: &mut MaterialCraftApp, action: Guarded) {
match action {
Guarded::Menu { .. } => {
app.run("file.newPackage", Value::Null);
}
#[cfg(not(target_arch = "wasm32"))]
Guarded::OpenPath { path } => crate::windows::open_path_now(app, &path),
#[cfg(target_arch = "wasm32")]
Guarded::OpenPath { .. } => {}
Guarded::LoadBytes { .. } => {
if let Some((name, bytes)) = app.pending_load.take() {
crate::web_files::load_now(app, &name, &bytes);
}
}
Guarded::Quit => app.quit_confirmed = true,
}
}
/// Per frame: hold back a window close while there is unsaved work, and finish a confirmed quit.
pub fn handle_close(app: &mut MaterialCraftApp, ctx: &Context) {
if ctx.input(|i| i.viewport().close_requested()) && holds_close(needs_confirmation(&app.session), app.quit_confirmed) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
guard(app, Guarded::Quit);
}
if app.quit_confirmed {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
/// The Save / Discard / Cancel dialog, while an action is held.
pub fn show(app: &mut MaterialCraftApp, ctx: &Context) {
if app.ui.windows.unsaved.is_none() {
return;
}
let mut choice = None;
Window::new(tr("Unsaved changes"))
.id(egui::Id::unique("unsaved-changes"))
.collapsible(false)
.resizable(false)
.pivot(Align2::CENTER_CENTER)
.default_pos(ctx.content_rect().center())
.show(ctx, |ui| {
ui.label(RichText::new(format!("{} \"{}\"?", tr("Save changes to"), app.session.pkg.name)).strong());
ui.label(tr("Your changes will be lost if you don't save them."));
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.button(tr("Save")).clicked() {
choice = Some(Choice::Save);
}
if ui.button(tr("Discard")).clicked() {
choice = Some(Choice::Discard);
}
if ui.button(tr("Cancel")).clicked() {
choice = Some(Choice::Cancel);
}
});
});
if choice.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
choice = Some(Choice::Cancel);
}
let Some(choice) = choice else { return };
match answer(&mut app.ui.windows.unsaved, choice) {
Step::Run(a) => perform(app, a),
Step::Save(a) => {
crate::windows::file_action(app, ctx, "file.save");
match after_save(needs_confirmation(&app.session), a) {
Some(a) => perform(app, a),
None => app.pending_load = None,
}
}
Step::Stop => app.pending_load = None,
}
}
#[cfg(test)]
#[path = "unsaved.test.rs"]
mod tests;
+95
View File
@@ -0,0 +1,95 @@
#[cfg(test)]
mod unsaved_tests {
use crate::unsaved::{Choice, Guarded, Step, after_save, answer, needs_confirmation, request};
fn open() -> Guarded {
Guarded::OpenPath { path: "a.sbs".into() }
}
#[test]
fn a_clean_session_never_asks() {
let mut s = materialcraft_engine::sample_session();
s.modified = false;
assert!(!needs_confirmation(&s));
let mut pending = None;
assert_eq!(request(&mut pending, false, open()), Some(open()));
assert_eq!(pending, None);
}
#[test]
fn a_modified_session_asks_and_holds_the_action() {
let mut s = materialcraft_engine::sample_session();
s.modified = true;
assert!(needs_confirmation(&s));
let mut pending = None;
assert_eq!(request(&mut pending, true, open()), None);
assert_eq!(pending, Some(open()));
}
#[test]
fn the_first_pending_action_is_kept() {
let mut pending = None;
request(&mut pending, true, open());
assert_eq!(request(&mut pending, true, Guarded::Quit), None);
assert_eq!(pending, Some(open()));
}
#[test]
fn cancel_drops_discard_runs_save_saves_first() {
let mut pending = Some(open());
assert_eq!(answer(&mut pending, Choice::Cancel), Step::Stop);
assert_eq!(pending, None);
let mut pending = Some(open());
assert_eq!(answer(&mut pending, Choice::Discard), Step::Run(open()));
assert_eq!(pending, None);
let mut pending = Some(open());
assert_eq!(answer(&mut pending, Choice::Save), Step::Save(open()));
assert_eq!(pending, None);
assert_eq!(answer(&mut None, Choice::Discard), Step::Stop, "nothing pending, nothing to run");
}
#[test]
fn closing_the_window_is_held_only_for_unsaved_work() {
use crate::unsaved::holds_close;
assert!(holds_close(true, false));
assert!(!holds_close(false, false));
assert!(!holds_close(true, true), "after Discard the close goes through");
}
#[test]
fn the_action_runs_after_save_only_when_the_save_worked() {
assert_eq!(after_save(false, open()), Some(open()));
assert_eq!(after_save(true, open()), None, "still modified: the save was cancelled or failed");
}
}
#[test]
fn a_second_package_cannot_replace_the_payload_waiting_for_confirmation() {
use crate::unsaved::{Choice, Guarded, Step};
let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
app.session.modified = true;
let bytes = |name: &str| materialcraft_engine::formats::save_package(&materialcraft_engine::core::Package::new(name)).unwrap();
crate::web_files::load(&mut app, "first.mcraft", bytes("First"), false);
crate::web_files::load(&mut app, "second.mcraft", bytes("Second"), false);
assert_eq!(app.ui.windows.unsaved, Some(Guarded::LoadBytes { name: "first.mcraft".into() }));
let result = crate::control::handle(&mut app, &egui::Context::default(), "ui.set", &serde_json::json!({"prefs": {"thumbnails": false}}));
assert_eq!(result["ok"], true);
assert!(app.ui.windows.unsaved.is_some());
if let Step::Run(action) = crate::unsaved::answer(&mut app.ui.windows.unsaved, Choice::Discard) {
crate::unsaved::perform(&mut app, action);
} else {
panic!("missing held action");
}
assert_eq!(app.session.pkg.name, "First");
}
#[test]
fn a_pending_action_is_kept_even_if_the_package_was_saved_elsewhere() {
let first = crate::unsaved::Guarded::Quit;
let mut pending = Some(first.clone());
assert!(crate::unsaved::request(&mut pending, false, crate::unsaved::Guarded::Menu { id: "ui.closeAll".into() }).is_none());
assert_eq!(pending, Some(first));
}
+39 -1
View File
@@ -75,7 +75,21 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool
}
return;
}
match materialcraft_engine::file_cmds::open_bytes(&mut app.session, &bytes, Some(name.to_string())) {
if app.ui.windows.unsaved.is_some() {
return;
}
// Opening a package replaces the open one: ask first when it has unsaved changes.
if crate::unsaved::needs_confirmation(&app.session) {
app.pending_load = Some((name.to_string(), bytes));
crate::unsaved::guard(app, crate::unsaved::Guarded::LoadBytes { name: name.to_string() });
return;
}
load_now(app, name, &bytes);
}
/// Open a package from bytes, replacing the open one (already confirmed).
pub fn load_now(app: &mut MaterialCraftApp, name: &str, bytes: &[u8]) {
match materialcraft_engine::file_cmds::open_bytes(&mut app.session, bytes, Some(name.to_string())) {
Ok(()) => {
app.ui.frame_all = true;
app.toast(format!("{} {name}", tr("Opened")), false);
@@ -245,6 +259,30 @@ mod web {
mod tests {
use super::*;
fn app(modified: bool) -> MaterialCraftApp {
let mut s = materialcraft_engine::sample_session();
s.modified = modified;
MaterialCraftApp::headless(s, crate::state::UiState::default())
}
#[test]
fn a_package_picked_over_unsaved_work_is_held_not_loaded() {
let mut app = app(true);
let before = app.session.pkg.name.clone();
load(&mut app, "other.sbs", b"not a package".to_vec(), false);
assert_eq!(app.ui.windows.unsaved, Some(crate::unsaved::Guarded::LoadBytes { name: "other.sbs".into() }));
assert_eq!(app.pending_load.as_ref().map(|(n, _)| n.as_str()), Some("other.sbs"));
assert_eq!(app.session.pkg.name, before);
assert!(app.toasts.is_empty());
}
#[test]
fn an_image_import_is_not_a_replacement_and_never_asks() {
let mut app = app(true);
load(&mut app, "x.png", b"junk".to_vec(), true);
assert!(app.ui.windows.unsaved.is_none());
}
#[test]
fn zip_round_trips() {
let files = vec![("a.png".to_string(), b"one".to_vec()), ("b.png".to_string(), vec![7u8; 4096])];
+13 -1
View File
@@ -96,6 +96,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if app.ui.windows.home {
home(app, ctx);
}
crate::unsaved::show(app, ctx);
}
fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) {
@@ -637,9 +638,16 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
}
}
/// Open a package from a path (recent list, command line).
/// Open a package from a path (recent list, drag and drop, command line). Asks first when the
/// open package has unsaved changes.
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path(app: &mut MaterialCraftApp, path: &str) {
crate::unsaved::guard(app, crate::unsaved::Guarded::OpenPath { path: path.to_string() });
}
/// Open a package from a path, replacing the open one (already confirmed).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_path_now(app: &mut MaterialCraftApp, path: &str) {
if app.run("file.open", json!({"path": path})).is_some() {
app.ui.add_recent(path);
app.ui.frame_all = true;
@@ -647,3 +655,7 @@ pub fn open_path(app: &mut MaterialCraftApp, path: &str) {
after_open(app);
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "windows.test.rs"]
mod tests;
+25
View File
@@ -0,0 +1,25 @@
#[cfg(test)]
mod open_guard_tests {
use crate::unsaved::Guarded;
use crate::{MaterialCraftApp, state::UiState};
#[test]
fn opening_a_path_over_unsaved_work_asks_first() {
let mut s = materialcraft_engine::sample_session();
s.modified = true;
let mut app = MaterialCraftApp::headless(s, UiState::default());
crate::windows::open_path(&mut app, "does-not-exist.sbs");
assert_eq!(app.ui.windows.unsaved, Some(Guarded::OpenPath { path: "does-not-exist.sbs".into() }));
assert!(app.toasts.is_empty(), "nothing was attempted yet");
}
#[test]
fn opening_a_path_over_a_clean_package_goes_straight_to_open() {
let mut s = materialcraft_engine::sample_session();
s.modified = false;
let mut app = MaterialCraftApp::headless(s, UiState::default());
crate::windows::open_path(&mut app, "does-not-exist.sbs");
assert!(app.ui.windows.unsaved.is_none());
assert!(!app.toasts.is_empty(), "the open was attempted and its error reported");
}
}
+31
View File
@@ -0,0 +1,31 @@
use egui::{Rect, vec2};
use egui_kittest::{Harness, kittest::Queryable};
use materialcraft_ui_egui::{
MaterialCraftApp, UiState,
unsaved::{self, Guarded},
};
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn unsaved_dialog_snapshot_and_cancel() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.session.modified = true;
unsaved::guard(&mut app, Guarded::Menu { id: "ui.closeAll".into() });
let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(10);
let rect = h.ctx.memory(|m| m.area_rect(egui::Id::unique("unsaved-changes"))).unwrap_or(Rect::NOTHING);
assert!(rect.is_finite() && rect.width() > 100.0);
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR"));
std::fs::create_dir_all(&dir).unwrap();
h.render().unwrap().save(dir.join("unsaved-changes.png")).unwrap();
h.get_by_label("Cancel").click();
h.run_steps(5);
assert!(h.state().ui.windows.unsaved.is_none());
assert!(h.state().session.modified);
}