fix(ui): ask about unsaved changes with the shared dialog

Route the engine's saveChanges dialog request to craft_ui::dialog::UnsavedChangesDialog on framework_dialogs with document wording, remove the custom saveChanges dialog and its unused i18n strings, and update UI/doc-window tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
arnav-hiwarkar
2026-12-04 15:28:49 +05:30
co-authored by Claude Opus 5.5
parent fb7ca98282
commit a2df25c9bd
30 changed files with 204 additions and 104 deletions
Generated
+1
View File
@@ -3050,6 +3050,7 @@ dependencies = [
"craft-host",
"craft-keymap",
"craft-print",
"craft-quit",
"craft-theme",
"craft-ui",
"craft-update",
+1
View File
@@ -105,6 +105,7 @@ 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"
+1
View File
@@ -16,6 +16,7 @@ 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 }
+18 -2
View File
@@ -93,6 +93,7 @@ impl SheetApp {
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
unsaved_prompt: None,
framework_host: crate::framework::host(),
}
}
@@ -267,10 +268,13 @@ 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 and the framework dialogs run once per frame, in the root window.
// 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"))]
if ctx.viewport_id() == egui::ViewportId::ROOT {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
}
if self.framework_dialogs_here(&ctx) {
self.run_framework_dialogs(ui);
}
self.flush_viewport_commands(&ctx);
@@ -302,6 +306,18 @@ 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() };
+2 -1
View File
@@ -335,7 +335,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.dialog.as_ref().map(|d| d.name())}))
Ok(json!({"dialog": self.open_dialog_name()}))
}
"ui.selectionMode" => {
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
@@ -481,6 +481,7 @@ 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.dialog.is_none()
&& !self.modal_open()
&& self.message.is_none()
&& self.name_box.is_none()
&& !ctx.text_edit_focused()
+77 -7
View File
@@ -1,7 +1,10 @@
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
@@ -31,12 +34,11 @@ impl SheetApp {
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
}
match self.dialog.as_mut() {
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
// Already asking about a workbook (File › Close): answering it now goes on to quit.
Some(d) if d.name() == "saveChanges" => {
d.values.insert("quit".into(), json!(true));
}
_ => self.continue_quit(ctx),
self.promote_unsaved_to_quit();
} else {
self.continue_quit(ctx);
}
CloseDecision::Hold
}
@@ -233,13 +235,81 @@ impl SheetApp {
crate::macro_editor::request_close(self, true);
return;
}
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
// Already asking about a workbook (File › Close): answering it goes on to quit.
d.values.insert("quit".into(), json!(true));
self.promote_unsaved_to_quit();
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));
}
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));
}
}
/// 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) {
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.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
if !typing && !app.modal_open() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
out.close = true;
}
if let Some(page) = out.page {
+3 -2
View File
@@ -147,7 +147,8 @@ 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})),
"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}}))),
"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,
@@ -339,7 +340,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.dialog.as_ref().map(|d| d.name.clone())}))
ok(json!({"dialog": app.open_dialog_name()}))
}
"ui.dialog.set" => match app.dialog.as_mut() {
Some(d) => {
-1
View File
@@ -1166,7 +1166,6 @@ 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,19 +374,6 @@ 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.dialog.is_some();
let dialog_open = app.modal_open();
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.dialog.is_some() {
if !has_focus || !mine || app.message.is_some() || app.modal_open() {
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.dialog.is_some();
let blocked = app.message.is_some() || app.modal_open();
let mut caret = None;
if blocked {
ed.request_focus = true;
+11
View File
@@ -112,9 +112,20 @@ 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.
pub(crate) fn framework_dialogs_here(&self, ctx: &egui::Context) -> 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) => self.ui_window() == 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.dialog.is_some()
|| app.modal_open()
|| 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.dialog.is_some() || app.grid.drag != Drag::None {
if app.editor.is_some() || app.modal_open() || 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.dialog.is_some() || sh.show_formulas || app.grid.drag != Drag::None {
if app.editor.is_some() || app.modal_open() || 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,7 +574,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Zoom Out" => "Σμίκρυνση",
"Dismiss" => "Κλείσιμο",
"OK" => "Εντάξει",
"Don't Save" => "Χωρίς αποθήκευση",
"Open…" => "Άνοιγμα…",
"Show password" => "Εμφάνιση κωδικού πρόσβασης",
"Start a new workbook" => "Δημιουργία νέου βιβλίου εργασίας",
@@ -583,7 +582,6 @@ 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" => "Ύψος γραμμής",
@@ -624,7 +622,6 @@ 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,7 +445,6 @@ 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",
@@ -454,7 +453,6 @@ 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",
@@ -505,7 +503,6 @@ 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,7 +462,6 @@ 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", "新しいブックの作成"),
@@ -471,7 +470,6 @@ 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", "テキスト ボックス"),
@@ -522,7 +520,6 @@ 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,7 +436,6 @@ 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",
@@ -445,7 +444,6 @@ 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",
@@ -496,7 +494,6 @@ 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,7 +464,6 @@ 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",
@@ -473,7 +472,6 @@ 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",
@@ -530,7 +528,6 @@ 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,7 +442,6 @@ 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",
@@ -451,7 +450,6 @@ 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",
@@ -502,7 +500,6 @@ 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,8 +599,6 @@ 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" => "Кольцевая",
@@ -846,7 +844,6 @@ 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,7 +440,6 @@ 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",
@@ -449,7 +448,6 @@ 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" => "Напис",
@@ -500,7 +498,6 @@ 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,7 +450,6 @@ 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",
@@ -459,7 +458,6 @@ 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",
@@ -510,7 +508,6 @@ 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",
+4 -2
View File
@@ -362,9 +362,11 @@ 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), 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 and the unsaved-changes
/// prompt), 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>,
}
+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.dialog.is_some()
|| app.modal_open()
|| app.text_box_editor.is_some()
|| app.grid.context_menu.is_some()
|| geo.paper.is_some()
+9
View File
@@ -19,6 +19,15 @@ 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 {
+38 -26
View File
@@ -7,6 +7,7 @@
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;
@@ -18,8 +19,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()) };
/// 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()) };
/// 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());
}
fn record(mut out: egui::FullOutput) {
@@ -32,6 +33,17 @@ 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,
@@ -49,6 +61,7 @@ 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)));
});
@@ -68,7 +81,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 = EVENTS.with(|e| std::mem::take(&mut *e.borrow_mut()));
input.events = take_events(ViewportId::ROOT);
let Desk { ctx, app, windows } = self;
let mut act = Some(act);
let out = ctx.clone().run_ui(input, |ui| {
@@ -104,15 +117,19 @@ impl Desk {
sent
}
/// Answers the Save Changes question showing in the active window, as its button does.
/// 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.
fn answer(&mut self, answer: SaveAnswer) -> Vec<(ViewportId, ViewportCommand)> {
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));
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 (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);
let sent = 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");
sent
}
@@ -123,9 +140,7 @@ impl Desk {
/// The user presses `key` in the root window.
fn key(&mut self, key: egui::Key) -> Vec<(ViewportId, ViewportCommand)> {
EVENTS.with(|e| {
e.borrow_mut().push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE })
});
press(ViewportId::ROOT, key, egui::Modifiers::NONE);
let mut sent = self.frame_with(|_, _| {});
sent.extend(self.frames(2));
sent
@@ -202,7 +217,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_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
assert_eq!(desk.app.session.documents().len(), 1);
let sent = desk.answer(SaveAnswer::Cancel);
@@ -244,17 +259,17 @@ 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_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
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.dialog.is_none());
assert!(!desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
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_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
let sent = desk.answer(SaveAnswer::DontSave);
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "both answered: the app quits: {sent:?}");
}
@@ -268,7 +283,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_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>());
for cmd in [ViewportCommand::Visible(true), ViewportCommand::Minimized(false), ViewportCommand::Focus] {
assert!(sent_to(&sent, desk.viewport(w), &cmd), "{cmd:?} missing: {sent:?}");
}
@@ -517,9 +532,8 @@ 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));
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!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "Book2 is asked about");
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
assert_eq!(desk.app.session.documents().len(), 2, "nothing closed before the answer");
}
@@ -551,10 +565,8 @@ 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");
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!(desk.app.framework_dialogs.is_open::<UnsavedChangesDialog>(), "Book2 is asked about");
assert!(desk.app.unsaved_prompt.as_ref().is_some_and(|p| p.quitting));
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.
+25 -6
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_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0));
}
@@ -357,23 +357,42 @@ 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_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
let sent = click_commands(&mut h, "Cancel");
assert!(!sent.contains(&egui::ViewportCommand::Close), "Cancel keeps the app open");
assert!(h.state().dialog.is_none());
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
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_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"), "then it asks about the next one");
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>(), "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 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.
let platform_order = if cfg!(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 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()));
@@ -408,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_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
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");
@@ -417,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().dialog.is_none());
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
}
/// Book1 has a cell being typed when File › New runs (the macOS menu runs the command directly).
+5 -8
View File
@@ -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_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
}
#[test]
@@ -687,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_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
assert!(h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
h.get_all_by_role_and_label(egui::Role::Button, "Save").last().unwrap().click();
h.run_steps(4);
assert!(!is_open(&h, book));
@@ -996,7 +996,6 @@ 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 =
@@ -1016,17 +1015,15 @@ 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");
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!(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));
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().dialog.is_none());
assert!(!h.state().framework_dialogs.is_open::<craft_ui::dialog::UnsavedChangesDialog>());
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());