Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor b2accf8484 Merge main into fix/sec-script-confinement-grants 2026-12-06 09:10:29 -05:00
Dylan M. Taylor 077b487e17 fix(engine): purge unlock grants after each restored history step 2026-12-06 09:10:19 -05:00
FredAppsandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> f77d672f83 Merge pull request #4884
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-05 07:37:01 +00:00
FredAppsandautocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> e2b2084eb2 Merge pull request #5038
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
2026-12-05 07:37:01 +00:00
yoriswind 2ecd0cf70a Merge official main for exact shared font adapter validation 2026-12-04 22:37:20 -08:00
yoriswind 2c0d199321 Preserve table headers when changing calculation options 2026-12-03 09:18:56 -08:00
yoriswind 4a604e7a17 xlsx: apply hosted font adapter formatting 2026-11-28 12:42:56 -08:00
yoriswind f4062709c4 xlsx: map cell and differential fonts through shared Font 2026-11-28 11:20:15 -08:00
Dylan M. Taylor 6eaa4bc928 fix(engine): undo and redo purge stale grants; explicit-text paste is not a clipboard read 2026-11-11 22:46:39 +00:00
Dylan M. Taylor bd027bc05b fix(engine): scripts stay in their workbook, cannot approve for the person; unlock grants follow the sheet 2026-11-11 20:44:21 +00:00
38 changed files with 376 additions and 504 deletions
Generated
-1
View File
@@ -3170,7 +3170,6 @@ dependencies = [
"craft-host",
"craft-keymap",
"craft-print",
"craft-quit",
"craft-theme",
"craft-ui",
"craft-update",
-1
View File
@@ -110,7 +110,6 @@ craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
[workspace.lints.rust]
unsafe_code = "forbid"
+8
View File
@@ -496,11 +496,19 @@ pub(crate) fn commit<R>(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result<R>)
if let Some(t0) = t0 {
eprintln!("commit: + rows {:?}", since(t0));
}
// A grant to edit a protected range belongs to the sheet and range it was given for: a sheet that
// was renamed, deleted or replaced by another of the same name no longer carries it.
purge_unlock_grants(&mut d.unlocked_ranges, &wb);
d.wb = std::sync::Arc::new(wb);
d.selection = sel;
Ok(r)
}
/// Drops the grants to edit protected ranges whose sheet name or range title `wb` no longer has.
pub(crate) fn purge_unlock_grants(grants: &mut Vec<(String, String)>, wb: &Workbook) {
grants.retain(|(sheet, title)| wb.sheets.iter().any(|sh| sh.name == *sheet && sh.edit_ranges.iter().any(|r| r.title == *title)));
}
/// "Set precision as displayed": a number typed, pasted or reformatted is stored as its format
/// shows it (Excel rounds a constant when it is entered and when its cell's format changes,
/// observed through COM). Only cells the edit touched are visited, so this costs nothing for
+4
View File
@@ -208,6 +208,8 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
super::extra::keep_view_modes(d, &cur_wb);
super::view::keep_zoom(d, &cur_wb);
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
// Each step, as separate requests would: a grant whose range a middle step removes goes.
crate::cmd::purge_unlock_grants(&mut d.unlocked_ranges, &d.wb);
}
super::extra::keep_watch_list(&now, &mut d.wb);
super::extra::keep_page_breaks(d, &now);
@@ -231,6 +233,8 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
super::extra::keep_view_modes(d, &cur_wb);
super::view::keep_zoom(d, &cur_wb);
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
// Each step, as separate requests would: a grant whose range a middle step removes goes.
crate::cmd::purge_unlock_grants(&mut d.unlocked_ranges, &d.wb);
}
super::extra::keep_watch_list(&now, &mut d.wb);
super::extra::keep_page_breaks(d, &now);
+38 -1
View File
@@ -75,6 +75,9 @@ fn denied_script_step(id: &str, params: &Json) -> Option<String> {
None
}
/// Commands that read the session's clipboard, which a script may use only for a copy made in its own workbook.
const CLIPBOARD_READERS: [&str; 3] = ["edit.paste", "edit.pasteSpecial", "home.insertCopiedCells"];
pub(super) fn trust_scripts(s: &mut Session, p: &Json) -> Result<Json> {
// Only a missing `trusted` means "trust"; `"false"`, `0` or `null` are mistakes, not consent.
let trusted = match p.get("trusted") {
@@ -86,6 +89,23 @@ pub(super) fn trust_scripts(s: &mut Session, p: &Json) -> Result<Json> {
Ok(json!({"trusted": trusted}))
}
/// Whether step `id` with `params` takes cells from the session clipboard: not `edit.paste` of explicit
/// text that differs from it (that pastes the text, see `edit::clipboard::paste`).
fn reads_clipboard(s: &Session, id: &str, params: &Json) -> bool {
if !CLIPBOARD_READERS.contains(&id) {
return false;
}
let trim = |t: &str| t.trim_end_matches(['\r', '\n']).to_string();
match (id, str_param(params, "text")) {
("edit.paste", Some(text)) => s.clipboard.as_ref().is_some_and(|c| trim(&c.text) == trim(text)),
_ => true,
}
}
fn d_uid(s: &Session) -> Result<u64> {
Ok(s.doc()?.uid)
}
/// Runs a stored script. Scripts in a workbook opened from a file run only once the workbook is
/// trusted for this session (`automate.trustScripts`, or `trusted: true` on this call); steps that
/// reach outside the workbook ([`denied_script_step`]) are refused before any step runs.
@@ -108,6 +128,7 @@ pub(super) fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
}
}
let _sandbox = crate::io::ScriptSandbox::enter();
let home = d_uid(s)?;
let mut n = 0;
// What ran, for a recorder in progress: the recording keeps these steps with the run, so
// editing or deleting the script before the recording stops does not change what it saved.
@@ -117,9 +138,25 @@ pub(super) fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
if id.starts_with("automate.") {
continue;
}
if reads_clipboard(s, id, &st["params"]) && s.clipboard.as_ref().is_some_and(|c| c.doc_uid != home) {
return Err(bad("automate.runScript", format!("scripts can't run `{id}` on cells copied from another workbook")));
}
let before = s.ui_requests.len();
let wb_before = s.doc().ok().map(|d| (d.uid, d.wb.clone()));
let ran = s.execute(id, st["params"].clone());
// A stored step is not the person: an `approve` it carries is not consent to run a macro.
let mut params = st["params"].clone();
if let Some(o) = params.as_object_mut() {
o.remove("approve");
}
let ran = s.execute(id, params);
// A step (a nested macro, an alias of a window command) that switched windows would point the
// rest of the script at another workbook: put the script's own back and stop.
if s.doc().map(|d| d.uid).ok() != Some(home) {
if let Some(i) = s.docs.iter().position(|d| d.uid == home) {
s.set_active(i);
}
return Err(bad("automate.runScript", format!("`{id}` switched to another workbook; scripts stay in their own")));
}
// A step that asks the host to open a URL leaves the app: drop the request and stop.
if s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::OpenUrl(_)))) {
let mut i = 0;
+37 -1
View File
@@ -1057,7 +1057,7 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
// values change as soon as it is switched on or off.
let precision_changed = c.precision_as_displayed != before.precision_as_displayed;
if mode == Some(CalcMode::Automatic) || (iteration_changed && c.mode != CalcMode::Manual) || precision_changed {
cx.structural = true;
cx.recalc_all = true;
}
Ok(json!({
"mode": format!("{:?}", c.mode),
@@ -1073,6 +1073,42 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
mod tests {
use super::*;
#[test]
fn calculation_options_preserve_numeric_table_headers() {
for (mode, precision, params) in [
(CalcMode::Automatic, false, json!({"mode": "automatic"})),
(CalcMode::Manual, false, json!({"mode": "automatic"})),
(CalcMode::Automatic, false, json!({"iterative": true})),
(CalcMode::Manual, false, json!({"precisionAsDisplayed": true})),
(CalcMode::Manual, true, json!({"precisionAsDisplayed": false})),
] {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["Price", "Qty"], [7, 1]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:B2", "header": true})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "=SUM(Table1[Price])"})).unwrap();
let header = CellRef::new(0, 0);
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
wb.calc.mode = mode;
wb.calc.precision_as_displayed = precision;
let sheet = wb.sheet_mut(0).unwrap();
// A workbook can import a numeric cell with a different table column name.
sheet.set_value(header, Value::Number(123.0));
sheet.set_value(CellRef::new(1, 0), Value::Number(9.0));
assert_eq!(sheet.value(CellRef::new(0, 3)), Value::Number(7.0));
s.execute("formulas.calculationOptions", params.clone()).unwrap();
let sheet = s.doc().unwrap().wb.sheet(0).unwrap();
assert_eq!(sheet.value(header), Value::Number(123.0), "{params}");
assert_eq!(sheet.tables[0].columns[0].name, "Price", "{params}");
let result = s.execute("cell.get", json!({"cell": "D1"})).unwrap();
assert_eq!(result["formula"], "=SUM(Table1[Price])", "{params}");
assert_eq!(result["value"], json!(9.0), "{params}");
}
}
#[test]
fn names_with_relative_references() {
let mut s = Session::new();
+28
View File
@@ -7909,6 +7909,34 @@ fn clearing_links_and_notes_keeps_allow_edit_ranges() {
assert!(sh.hyperlinks.is_empty() && sh.comments.is_empty());
}
#[test]
fn an_edit_range_grant_does_not_outlive_its_sheet_name() {
let mut s = s();
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Kept", "range": "C5", "password": "example"})).unwrap();
s.execute("review.protectSheet", json!({})).unwrap();
s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Kept", "password": "example"})).unwrap();
assert!(!s.doc().unwrap().unlocked_ranges.is_empty());
// The sheet is renamed and another takes its name, with a range of the same title and password.
s.execute("review.unprotectSheet", json!({})).unwrap();
let old = s.doc().unwrap().wb.active().unwrap().name.clone();
s.execute("sheet.rename", json!({"name": "Renamed"})).unwrap();
assert!(s.doc().unwrap().unlocked_ranges.is_empty(), "the grant went with the old name");
s.execute("home.insertSheet", json!({"name": old})).unwrap();
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Kept", "range": "C5", "password": "other"})).unwrap();
s.execute("review.protectSheet", json!({})).unwrap();
assert!(s.execute("cell.set", json!({"cell": "C5", "input": "1"})).is_err(), "the new sheet's range is locked");
}
#[test]
fn undo_drops_the_grant_of_a_range_it_removes() {
let mut s = s();
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Kept", "range": "C5", "password": "example"})).unwrap();
s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Kept", "password": "example"})).unwrap();
assert!(!s.doc().unwrap().unlocked_ranges.is_empty());
s.execute("edit.undo", json!({})).unwrap();
assert!(s.doc().unwrap().unlocked_ranges.is_empty(), "the range is gone, so is its grant");
}
#[test]
fn replace_does_not_search_hidden_formula_source() {
let mut s = s();
+37
View File
@@ -2514,3 +2514,40 @@ fn a_step_that_deletes_a_form_control_after_a_partial_footprint_is_caught() {
s.execute("macro.run", json!({"name": "Drop", "inputs": "A1", "overwrite": true})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().controls.is_empty());
}
#[test]
fn a_script_cannot_paste_what_another_workbook_copied() {
let mut s = s();
let steps = json!([{"command": "edit.paste", "params": {"at": "B2"}}]);
s.execute("automate.newScript", json!({"name": "Paste", "commands": steps})).unwrap();
// A copy made in this workbook may be pasted by its script.
s.execute("cell.set", json!({"cell": "A1", "input": "mine"})).unwrap();
s.execute("edit.copy", json!({"range": "A1"})).unwrap();
s.execute("automate.runScript", json!({"name": "Paste"})).unwrap();
// A copy from another workbook is not read.
s.execute("file.new", json!({})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "secret"})).unwrap();
s.execute("edit.copy", json!({"range": "A1"})).unwrap();
s.set_active(0);
let err = s.execute("automate.runScript", json!({"name": "Paste"})).unwrap_err().to_string();
assert!(err.contains("another workbook"), "{err}");
// Explicit text that is not the clipboard's does not read it.
let own = json!([{"command": "edit.paste", "params": {"at": "C3", "text": "typed"}}]);
s.execute("automate.newScript", json!({"name": "Typed", "commands": own})).unwrap();
s.execute("automate.runScript", json!({"name": "Typed"})).unwrap();
}
#[test]
fn a_script_step_cannot_approve_a_macro_for_the_person() {
let mut s = s();
let mut wb = gridcraft_model::Workbook::new();
wb.macros.push(crate::macros::parse_macro(&json!({"name": "Theirs", "output": {"onConflict": "overwrite"}, "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": "ran"}}]})).unwrap());
let bytes = serde_json::to_vec(&wb).unwrap();
s.execute("file.open", json!({"name": "theirs.json", "base64": crate::io::base64_encode(&bytes)})).unwrap();
let steps = json!([{"command": "macro.run", "params": {"name": "Theirs", "approve": true}}]);
s.execute("automate.newScript", json!({"name": "Run", "commands": steps})).unwrap();
let r = s.execute("automate.runScript", json!({"name": "Run", "trusted": true}));
assert!(matches!(r, Err(EngineError::Approve(_))), "{r:?}");
assert!(s.macro_approvals.is_empty(), "the step's flag approved nothing");
assert!(v(&s, "A1").is_empty());
}
-1
View File
@@ -16,7 +16,6 @@ craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-print = { workspace = true }
craft-quit = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
gridcraft-engine = { workspace = true }
+2 -24
View File
@@ -105,7 +105,6 @@ impl SheetApp {
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
unsaved_prompt: None,
framework_host: crate::framework::host(),
}
}
@@ -127,9 +126,6 @@ impl SheetApp {
/// Per-frame logic (control channel, screenshots). Call before `ui`.
pub fn logic(&mut self, ctx: &egui::Context) {
// A completed answer wins over a concurrent forced close; otherwise retire an orphan.
self.take_unsaved_changes_dialog(ctx);
self.retire_closed_unsaved_prompt(ctx);
self.ensure_text_width(ctx);
// A keytip control request lives one frame: the ribbon consumes it during `ui`, and
// anything that never reached a control (collapsed ribbon, tab switch) is dropped. One
@@ -223,9 +219,6 @@ impl SheetApp {
let t0 = now_ms();
// A script may have switched windows since the last frame.
self.follow_active_window();
// The window this pass draws: a command run in it may switch to another window, which draws
// in its own pass.
let drawn = self.ui_window();
// This window's key tip request that waited for this frame (its tab or ribbon was just
// shown); any other window's request was dropped before it.
self.ui.keytip_invoke = self.ui.keytip_invoke_next.take();
@@ -288,13 +281,10 @@ impl SheetApp {
widgets::toast(self, &ctx);
// Last, so its resize cursors win over the widgets under the window edges.
ribbon::window_frame(self, &ctx);
// The update flow runs once per frame, in the root window; the framework dialogs too, unless
// the unsaved-changes question asks about a workbook in another window: they show there.
#[cfg(not(target_arch = "wasm32"))]
// The update flow and the framework dialogs run once per frame, in the root window.
if ctx.viewport_id() == egui::ViewportId::ROOT {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
}
if self.framework_dialogs_here(&ctx, drawn) {
self.run_framework_dialogs(ui);
}
self.flush_viewport_commands(&ctx);
@@ -326,18 +316,6 @@ impl SheetApp {
}
}
/// Whether a modal question is up and owns the keyboard: a GridCraft dialog or the shared
/// unsaved-changes question.
pub fn modal_open(&self) -> bool {
self.dialog.is_some() || self.unsaved_prompt.is_some()
}
/// The name of the open dialog, for automation: a GridCraft dialog's, or `saveChanges` while
/// the shared unsaved-changes question is up.
pub fn open_dialog_name(&self) -> Option<&str> {
self.dialog.as_ref().map(|d| d.name()).or_else(|| self.unsaved_prompt.as_ref().map(|_| "saveChanges"))
}
/// Current selection's top-left cell text as A1 (for the Name Box).
pub fn name_box_text(&self) -> String {
let Some(d) = self.session.active() else { return String::new() };
+1 -2
View File
@@ -336,7 +336,7 @@ impl SheetApp {
"ui.dialog" => {
let name = p.get("name").and_then(Json::as_str).unwrap_or("");
self.open_dialog(name, p.clone());
Ok(json!({"dialog": self.open_dialog_name()}))
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
}
"ui.selectionMode" => {
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
@@ -482,7 +482,6 @@ impl SheetApp {
}
// The notice AutoSave holds back with: Save asks what the notice says.
"saveLoss" => self.run_or_alert("file.save", json!({})),
"saveChanges" => self.open_unsaved_changes(&params),
// File › Options (`file.options`) and the File tab itself open the Backstage view.
"options" => self.open_backstage(backstage::Page::Options),
"backstage" => {
+1 -1
View File
@@ -4,7 +4,7 @@ impl SheetApp {
pub(super) fn ribbon_keys(&mut self, ctx: &egui::Context) {
let before = self.keytips.prefix().map(str::to_string);
let enabled = self.editor.is_none()
&& !self.modal_open()
&& self.dialog.is_none()
&& self.message.is_none()
&& self.name_box.is_none()
&& !ctx.text_edit_focused()
+7 -103
View File
@@ -1,10 +1,7 @@
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::{DialogResult, UnsavedAnswer, UnsavedChangesDialog};
use craft_ui::shell::embed::CloseDecision;
use gridcraft_engine::cmd::file::{SaveLosses, save_losses, xlsx_save_losses};
use super::{AfterSave, Json, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetApp, json};
use crate::state::UnsavedPrompt;
impl SheetApp {
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
@@ -34,11 +31,12 @@ impl SheetApp {
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
}
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
match self.dialog.as_mut() {
// Already asking about a workbook (File › Close): answering it now goes on to quit.
self.promote_unsaved_to_quit();
} else {
self.continue_quit(ctx);
Some(d) if d.name() == "saveChanges" => {
d.values.insert("quit".into(), json!(true));
}
_ => self.continue_quit(ctx),
}
CloseDecision::Hold
}
@@ -235,107 +233,13 @@ impl SheetApp {
crate::macro_editor::request_close(self, true);
return;
}
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
// Already asking about a workbook (File › Close): answering it goes on to quit.
self.promote_unsaved_to_quit();
d.values.insert("quit".into(), json!(true));
return;
}
self.continue_quit(ctx);
}
/// Opens the shared unsaved-changes dialog on `framework_dialogs` for the active workbook.
pub(crate) fn open_unsaved_changes(&mut self, params: &Json) {
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
self.message = Some((
"Macro".into(),
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
));
return;
}
if let Some(mut old) = self.dialog.take() {
let _ = old.end_pick(self);
}
let Some(doc) = self.session.active().map(|d| d.uid) else { return };
let title = params
.get("title")
.and_then(Json::as_str)
.map(str::to_owned)
.or_else(|| self.session.active().map(|d| d.display_title()))
.unwrap_or_else(|| "this workbook".into());
let quitting = params.get("quit").and_then(Json::as_bool) == Some(true);
let scope = if quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(UnsavedPrompt { doc, window: self.ui_window(), quitting });
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
// A replaced question leaves a Cancel result; it is not the new question's answer.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
fn promote_unsaved_to_quit(&mut self) {
if let Some(prompt) = self.unsaved_prompt.as_mut()
&& !prompt.quitting
{
prompt.quitting = true;
let title =
self.session.documents().iter().find(|d| d.uid == prompt.doc).map(|d| d.display_title()).unwrap_or_else(|| "this workbook".into());
self.framework_dialogs.open(UnsavedChangesDialog::new(CloseScope::Quit, title).document_wording(true));
// The question it replaced left a Cancel as its result; it was not answered, and the
// quit's question asks on.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
}
/// A forced close can remove the workbook and its window while the question is open. Retire
/// that question and continue a pending quit without applying its answer to another workbook.
pub(crate) fn retire_closed_unsaved_prompt(&mut self, ctx: &egui::Context) {
let Some(prompt) = self.unsaved_prompt.as_ref() else { return };
if self.session.documents().iter().any(|doc| doc.uid == prompt.doc) {
return;
}
let quitting = prompt.quitting;
self.unsaved_prompt = None;
self.framework_dialogs.cancel::<UnsavedChangesDialog>(ctx);
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
if quitting {
self.continue_quit(ctx);
}
}
/// Reads the answer from an open [`UnsavedChangesDialog`] and continues closing or quitting.
pub(crate) fn take_unsaved_changes_dialog(&mut self, ctx: &egui::Context) {
let Some(result) = self.framework_dialogs.take::<UnsavedChangesDialog>() else {
return;
};
let Some(prompt) = self.unsaved_prompt.take() else {
return;
};
let answer = match result {
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::DontSave, .. }) => SaveAnswer::DontSave,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Save, .. }) => SaveAnswer::Save,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Cancel, .. }) | DialogResult::Cancel | _ => SaveAnswer::Cancel,
};
if answer == SaveAnswer::Cancel {
return;
}
if let Some(w) = prompt.window.filter(|w| self.session.window(*w).is_some())
&& self.ui_window() != Some(w)
{
self.enter_window(w);
}
if self.session.active().map(|d| d.uid) != Some(prompt.doc) {
// A completed answer for a workbook closed in the same frame cannot apply to the
// replacement workbook; a pending quit still needs to ask about what remains.
if prompt.quitting && !self.session.documents().iter().any(|doc| doc.uid == prompt.doc) {
self.continue_quit(ctx);
}
return;
}
if !self.answer_save_changes(answer, prompt.quitting, ctx) {
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
let scope = if prompt.quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(prompt);
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
}
}
}
#[cfg(test)]
+1 -1
View File
@@ -258,7 +258,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
});
});
bs.text_edit_focused = ctx.text_edit_focused();
if !typing && !app.modal_open() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
out.close = true;
}
if let Some(page) = out.page {
+2 -3
View File
@@ -147,8 +147,7 @@ pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
"grid": app.grid.cells_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
"scroll": [v.scroll.x, v.scroll.y],
"editor": app.editor.as_ref().map(|e| editor_json(app, e)),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab}))
.or_else(|| app.unsaved_prompt.as_ref().map(|p| json!({"name": "saveChanges", "values": {"quit": p.quitting}}))),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab})),
"backstage": app.backstage.as_ref().map(|b| b.page.id()),
"message": app.message.as_ref().map(|(t, m)| json!({"title": t, "text": m})),
"selectedObject": app.selected_object,
@@ -345,7 +344,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
}
"ui.dialog" => {
app.open_dialog(s("name").unwrap_or(""), p.clone());
ok(json!({"dialog": app.open_dialog_name()}))
ok(json!({"dialog": app.dialog.as_ref().map(|d| d.name.clone())}))
}
"ui.dialog.set" => match app.dialog.as_mut() {
Some(d) => {
+1
View File
@@ -1166,6 +1166,7 @@ impl Dialog {
"formatControl" => return crate::control_ui::open_format(app, &params),
"controlQuestion" => return crate::control_ui::open_question(&params),
"saveCopy" => Dialog::custom("saveCopy", "Save a Copy", json!({"format": p("format")})),
"saveChanges" => Dialog::custom("saveChanges", "Save Changes?", json!({"title": p("title"), "quit": p("quit")})),
"start" => Dialog::custom("start", "GridCraft", json!({})),
"comments" => {
app.grid.pane = None;
+13
View File
@@ -374,6 +374,19 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
}
}
}
"saveChanges" => {
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
ui.horizontal(|ui| {
for (label, answer) in
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
{
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
open = false;
}
}
});
}
"saveLoss" => {
let lang = app.ui.language;
let pending = d.pending_save();
+3 -3
View File
@@ -529,7 +529,7 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font:
let chars_before = ed.text.chars().count();
// A dialog opened over the edit (Paste Name) takes the keyboard until it closes, and the
// editor takes it back afterwards.
let dialog_open = app.modal_open();
let dialog_open = app.dialog.is_some();
if dialog_open && mine {
ed.request_focus = true;
ed.keep_selection = true;
@@ -671,7 +671,7 @@ fn editor_shortcuts(
) -> EditorKeyOutcome {
let mut outcome = EditorKeyOutcome { action: None, arrow: false, cancel: false, to_python: false };
// A message or dialog owns Enter and Escape until it closes.
if !has_focus || !mine || app.message.is_some() || app.modal_open() {
if !has_focus || !mine || app.message.is_some() || app.dialog.is_some() {
return outcome;
}
// Ctrl+Alt+Shift+P turns the edit into Python code.
@@ -864,7 +864,7 @@ fn python_editor(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, width: f32
let Some(mut ed) = app.editor.take() else { return EditorInfo::default() };
// A message box (the code was refused) or a dialog over the edit has the keyboard; the
// editor takes it back when it closes.
let blocked = app.message.is_some() || app.modal_open();
let blocked = app.message.is_some() || app.dialog.is_some();
let mut caret = None;
if blocked {
ed.request_focus = true;
-13
View File
@@ -112,22 +112,9 @@ impl SheetApp {
embed::logic(ctx, || self.close_decision(ctx));
}
/// Whether this pass draws [`SheetApp::framework_dialogs`]: the pass of the window the unsaved-changes
/// question asks about (the window that keeps it, as a GridCraft dialog stays in its window), else the root's.
/// `drawn` is the window the pass began drawing: a question a command in it opened for another window (a quit
/// moving on to the next unsaved workbook) shows in that window's own pass, not for a frame in this one.
pub(crate) fn framework_dialogs_here(&self, ctx: &egui::Context, drawn: Option<u64>) -> bool {
let shown = |w: &u64| self.session.window(*w).is_some_and(|w| !w.hidden);
match self.unsaved_prompt.as_ref().and_then(|p| p.window).filter(shown) {
Some(w) => drawn == Some(w),
None => ctx.viewport_id() == egui::ViewportId::ROOT,
}
}
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
self.take_unsaved_changes_dialog(ui.ctx());
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
// arrow key would move the selection the menu fills from), and a macro's question.
editing
|| app.modal_open()
|| app.dialog.is_some()
|| other_focus
|| app.message.is_some()
|| app.grid.filter_menu.is_some()
+2 -2
View File
@@ -328,7 +328,7 @@ pub(super) fn fill_options_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo,
app.grid.fill_tag = None;
return;
}
if app.editor.is_some() || app.modal_open() || app.grid.drag != Drag::None {
if app.editor.is_some() || app.dialog.is_some() || app.grid.drag != Drag::None {
return;
}
let size = vec2(18.0, 18.0);
@@ -471,7 +471,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
/// The warning button beside an active cell holding a number stored as text, as in Excel: its
/// menu names the problem and offers Convert to Number for the selection (#1994).
pub(super) fn error_check_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) {
if app.editor.is_some() || app.modal_open() || sh.show_formulas || app.grid.drag != Drag::None {
if app.editor.is_some() || app.dialog.is_some() || sh.show_formulas || app.grid.drag != Drag::None {
return;
}
let Some(active) = app.session.active().map(|d| d.selection.active) else { return };
+3
View File
@@ -574,6 +574,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Zoom Out" => "Σμίκρυνση",
"Dismiss" => "Κλείσιμο",
"OK" => "Εντάξει",
"Don't Save" => "Χωρίς αποθήκευση",
"Open…" => "Άνοιγμα…",
"Show password" => "Εμφάνιση κωδικού πρόσβασης",
"Start a new workbook" => "Δημιουργία νέου βιβλίου εργασίας",
@@ -582,6 +583,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Βαθμολόγιο",
"this workbook" => "αυτό το βιβλίο εργασίας",
"This workbook" => "Αυτό το βιβλίο εργασίας",
"Do you want to save the changes you made to {title}?" => "Θέλετε να αποθηκεύσετε τις αλλαγές που κάνατε στο {title};",
"Save a copy as .{format}" => "Αποθήκευση αντιγράφου ως .{format}",
"Select a chart first." => "Επιλέξτε πρώτα ένα γράφημα.",
"Row Height" => "Ύψος γραμμής",
@@ -622,6 +624,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Τοποθέτηση εικόνας πάνω από κελιά",
"Pick From List" => "Επιλογή από λίστα",
"Save a Copy" => "Αποθήκευση αντιγράφου",
"Save Changes?" => "Αποθήκευση αλλαγών;",
"Shift cells right" => "Μετατόπιση κελιών προς τα δεξιά",
"Shift cells down" => "Μετατόπιση κελιών προς τα κάτω",
"Shift cells left" => "Μετατόπιση κελιών προς τα αριστερά",
+3
View File
@@ -445,6 +445,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Le impostazioni di calcolo vengono salvate con la cartella di lavoro.",
"OK" => "OK",
"Cancel" => "Annulla",
"Don't Save" => "Non salvare",
"Open…" => "Apri…",
"Show password" => "Mostra password",
"Start a new workbook" => "Crea una nuova cartella di lavoro",
@@ -453,6 +454,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Registro dei voti",
"this workbook" => "questa cartella di lavoro",
"This workbook" => "Questa cartella di lavoro",
"Do you want to save the changes you made to {title}?" => "Vuoi salvare le modifiche apportate a {title}?",
"Save a copy as .{format}" => "Salva una copia come .{format}",
"Select a chart first." => "Seleziona prima un grafico.",
"Text Box" => "Casella di testo",
@@ -503,6 +505,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Inserisci immagine sopra le celle",
"Pick From List" => "Scegli dall'elenco",
"Save a Copy" => "Salva una copia",
"Save Changes?" => "Salvare le modifiche?",
"Shift cells right" => "Sposta celle a destra",
"Shift cells down" => "Sposta celle in basso",
"Shift cells left" => "Sposta celle a sinistra",
+3
View File
@@ -462,6 +462,7 @@ pub(super) const CORE: &[(&str, &str)] = &[
pub(super) const DIALOGS: &[(&str, &str)] = &[
("OK", "OK"),
("Cancel", "キャンセル"),
("Don't Save", "保存しない"),
("Open…", "開く…"),
("Show password", "パスワードの表示"),
("Start a new workbook", "新しいブックの作成"),
@@ -470,6 +471,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Gradebook", "成績表"),
("this workbook", "このブック"),
("This workbook", "このブック"),
("Do you want to save the changes you made to {title}?", "{title} への変更を保存しますか?"),
("Save a copy as .{format}", ".{format} としてコピーを保存"),
("Select a chart first.", "先にグラフを選択してください。"),
("Text Box", "テキスト ボックス"),
@@ -520,6 +522,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Place Picture over Cells", "セルの上に画像を配置"),
("Pick From List", "リストから選択"),
("Save a Copy", "コピーを保存"),
("Save Changes?", "変更を保存しますか?"),
("Shift cells right", "セルを右に移動"),
("Shift cells down", "セルを下に移動"),
("Shift cells left", "セルを左に移動"),
+3
View File
@@ -436,6 +436,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Ustawienia obliczeń są zapisywane razem ze skoroszytem.",
"OK" => "OK",
"Cancel" => "Anuluj",
"Don't Save" => "Nie zapisuj",
"Open…" => "Otwórz…",
"Show password" => "Pokaż hasło",
"Start a new workbook" => "Utwórz nowy skoroszyt",
@@ -444,6 +445,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Dziennik ocen",
"this workbook" => "ten skoroszyt",
"This workbook" => "Ten skoroszyt",
"Do you want to save the changes you made to {title}?" => "Czy chcesz zapisać zmiany wprowadzone w pliku {title}?",
"Save a copy as .{format}" => "Zapisz kopię jako .{format}",
"Select a chart first." => "Najpierw zaznacz wykres.",
"Text Box" => "Pole tekstowe",
@@ -494,6 +496,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Umieść obraz na komórkach",
"Pick From List" => "Wybierz z listy",
"Save a Copy" => "Zapisz kopię",
"Save Changes?" => "Zapisać zmiany?",
"Shift cells right" => "Przesuń komórki w prawo",
"Shift cells down" => "Przesuń komórki w dół",
"Shift cells left" => "Przesuń komórki w lewo",
+3
View File
@@ -464,6 +464,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.",
"OK" => "OK",
"Cancel" => "Cancelar",
"Don't Save" => "Não Salvar",
"Open…" => "Abrir…",
"Show password" => "Mostrar senha",
"Start a new workbook" => "Criar uma pasta de trabalho",
@@ -472,6 +473,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Boletim de Notas",
"this workbook" => "esta pasta de trabalho",
"This workbook" => "Esta pasta de trabalho",
"Do you want to save the changes you made to {title}?" => "Deseja salvar as alterações feitas em {title}?",
"Save a copy as .{format}" => "Salvar uma cópia como .{format}",
"Select a chart first." => "Selecione um gráfico primeiro.",
"Text Box" => "Caixa de Texto",
@@ -528,6 +530,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Colocar Imagem sobre as Células",
"Pick From List" => "Escolher na Lista",
"Save a Copy" => "Salvar uma Cópia",
"Save Changes?" => "Salvar Alterações?",
"Shift cells right" => "Deslocar células para a direita",
"Shift cells down" => "Deslocar células para baixo",
"Shift cells left" => "Deslocar células para a esquerda",
+3
View File
@@ -442,6 +442,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Setările de calcul se salvează împreună cu registrul.",
"OK" => "OK",
"Cancel" => "Anulare",
"Don't Save" => "Nu salva",
"Open…" => "Deschidere…",
"Show password" => "Afișare parolă",
"Start a new workbook" => "Începeți un registru nou",
@@ -450,6 +451,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Catalog de note",
"this workbook" => "acest registru",
"This workbook" => "Acest registru",
"Do you want to save the changes you made to {title}?" => "Doriți să salvați modificările făcute în {title}?",
"Save a copy as .{format}" => "Salvare copie ca .{format}",
"Select a chart first." => "Selectați mai întâi o diagramă.",
"Text Box" => "Casetă de text",
@@ -500,6 +502,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Plasare imagine peste celule",
"Pick From List" => "Alegere din listă",
"Save a Copy" => "Salvare copie",
"Save Changes?" => "Salvați modificările?",
"Shift cells right" => "Deplasare celule la dreapta",
"Shift cells down" => "Deplasare celule în jos",
"Shift cells left" => "Deplasare celule la stânga",
+3
View File
@@ -599,6 +599,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Display:" => "Отображать:",
"Distributed" => "Распределённый",
"Divide" => "Разделить",
"Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?",
"Don't Save" => "Не сохранять",
"Double" => "Двойное",
"Double Accounting" => "Двойное бухгалтерское",
"Doughnut" => "Кольцевая",
@@ -844,6 +846,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Rows" => "Строки",
"Sample" => "Выборка",
"Save (⌘S)" => "Сохранить (⌘S)",
"Save Changes?" => "Сохранить изменения?",
"Save a Copy" => "Сохранить копию",
"Save a copy as .{format}" => "Сохранить копию как .{format}",
"Scatter" => "Точечная",
+3
View File
@@ -440,6 +440,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Параметри обчислень зберігаються разом із книгою.",
"OK" => "OK",
"Cancel" => "Cancel",
"Don't Save" => "Don't Save",
"Open…" => "Open…",
"Show password" => "Show password",
"Start a new workbook" => "Start a new workbook",
@@ -448,6 +449,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Gradebook",
"this workbook" => "this workbook",
"This workbook" => "This workbook",
"Do you want to save the changes you made to {title}?" => "Do you want to save the changes you made to {title}?",
"Save a copy as .{format}" => "Save a copy as .{format}",
"Select a chart first." => "Спочатку виділіть діаграму.",
"Text Box" => "Напис",
@@ -498,6 +500,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Place Picture over Cells",
"Pick From List" => "Pick From List",
"Save a Copy" => "Save a Copy",
"Save Changes?" => "Save Changes?",
"Shift cells right" => "Shift cells right",
"Shift cells down" => "Shift cells down",
"Shift cells left" => "Shift cells left",
+3
View File
@@ -450,6 +450,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
// Dialogs, menus, context menus and tooltips.
"OK" => "OK",
"Cancel" => "Hủy",
"Don't Save" => "Không lưu",
"Open…" => "Mở…",
"Show password" => "Hiện mật khẩu",
"Start a new workbook" => "Bắt đầu sổ làm việc mới",
@@ -458,6 +459,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Sổ điểm",
"this workbook" => "sổ làm việc này",
"This workbook" => "Sổ làm việc này",
"Do you want to save the changes you made to {title}?" => "Bạn có muốn lưu các thay đổi đã thực hiện cho {title} không?",
"Save a copy as .{format}" => "Lưu bản sao dưới dạng .{format}",
"Select a chart first." => "Hãy chọn một biểu đồ trước.",
"Text Box" => "Hộp văn bản",
@@ -508,6 +510,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Đặt ảnh đè lên các ô",
"Pick From List" => "Chọn từ danh sách",
"Save a Copy" => "Lưu bản sao",
"Save Changes?" => "Lưu thay đổi?",
"Shift cells right" => "Dịch các ô sang phải",
"Shift cells down" => "Dịch các ô xuống dưới",
"Shift cells left" => "Dịch các ô sang trái",
+2 -4
View File
@@ -396,11 +396,9 @@ pub struct SheetApp {
/// The update check, the startup prompt and a running self-update (desktop only).
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime,
/// The framework dialogs GridCraft keeps as values (the update dialogs and the unsaved-changes
/// prompt), run once per frame after GridCraft's own UI in the root window's pass.
/// The framework dialogs GridCraft keeps as values (the update dialogs), run once per frame
/// after GridCraft's own UI in the root window's pass.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Which workbook and window the open `UnsavedChangesDialog` is asking about.
pub unsaved_prompt: Option<state::UnsavedPrompt>,
/// Who GridCraft is to the framework's dialogs.
framework_host: std::sync::Arc<craft_host::Host>,
}
+21 -18
View File
@@ -18,8 +18,6 @@
use std::collections::BTreeMap;
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::UnsavedChangesDialog;
use egui::{Color32, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use gridcraft_engine::core::RangeRef;
use gridcraft_engine::macros::policy::{Policy, macro_policy};
@@ -1102,7 +1100,7 @@ fn ref_edit(app: &SheetApp, ui: &mut Ui, d: &mut Dialog, refs: &mut RefPick, key
d.values.insert(key.into(), json!(s));
}
/// Keep changes? (stopping a debugged run) and the unsaved-changes question (closing with unsaved edits).
/// Keep changes? (stopping a debugged run) and Save changes? (closing with unsaved edits).
fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut bool) {
if ed.ask_stop {
let mut answer: Option<Option<bool>> = None;
@@ -1143,20 +1141,25 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
return;
}
if ed.ask_close {
// The shared unsaved-changes question, named for the macro. Each asking gets its own area,
// so the question's own open state starts open every time it is asked.
let scope = if ed.quit { CloseScope::Quit } else { CloseScope::Close };
let asked = Id::unique("gridcraft.macro_editor.close");
let opening = ctx.data(|d| d.get_temp::<u64>(asked)).unwrap_or_default();
let shown = egui::Area::new(asked.with(opening))
.order(egui::Order::Foreground)
.show(ctx, |ui| UnsavedChangesDialog::new(scope, ed.draft.name.clone()).document_wording(true).show(ui));
let answer = shown.inner.answer.map(|a| a.answer);
if answer.is_some() {
ctx.data_mut(|d| d.insert_temp(asked, opening + 1));
}
let mut answer: Option<Option<bool>> = None;
egui::Modal::new(Id::unique("gridcraft.macro_editor.close")).show(ctx, |ui| {
ui.set_width(360.0);
ui.label(egui::RichText::new(format!("Save changes to macro “{}”?", ed.draft.name)).strong());
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
answer = Some(None);
}
if ui.button("Don't Save").clicked() {
answer = Some(Some(false));
}
if ui.button("Save").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
answer = Some(Some(true));
}
});
});
match answer {
Some(CloseAnswer::Save) => {
Some(Some(true)) => {
ed.ask_close = false;
if save(app, ed) {
*open = false;
@@ -1167,11 +1170,11 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
ed.quit = false;
}
}
Some(CloseAnswer::DontSave) => {
Some(Some(false)) => {
ed.ask_close = false;
*open = false;
}
Some(CloseAnswer::Cancel) => {
Some(None) => {
ed.ask_close = false;
ed.quit = false;
ed.then_close = None;
+1 -1
View File
@@ -167,7 +167,7 @@ pub fn is_hidden(app: &SheetApp, geo: &Geo, sh: &Sheet) -> bool {
d.selection.ranges.len() > 1
|| d.selection.current().is_single()
|| app.editor.is_some()
|| app.modal_open()
|| app.dialog.is_some()
|| app.text_box_editor.is_some()
|| app.grid.context_menu.is_some()
|| geo.paper.is_some()
-9
View File
@@ -19,15 +19,6 @@ pub enum SaveAnswer {
Cancel,
}
/// Which workbook and window an open [`craft_ui::dialog::UnsavedChangesDialog`] is asking about,
/// and whether answering it goes on to quit.
#[derive(Clone, Debug)]
pub struct UnsavedPrompt {
pub doc: u64,
pub window: Option<u64>,
pub quitting: bool,
}
/// How a save held back for an answer goes on.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum SaveRequest {
+26 -86
View File
@@ -7,7 +7,6 @@
use std::cell::RefCell;
use craft_ui::dialog::UnsavedChangesDialog;
use egui::{Context, RawInput, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
use gridcraft_engine::{Session, core::CellRef, core::Value};
use gridcraft_ui_egui::doc_windows::DocWindows;
@@ -19,8 +18,8 @@ thread_local! {
static INFOS: RefCell<egui::ViewportIdMap<ViewportInfo>> = RefCell::new(egui::ViewportIdMap::default());
/// The viewport commands the app sent this frame.
static SENT: RefCell<Vec<(ViewportId, ViewportCommand)>> = const { RefCell::new(Vec::new()) };
/// Each viewport's input events for its next pass (a key pressed in that window).
static EVENTS: RefCell<egui::ViewportIdMap<Vec<egui::Event>>> = RefCell::new(egui::ViewportIdMap::default());
/// Input events for the root window's next frame (a key pressed in it).
static EVENTS: RefCell<Vec<egui::Event>> = const { RefCell::new(Vec::new()) };
}
fn record(mut out: egui::FullOutput) {
@@ -33,17 +32,6 @@ fn record(mut out: egui::FullOutput) {
});
}
/// The events waiting for viewport `id`'s next pass.
fn take_events(id: ViewportId) -> Vec<egui::Event> {
EVENTS.with(|e| e.borrow_mut().remove(&id).unwrap_or_default())
}
/// Presses `key` with `modifiers` in viewport `id`'s next pass.
fn press(id: ViewportId, key: egui::Key, modifiers: egui::Modifiers) {
let event = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
EVENTS.with(|e| e.borrow_mut().entry(id).or_default().push(event));
}
struct Desk {
ctx: Context,
app: SheetApp,
@@ -61,7 +49,6 @@ impl Desk {
let mut input = RawInput { viewport_id: id, ..RawInput::default() };
input.viewports = INFOS.with(|i| i.borrow().clone());
input.viewports.entry(id).or_default().parent = Some(viewport.ids.parent);
input.events = take_events(id);
let mut cb = viewport.viewport_ui_cb;
record(ctx.run_ui(input, |ui| cb(ui)));
});
@@ -81,7 +68,7 @@ impl Desk {
let mut input = RawInput { viewport_id: ViewportId::ROOT, ..RawInput::default() };
input.viewports = INFOS.with(|i| i.borrow().clone());
input.viewports.entry(ViewportId::ROOT).or_default();
input.events = take_events(ViewportId::ROOT);
input.events = EVENTS.with(|e| std::mem::take(&mut *e.borrow_mut()));
let Desk { ctx, app, windows } = self;
let mut act = Some(act);
let out = ctx.clone().run_ui(input, |ui| {
@@ -94,15 +81,6 @@ impl Desk {
app.close_path(&ctx);
windows.show(app, ui);
});
// As eframe's, every pass's input lists each open window: the UI runtime keeps a window's state (the layers
// its dialogs showed, its focus) only while the root's input lists that window.
INFOS.with(|i| {
let mut i = i.borrow_mut();
i.retain(|id, _| out.viewport_output.contains_key(id));
for id in out.viewport_output.keys() {
i.entry(*id).or_default();
}
});
record(out);
// Close buttons are one-shot events.
INFOS.with(|i| i.borrow_mut().values_mut().for_each(|v| v.events.clear()));
@@ -126,24 +104,15 @@ impl Desk {
sent
}
/// Answers the Save Changes question with its key (Enter Save, Escape Cancel, Cmd+D Don't
/// Save), pressed in the window of the workbook it asks about: the question shows there.
/// The person reads the question first: the shared dialog takes its Cmd+D from the pass after
/// one in which it already showed on top, so a press in the frame right after it opened is
/// not an answer.
/// Answers the Save Changes question showing in the active window, as its button does.
fn answer(&mut self, answer: SaveAnswer) -> Vec<(ViewportId, ViewportCommand)> {
assert!(self.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "no question is showing");
let w = self.app.unsaved_prompt.as_ref().and_then(|p| p.window).expect("the question names its window");
let mut sent = self.frames(2);
assert!(self.app.unsaved_prompt.as_ref().is_some_and(|p| p.window == Some(w)), "the question in window {w} waits for its answer");
let (key, modifiers) = match answer {
SaveAnswer::Save => (egui::Key::Enter, egui::Modifiers::NONE),
SaveAnswer::Cancel => (egui::Key::Escape, egui::Modifiers::NONE),
SaveAnswer::DontSave => (egui::Key::D, egui::Modifiers::COMMAND),
};
press(self.viewport(w), key, modifiers);
sent.extend(self.frames(3));
assert!(self.app.unsaved_prompt.as_ref().is_none_or(|p| p.window != Some(w)), "the question in window {w} was answered");
let mut sent = self.frame_with(|app, ctx| {
let d = app.dialog.take().unwrap_or_else(|| panic!("no question is showing"));
assert_eq!(d.name(), "saveChanges");
let quitting = d.values.get("quit").and_then(serde_json::Value::as_bool) == Some(true);
app.answer_save_changes(answer, quitting, ctx);
});
sent.extend(self.frames(2));
sent
}
@@ -154,7 +123,9 @@ impl Desk {
/// The user presses `key` in the root window.
fn key(&mut self, key: egui::Key) -> Vec<(ViewportId, ViewportCommand)> {
press(ViewportId::ROOT, key, egui::Modifiers::NONE);
EVENTS.with(|e| {
e.borrow_mut().push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE })
});
let mut sent = self.frame_with(|_, _| {});
sent.extend(self.frames(2));
sent
@@ -231,7 +202,7 @@ fn closing_the_last_window_of_an_unsaved_workbook_asks_and_the_app_quits_after()
let w = desk.window_of(0);
let sent = desk.close(w);
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::CancelClose), "the window stays open to ask: {sent:?}");
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert_eq!(desk.app.session.documents().len(), 1);
let sent = desk.answer(SaveAnswer::Cancel);
@@ -273,41 +244,21 @@ fn quit_asks_about_each_unsaved_workbook_in_its_window_and_cancel_stops() {
let sent = desk.frame_with(|app, ctx| app.request_quit(ctx));
assert_eq!(desk.app.session.active_window(), Some(w1), "Book1's window comes forward to ask");
assert!(sent_to(&sent, desk.viewport(w1), &ViewportCommand::Focus), "{sent:?}");
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
let sent = desk.answer(SaveAnswer::Cancel);
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Cancel stops the quit: {sent:?}");
assert_eq!(desk.app.session.documents().len(), 2);
assert!(!desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
assert!(desk.app.dialog.is_none());
desk.frame_with(|app, ctx| app.request_quit(ctx));
let sent = desk.answer(SaveAnswer::DontSave);
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Book2 is still unsaved: {sent:?}");
assert_eq!(desk.app.session.active_window(), Some(w2), "then Book2's window asks");
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
let sent = desk.answer(SaveAnswer::DontSave);
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "both answered: the app quits: {sent:?}");
}
#[test]
fn quit_continues_when_automation_closes_the_prompted_workbook() {
let mut desk = Desk::new(true);
desk.app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
let first = desk.app.session.active().unwrap().uid;
desk.app.run("file.new", json!({})).unwrap();
desk.app.run("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
let second = desk.app.session.active().unwrap().uid;
desk.frames(3);
desk.frame_with(|app, ctx| app.request_quit(ctx));
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.doc == first && p.quitting));
desk.app.run("file.close", json!({"force": true, "document": true})).unwrap();
desk.frames(3);
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.doc == second && p.quitting), "quit asks the remaining workbook");
assert!(desk.app.session.active().is_some_and(|doc| doc.uid == second && doc.is_dirty()));
let sent = desk.answer(SaveAnswer::Cancel);
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Cancel still stops quit");
assert!(desk.app.session.active().is_some_and(|doc| doc.uid == second && doc.is_dirty()));
}
#[test]
fn a_quit_question_brings_its_window_to_the_front_from_the_background() {
// A Dock quit reaches the app while it is behind other apps, hidden or minimized.
@@ -317,7 +268,7 @@ fn a_quit_question_brings_its_window_to_the_front_from_the_background() {
let w = desk.window_of(0);
let sent = desk.frame_with(|app, ctx| app.request_quit(ctx));
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
for cmd in [ViewportCommand::Visible(true), ViewportCommand::Minimized(false), ViewportCommand::Focus] {
assert!(sent_to(&sent, desk.viewport(w), &cmd), "{cmd:?} missing: {sent:?}");
}
@@ -455,20 +406,6 @@ fn two_windows_on_one_workbook_show_their_own_sheet_and_each_others_edits() {
assert_eq!(d.wb.active().unwrap().value(CellRef::parse("B2").unwrap()), Value::Number(42.0));
}
#[test]
fn replacing_an_unsaved_question_keeps_the_new_answer() {
let mut desk = Desk::new(false);
desk.app.run("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
desk.frames(2);
desk.app.open_dialog("saveChanges", json!({}));
desk.frames(2);
desk.app.open_dialog("saveChanges", json!({}));
desk.frames(2);
assert!(desk.app.unsaved_prompt.is_some(), "the replaced question's cancel is not the new answer");
desk.answer(SaveAnswer::DontSave);
assert!(desk.app.session.documents().is_empty(), "the new answer closes the workbook");
}
#[test]
fn a_dialog_stays_with_its_window_across_a_switch() {
let mut desk = Desk::new(true);
@@ -580,8 +517,9 @@ fn quit_takes_over_a_workbook_close_waiting_on_the_macro_editor() {
assert!(desk.app.macros.editor.is_none());
// The quit asks about Book2 in its window, as the quit's question, not as a File › Close.
assert_eq!(desk.app.session.active_window(), Some(w2));
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "Book2 is asked about");
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
let d = desk.app.dialog.as_ref().expect("Book2 is asked about");
assert_eq!(d.name(), "saveChanges");
assert_eq!(d.values.get("quit"), Some(&json!(true)), "{:?}", d.values);
assert_eq!(desk.app.session.documents().len(), 2, "nothing closed before the answer");
}
@@ -613,8 +551,10 @@ fn quit_with_a_draft_in_one_window_and_unsaved_cells_in_another_asks_in_order_an
assert!(desk.app.macros.editor.is_none());
// Book2 is asked about next, in its window, as the quit's question.
assert_eq!(desk.app.session.active_window(), Some(w2), "the unsaved workbook's window comes forward");
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "Book2 is asked about");
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
let d = desk.app.dialog.as_ref().expect("Book2 is asked about");
assert_eq!(d.name(), "saveChanges");
assert_eq!(d.values.get("title").and_then(serde_json::Value::as_str), Some("Book2"));
assert_eq!(d.values.get("quit"), Some(&json!(true)), "{:?}", d.values);
assert_eq!(desk.app.session.documents().len(), 2, "nothing closed before the answer");
// Cancel: the quit stops with both windows and workbooks open; the discarded draft stays
// discarded.
+6 -63
View File
@@ -164,7 +164,7 @@ fn save_actions_include_the_cell_draft_and_close_keeps_the_unsaved_prompt() {
choose(&mut h, "Close");
assert!(h.state().backstage.is_none());
assert_eq!(h.state().session.documents().len(), 1);
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0));
}
@@ -376,80 +376,23 @@ fn closing_the_window_asks_about_every_unsaved_workbook() {
let sent = request_window_close(&mut h);
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "unsaved changes hold the window open: {sent:?}");
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
let sent = click_commands(&mut h, "Cancel");
assert!(!sent.contains(&egui::ViewportCommand::Close), "Cancel keeps the app open");
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert!(h.state().dialog.is_none());
assert_eq!(h.state().session.documents().len(), 2, "Cancel keeps both workbooks");
request_window_close(&mut h);
let sent = click_commands(&mut h, "Don't Save");
assert!(!sent.contains(&egui::ViewportCommand::Close), "the other workbook is still unsaved");
assert_eq!(h.state().session.documents().len(), 1);
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>(), "then it asks about the next one");
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"), "then it asks about the next one");
let sent = click_commands(&mut h, "Don't Save");
assert!(sent.contains(&egui::ViewportCommand::Close), "once every workbook is answered the window closes: {sent:?}");
let sent = request_window_close(&mut h);
assert!(!sent.contains(&egui::ViewportCommand::CancelClose), "the close that follows is let through");
}
#[test]
fn closing_the_window_while_close_asks_turns_the_question_into_the_quits() {
let mut h = harness(Services::default());
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
h.state_mut().run("file.close", serde_json::json!({})).unwrap();
h.run_steps(3);
assert!(h.query_by_label_contains("before closing?").is_some());
let sent = request_window_close(&mut h);
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
assert!(h.query_by_label_contains("before quitting?").is_some(), "the question now asks before quitting");
assert!(h.state().unsaved_prompt.as_ref().is_some_and(|p| p.quitting), "and still waits for its answer");
let sent = click_commands(&mut h, "Don't Save");
assert!(sent.contains(&egui::ViewportCommand::Close), "its answer goes on to quit: {sent:?}");
}
#[test]
fn close_question_names_the_actions_in_the_platform_order() {
let mut h = harness(Services::default());
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
h.state_mut().run("file.close", serde_json::json!({})).unwrap();
h.run_steps(2);
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
let dont_save = h.get_by_role_and_label(egui::accesskit::Role::Button, "Don't Save").rect();
let cancel = h.get_by_role_and_label(egui::accesskit::Role::Button, "Cancel").rect();
let save = h.get_by_role_and_label(egui::accesskit::Role::Button, "Save").rect();
// The order every Craft dialog uses on the platform: Save first on Windows; Don't Save, Cancel, Save elsewhere.
// The footer orders by the OS the craft shell runs on, which need not be the machine running the test.
let platform_order = if craft_ui::runtime::windows::os_of(&h.ctx) == craft_host::target::Os::Windows {
save.min.x < dont_save.min.x && dont_save.min.x < cancel.min.x
} else {
dont_save.min.x < cancel.min.x && cancel.min.x < save.min.x
};
assert!(platform_order, "Don't Save {dont_save:?}, Cancel {cancel:?}, Save {save:?}");
}
#[test]
fn close_question_starts_on_save_and_enter_saves() {
let dir = std::env::temp_dir().join(format!("gridcraft-close-enter-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
let mut h = harness(Services::default());
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
h.state_mut().run("file.close", serde_json::json!({})).unwrap();
h.run_steps(3);
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
// The answer that keeps the edits has the focus first; Don't Save never does.
assert!(h.get_by_role_and_label(egui::accesskit::Role::Button, "Save").is_focused(), "the question starts on Save");
assert!(!h.get_by_role_and_label(egui::accesskit::Role::Button, "Don't Save").is_focused());
h.key_press(egui::Key::Enter);
h.run_steps(4);
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
let (wb, _) = gridcraft_engine::io::open_bytes("Book.xlsx", &std::fs::read(&path).unwrap()).unwrap();
assert_eq!(wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(42.0), "Enter saved the change before closing");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn closing_the_window_can_save_first_and_a_saved_workbook_closes_at_once() {
let dir = std::env::temp_dir().join(format!("gridcraft-close-window-{}", std::process::id()));
@@ -484,7 +427,7 @@ fn quitting_with_one_of_two_workbooks_unsaved_asks_once() {
let sent = request_window_close(&mut h);
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert_eq!(h.state().session.active_index(), 0, "the unsaved workbook comes forward");
let sent = click_commands(&mut h, "Cancel");
assert!(!sent.contains(&egui::ViewportCommand::Close), "Cancel stops the quit");
@@ -493,7 +436,7 @@ fn quitting_with_one_of_two_workbooks_unsaved_asks_once() {
request_window_close(&mut h);
let sent = click_commands(&mut h, "Don't Save");
assert!(sent.contains(&egui::ViewportCommand::Close), "the saved workbook isn't asked about: {sent:?}");
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert!(h.state().dialog.is_none());
}
/// Book1 has a cell being typed when File › New runs (the macOS menu runs the command directly).
+12 -47
View File
@@ -493,7 +493,7 @@ fn quitting_asks_about_the_editors_unsaved_steps_first() {
let sent = request_window_close(&mut h);
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
assert!(!sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
assert!(asks_about(&h, "Unsaved"));
assert!(h.query_by_label_contains("Save changes to macro “Unsaved”").is_some());
// Cancel keeps the app and the draft.
// The formula bar's Cancel button has the same name; the question's is the button drawn last.
h.get_all_by_role_and_label(egui::Role::Button, "Cancel").last().unwrap().click();
@@ -522,7 +522,7 @@ fn quitting_with_the_editor_open_still_asks_about_unsaved_workbooks() {
assert!(h.state().macros.editor.is_none());
assert!(sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
request_window_close(&mut h);
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
}
#[test]
@@ -634,14 +634,8 @@ fn is_open(h: &Harness, uid: u64) -> bool {
h.state().session.documents().iter().any(|d| d.uid == uid)
}
/// Whether the shared unsaved-changes question is asking about the macro `name`.
fn asks_about(h: &Harness, name: &str) -> bool {
h.query_by_label_contains(&question_about(name)).is_some()
}
/// The words of the unsaved-changes question that name the macro, closing or quitting.
fn question_about(name: &str) -> String {
format!("the changes you made to “{name}”")
h.query_by_label_contains(&format!("Save changes to macro “{name}”")).is_some()
}
#[test]
@@ -693,7 +687,7 @@ fn save_in_the_question_saves_the_macro_then_the_workbook_asks_about_itself() {
// The macro is in the workbook now, which makes it unsaved: closing it goes on and asks.
assert!(h.state().macros.editor.is_none());
assert_eq!(h.state().session.active().unwrap().wb.macros.len(), 1);
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
h.get_all_by_role_and_label(egui::Role::Button, "Save").last().unwrap().click();
h.run_steps(4);
assert!(!is_open(&h, book));
@@ -705,38 +699,6 @@ fn save_in_the_question_saves_the_macro_then_the_workbook_asks_about_itself() {
let _ = std::fs::remove_file(&path);
}
#[test]
fn the_editors_question_is_the_shared_one_and_enter_saves_the_draft() {
let mut h = harness();
edited_new_macro(&mut h);
let name = h.state().macros.editor.as_ref().unwrap().draft.name.clone();
let book = h.state().session.active().unwrap().uid;
h.state_mut().run("file.close", json!({})).unwrap();
h.run_steps(3);
assert!(asks_about(&h, &name));
// The question's buttons are drawn last (the formula bar has a Cancel and the editor a Save).
let button = |label: &'static str| h.get_all_by_role_and_label(egui::Role::Button, label).last().unwrap();
let (dont_save, cancel, save) = (button("Don't Save").rect(), button("Cancel").rect(), button("Save").rect());
// The order the workbook's question and every Craft dialog use on the platform: Save first on
// Windows; Don't Save, Cancel, Save elsewhere. The footer orders by the OS the craft shell runs
// on, which need not be the machine running the test.
let platform_order = if craft_ui::runtime::windows::os_of(&h.ctx) == craft_host::target::Os::Windows {
save.min.x < dont_save.min.x && dont_save.min.x < cancel.min.x
} else {
dont_save.min.x < cancel.min.x && cancel.min.x < save.min.x
};
assert!(platform_order, "Don't Save {dont_save:?}, Cancel {cancel:?}, Save {save:?}");
// Save has the focus first and Enter answers it: neither discards the draft.
assert!(button("Save").is_focused(), "the question starts on Save");
assert!(!button("Don't Save").is_focused());
h.key_press(Key::Enter);
h.run_steps(4);
assert!(h.state().macros.editor.is_none());
let wb = &h.state().session.documents().iter().find(|d| d.uid == book).expect("the workbook asks about itself next").wb;
assert_eq!(wb.macros.iter().map(|m| m.steps.len()).collect::<Vec<_>>(), [1], "Enter saved the draft into the workbook");
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
}
#[test]
fn a_draft_that_cannot_be_saved_keeps_its_workbook_open() {
let mut h = harness();
@@ -958,7 +920,7 @@ fn a_close_request_during_the_editors_save_dialog_waits_for_it() {
let r = h.state_mut().run("window.close", json!({"window": home})).unwrap();
assert_eq!(r["closed"], false);
h.run_steps(3);
assert_eq!(h.get_all_by_label_contains(&question_about(&name)).count(), 1, "one question");
assert_eq!(h.get_all_by_label_contains("Save changes to macro").count(), 1, "one question");
assert!(is_open(&h, book1) && is_open(&h, book2));
assert!(h.state().message.is_none(), "{:?}", h.state().message);
let pending = h.state().macros.editor.as_ref().and_then(|e| e.then_close.as_ref()).expect("the close waits");
@@ -992,7 +954,7 @@ fn a_different_close_during_the_editors_question_is_refused_until_it_is_answered
let e = h.state_mut().run("file.close", json!({"document": true})).unwrap_err();
assert!(e.contains("asking whether to save") && e.contains("its window closes"), "{e}");
h.run_steps(2);
assert_eq!(h.get_all_by_label_contains(&question_about(&name)).count(), 1, "one question");
assert_eq!(h.get_all_by_label_contains("Save changes to macro").count(), 1, "one question");
assert!(is_open(&h, book));
assert_eq!(h.state().session.windows().len(), 2);
// Don't Save closes the editor's window alone, as the question was asked for.
@@ -1034,6 +996,7 @@ fn quitting_with_a_draft_in_one_window_and_unsaved_cells_in_another_asks_in_orde
h.state_mut().run("cell.set", json!({"cell": "Z9", "input": "unsaved"})).unwrap();
h.run_steps(2);
let book2 = h.state().session.active().unwrap().uid;
let title2 = h.state().session.active().unwrap().display_title();
let b = h.state().session.active_window().unwrap();
assert_ne!(a, b);
let both_open =
@@ -1053,15 +1016,17 @@ fn quitting_with_a_draft_in_one_window_and_unsaved_cells_in_another_asks_in_orde
request_window_close(&mut h);
// Book2 is asked about next, in its window, as the quit's question.
assert_eq!(h.state().session.active_window(), Some(b), "the unsaved workbook's window comes forward");
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>(), "Book2 is asked about");
assert!(h.state().unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
let d = h.state().dialog.as_ref().expect("Book2 is asked about");
assert_eq!(d.name(), "saveChanges");
assert_eq!(d.values.get("title").and_then(serde_json::Value::as_str), Some(title2.as_str()));
assert_eq!(d.values.get("quit"), Some(&json!(true)), "{:?}", d.values);
assert!(both_open(&h));
// Cancel: the quit stops with both windows and workbooks open and Book2's changes kept; the
// draft the person discarded stays discarded.
h.get_all_by_role_and_label(egui::Role::Button, "Cancel").last().unwrap().click();
let sent = step_commands(&mut h);
assert!(!sent.contains(&egui::ViewportCommand::Close) && !h.state().allow_close, "{sent:?}");
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert!(h.state().dialog.is_none());
assert!(both_open(&h));
assert!(h.state().session.documents().iter().find(|d| d.uid == book2).unwrap().is_dirty());
assert!(h.state().macros.editor.is_none());
+95 -118
View File
@@ -56,75 +56,48 @@ fn opt_color(e: Option<&El>, palette: &[u32]) -> Color {
e.map(|e| read_color(e, palette)).unwrap_or(Color::Auto)
}
/// `<b/>`-style boolean property elements: present means true unless `val` says otherwise.
fn bool_prop(e: &El, name: &str) -> bool {
e.child(name).is_some_and(|c| c.flag("val", true))
}
/// A font's `outline` as the shared SpreadsheetML font (`craft-xlsx`) reads it: `None` when the
/// element is absent, `Some(false)` when it says `val="0"` (stated off, which a differential
/// format keeps), `Some(true)` when on.
fn shared_outline(e: &El) -> Option<bool> {
craft_xlsx::Font::read(&crate::chart::to_craft_el(e)).outline
}
/// The shared SpreadsheetML font's `outline` element for `outline`, written as it writes it:
/// `<outline/>`, `<outline val="0"/>`, or nothing.
fn push_shared_outline(s: &mut String, outline: Option<bool>) {
let font = craft_xlsx::Font { outline, ..Default::default() }.to_el("font", false);
for child in font.elements() {
child.write_xml(s);
}
}
const DEFAULT_FONT_FAMILY: u8 = 2;
const MAX_FONT_FAMILY: u8 = 14;
pub fn read_font(e: &El, palette: &[u32]) -> Font {
let mut f = Font::default();
if let Some(n) = e.child("name").or_else(|| e.child("rFont")).and_then(|n| n.attr("val")) {
// Every cell format that uses the font copies its name: keep it short.
f.name = match n.char_indices().nth(MAX_FONT_NAME_CHARS) {
Some((at, _)) => n.get(..at).unwrap_or_default().to_string(),
None => n.to_string(),
};
}
if let Some(sz) = e.child("sz").and_then(|s| s.attr_f64("val")) {
f.size = sz.clamp(1.0, 409.0) as f32;
}
f.bold = bool_prop(e, "b");
f.italic = bool_prop(e, "i");
f.strike = bool_prop(e, "strike");
f.outline = shared_outline(e) == Some(true);
if let Some(u) = e.child("u") {
f.underline = match u.attr("val").unwrap_or("single") {
"double" => Underline::Double,
"singleAccounting" => Underline::SingleAccounting,
"doubleAccounting" => Underline::DoubleAccounting,
"none" => Underline::None,
_ => Underline::Single,
};
}
if let Some(v) = e.child_val("vertAlign") {
f.vert = match v {
"superscript" => VertAlign::Superscript,
"subscript" => VertAlign::Subscript,
model_font(&craft_xlsx::Font::read(&crate::chart::to_craft_el(e)), palette)
}
/// The format reader owns SpreadsheetML spelling and presence; the app owns its font limits,
/// palette and theme defaults, and conversion to the model's enums.
fn model_font(f: &craft_xlsx::Font, palette: &[u32]) -> Font {
let def = Font::default();
let color = match f.color.map(|c| (c.source, c.tint)) {
Some((craft_xlsx::ColorSource::Theme(t), tint)) if t <= 11 => Color::Theme(t as u8, (tint * 1000.0).round().clamp(-1000.0, 1000.0) as i16),
Some((craft_xlsx::ColorSource::Rgb(v), _)) => Color::Rgb(v & 0xFF_FFFF),
Some((craft_xlsx::ColorSource::Indexed(i), _)) => palette.get(i as usize).copied().map(Color::Rgb).unwrap_or(Color::Auto),
_ => Color::Auto,
};
Font {
name: f.name.as_ref().map(|n| n.chars().take(MAX_FONT_NAME_CHARS).collect()).unwrap_or(def.name),
size: f.size.map(|s| s.clamp(1.0, 409.0) as f32).unwrap_or(def.size),
bold: f.bold == Some(true),
italic: f.italic == Some(true),
strike: f.strike == Some(true),
outline: f.outline == Some(true),
underline: match f.underline {
Some(craft_xlsx::Underline::Single) => Underline::Single,
Some(craft_xlsx::Underline::Double) => Underline::Double,
Some(craft_xlsx::Underline::SingleAccounting) => Underline::SingleAccounting,
Some(craft_xlsx::Underline::DoubleAccounting) => Underline::DoubleAccounting,
_ => Underline::None,
},
vert: match f.vert_align {
Some(craft_xlsx::Script::Superscript) => VertAlign::Superscript,
Some(craft_xlsx::Script::Subscript) => VertAlign::Subscript,
_ => VertAlign::Baseline,
};
},
charset: f.charset.and_then(|v| u8::try_from(v).ok()),
family: f.family.and_then(|v| u8::try_from(v).ok()).filter(|v| *v <= MAX_FONT_FAMILY && *v != DEFAULT_FONT_FAMILY),
minor: f.scheme == Some(craft_xlsx::FontScheme::Minor),
// Text 1 (dk1) is what automatic font colour means in practice.
color: if color == Color::Theme(1, 0) { Color::Auto } else { color },
}
f.charset = e.child("charset").and_then(|c| c.attr_u32("val")).and_then(|v| u8::try_from(v).ok());
f.family = e
.child("family")
.and_then(|c| c.attr_u32("val"))
.and_then(|v| u8::try_from(v).ok())
.filter(|v| *v <= MAX_FONT_FAMILY && *v != DEFAULT_FONT_FAMILY);
f.minor = e.child_val("scheme") == Some("minor");
f.color = opt_color(e.child("color"), palette);
// Text 1 (dk1) is what "automatic" font colour means in practice.
if f.color == Color::Theme(1, 0) {
f.color = Color::Auto;
}
f
}
fn pattern_from(s: &str) -> PatternType {
@@ -421,21 +394,23 @@ pub fn read_styles(root: &El, checkboxes: &[bool], minor_font: &str) -> StylesIn
fn read_dxf<'a>(x: &'a El, palette: &[u32], fmts: &HashMap<u32, NumFmt>, inline_fmts: &mut HashMap<&'a str, NumFmt>) -> Style {
let mut s = Style::default();
if let Some(e) = x.child("font") {
let f = read_font(e, palette);
let shared = craft_xlsx::Font::read(&crate::chart::to_craft_el(e));
let f = model_font(&shared, palette);
// Differential fonts rarely name a face; unless stated, keep the default face and size.
let has_size = e.child("sz").and_then(|n| n.attr_f64("val")).is_some();
let has_name = e.child("name").and_then(|n| n.attr("val")).is_some();
let has_size = shared.size.is_some();
let has_name = shared.name.is_some();
let name = if has_name { f.name.clone() } else { s.font.name.clone() };
let size = if has_size { f.size } else { s.font.size };
let def = Font::default();
let st = &mut s.dxf_stated;
st.bold = e.child("b").is_some() && !f.bold;
st.italic = e.child("i").is_some() && !f.italic;
st.strike = e.child("strike").is_some() && !f.strike;
st.outline = shared_outline(e) == Some(false);
st.underline = e.child("u").is_some() && f.underline == Underline::None;
st.bold = shared.bold == Some(false);
st.italic = shared.italic == Some(false);
st.strike = shared.strike == Some(false);
st.outline = shared.outline == Some(false);
st.underline = shared.underline == Some(craft_xlsx::Underline::None);
st.size = has_size && size == def.size;
st.name = has_name && name == def.name;
// Keep the model's raw scheme statement, including a spelling it does not interpret.
st.scheme = e.child_val("scheme").map(str::to_string);
// A differential font's scheme is in `dxf_stated`.
s.font = Font { name, size, minor: s.font.minor, ..f };
@@ -491,57 +466,59 @@ pub fn color_attrs(c: &Color) -> String {
/// differential format's font, which writes only what it states.
fn font_xml(f: &Font, dxf: Option<&DxfStated>, minor: bool) -> String {
let stated = dxf.cloned().unwrap_or_default();
let mut s = String::from("<font>");
for (on, said, tag) in [(f.bold, stated.bold, "b"), (f.italic, stated.italic, "i"), (f.strike, stated.strike, "strike")] {
if on {
let _ = write!(s, "<{tag}/>");
} else if said {
let _ = write!(s, "<{tag} val=\"0\"/>");
}
}
// Excel's order puts outline after strike (condense and extend aren't modelled).
let outline = if f.outline { Some(true) } else { stated.outline.then_some(false) };
push_shared_outline(&mut s, outline);
match f.underline {
Underline::None if stated.underline => s.push_str("<u val=\"none\"/>"),
Underline::None => {}
Underline::Single => s.push_str("<u/>"),
Underline::Double => s.push_str("<u val=\"double\"/>"),
Underline::SingleAccounting => s.push_str("<u val=\"singleAccounting\"/>"),
Underline::DoubleAccounting => s.push_str("<u val=\"doubleAccounting\"/>"),
}
match f.vert {
VertAlign::Baseline => {}
VertAlign::Superscript => s.push_str("<vertAlign val=\"superscript\"/>"),
VertAlign::Subscript => s.push_str("<vertAlign val=\"subscript\"/>"),
}
let flag = |on: bool, off: bool| if on { Some(true) } else { off.then_some(false) };
let def = Font::default();
if dxf.is_none() || stated.size || f.size != def.size {
let _ = write!(s, "<sz val=\"{}\"/>", num(f.size as f64));
}
if f.color != Color::Auto {
let _ = write!(s, "<color {}/>", color_attrs(&f.color));
} else if dxf.is_none() {
s.push_str("<color theme=\"1\"/>");
}
if dxf.is_none() {
let family = f.family.filter(|v| *v <= MAX_FONT_FAMILY).unwrap_or(DEFAULT_FONT_FAMILY);
let _ = write!(s, "<name val=\"{}\"/><family val=\"{family}\"/>", esc_attr(&f.name));
if let Some(charset) = f.charset {
let _ = write!(s, "<charset val=\"{charset}\"/>");
}
if minor {
s.push_str("<scheme val=\"minor\"/>");
}
let color = match f.color {
Color::Auto if dxf.is_some() => None,
Color::Auto => Some(craft_xlsx::Color { source: craft_xlsx::ColorSource::Theme(1), tint: 0.0 }),
Color::Rgb(v) => Some(craft_xlsx::Color { source: craft_xlsx::ColorSource::Rgb(0xFF00_0000 | v), tint: 0.0 }),
Color::Theme(i, tint) => Some(craft_xlsx::Color { source: craft_xlsx::ColorSource::Theme(u32::from(i)), tint: f64::from(tint) / 1000.0 }),
};
let scheme = if dxf.is_none() {
minor.then_some(craft_xlsx::FontScheme::Minor)
} else {
if stated.name || f.name != def.name {
let _ = write!(s, "<name val=\"{}\"/>", esc_attr(&f.name));
}
if let Some(sc) = &stated.scheme {
let _ = write!(s, "<scheme val=\"{}\"/>", esc_attr(sc));
match stated.scheme.as_deref() {
Some("major") => Some(craft_xlsx::FontScheme::Major),
Some("minor") => Some(craft_xlsx::FontScheme::Minor),
Some("none") => Some(craft_xlsx::FontScheme::None),
_ => None,
}
};
let shared = craft_xlsx::Font {
bold: flag(f.bold, stated.bold),
italic: flag(f.italic, stated.italic),
strike: flag(f.strike, stated.strike),
outline: flag(f.outline, stated.outline),
underline: (f.underline != Underline::None || stated.underline).then_some(match f.underline {
Underline::None => craft_xlsx::Underline::None,
Underline::Single => craft_xlsx::Underline::Single,
Underline::Double => craft_xlsx::Underline::Double,
Underline::SingleAccounting => craft_xlsx::Underline::SingleAccounting,
Underline::DoubleAccounting => craft_xlsx::Underline::DoubleAccounting,
}),
vert_align: match f.vert {
VertAlign::Baseline => None,
VertAlign::Superscript => Some(craft_xlsx::Script::Superscript),
VertAlign::Subscript => Some(craft_xlsx::Script::Subscript),
},
size: (dxf.is_none() || stated.size || f.size != def.size).then_some(f64::from(f.size)),
color,
name: (dxf.is_none() || stated.name || f.name != def.name).then(|| f.name.clone()),
family: dxf.is_none().then(|| u32::from(f.family.filter(|v| *v <= MAX_FONT_FAMILY).unwrap_or(DEFAULT_FONT_FAMILY))),
charset: if dxf.is_none() { f.charset.map(u32::from) } else { None },
scheme,
..Default::default()
};
let mut font = shared.to_el("font", false);
// The model preserves an unrecognized differential scheme as opaque text.
if dxf.is_some()
&& scheme.is_none()
&& let Some(raw) = &stated.scheme
{
font.push(craft_xml::El::new("scheme").with_attr("val", raw));
}
s.push_str("</font>");
let mut s = String::new();
font.write_xml(&mut s);
s
}