PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Unsaved-changes prompt: the default answer takes keyboard focus, so arrows and Enter work (part of #6441) (#6466)
Marco Arnulfodb46713c2ca0
diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rsindex 30e5f47de..672001545 100644--- a/crates/ui-egui/src/discard_ui.rs+++ b/crates/ui-egui/src/discard_ui.rs@@ -21,6 +21,8 @@ pub struct Prompt {/// The document the command was aimed at (`document` param, else the active one), if it has one.target: Option<DocId>,docs: Vec<DocId>,+ /// The document whose question has already put keyboard focus on its default answer.+ focused: Option<DocId>,}fn index_of(app: &PhotocraftApp, id: DocId) -> Option<usize> {@@ -69,7 +71,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str, params: &Value) -> bool {if docs.is_empty() {return false;}- let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs };+ let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs, focused: None };match &app.discard {None => ask(app, prompt),// Quitting overrides whatever is pending: it covers every document, so nothing is lost.@@ -226,6 +228,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {// Save can ask for a path and then TIFF or Targa Options, and then write in the background.// Wait for all three; cancellation or a failed save brings us back.if app.file_dialog_open() || app.save_options_open() || app.saving() {+ // Hidden meanwhile: the question takes focus again when it comes back.+ if let Some(p) = app.discard.as_mut() {+ p.focused = None;+ }return;}let Some(p) = &app.discard else { return };@@ -246,6 +252,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {};(tl!("Unsaved changes"), crate::i18n::fmt(template, &[("name", &name)]))};+ // Each question comes up with its default answer focused, as in Photoshop: the arrow keys then+ // move between the answers and Enter presses the focused one (#6441).+ let focus = p.focused != Some(doc);+ if let Some(p) = app.discard.as_mut() {+ p.focused = Some(doc);+ }let mac = ctx.os() == egui::os::OperatingSystem::Mac;// The answers in the platform's words; `dialog_buttons` puts them in its order. Windows (and// Linux) ask Yes / No / Cancel with Y, N and Esc, as Photoshop does there; macOS asks@@ -266,7 +278,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {};let mut answer = ctx.input_mut(|i| buttons.iter().find(|b| b.2.is_some_and(|k| i.consume_key(egui::Modifiers::NONE, k))).map(|b| b.4));let labels = button_labels(mac, &buttons.iter().map(|b| (b.1, b.2)).collect::<Vec<_>>());- let row: Vec<DialogButton> = buttons.iter().zip(&labels).map(|(b, label)| DialogButton::new(b.0, label, b.3)).collect();+ let row: Vec<DialogButton> =+ buttons.iter().zip(&labels).map(|(b, label)| DialogButton::new(b.0, label, b.3).focus(focus && b.0 == ButtonRole::Default)).collect();let modal = egui::Modal::new(egui::Id::new("discard-prompt")).show(ctx, |ui| {ui.set_max_width(420.0);ui.label(egui::RichText::new(tl!(&title)).font(crate::theme::semibold(15.0)));@@ -582,31 +595,60 @@ mod tests {v.into_iter().map(|(_, l)| l).collect()}- /// Tab walks `labels` left to right and wraps; Shift+Tab steps back.- fn tab_walks(h: &mut Prompted, labels: [&str; 3]) {- use egui_kittest::kittest::Queryable;- let focused = |h: &Prompted| labels.into_iter().find(|l| h.get_by_label(l).is_focused());- for want in [labels[0], labels[1], labels[2], labels[0]] {+ /// Tab walks `labels` left to right from the focused default answer, `labels[default]`, and+ /// wraps; Shift+Tab steps back.+ fn tab_walks(h: &mut Prompted, labels: [&str; 3], default: usize) {+ assert_eq!(focused(h, &labels), Some(labels[default]));+ for step in 1..=3 {h.key_press(Key::Tab);h.run_steps(2);- assert_eq!(focused(h), Some(want));+ assert_eq!(focused(h, &labels), Some(labels[(default + step) % 3]));}h.key_press_modifiers(egui::Modifiers::SHIFT, Key::Tab);h.run_steps(2);- assert_eq!(focused(h), Some(labels[2]));+ assert_eq!(focused(h, &labels), Some(labels[(default + 2) % 3]));}fn docs_left(h: &Prompted) -> Option<usize> {h.state().discard.as_ref().map(|p| p.docs.len())}+ /// Which of `labels` has keyboard focus.+ fn focused<'a>(h: &Prompted, labels: &[&'a str]) -> Option<&'a str> {+ use egui_kittest::kittest::Queryable;+ labels.iter().copied().find(|l| h.get_by_label(l).is_focused())+ }++ /// The default answer has keyboard focus as each question comes up, so the arrow keys move+ /// between the answers and Enter presses the one they reached, as in Photoshop (#6441).+ #[test]+ fn each_question_comes_up_with_the_default_answer_focused() {+ let mut h = prompt_on(egui::os::OperatingSystem::Windows);+ let labels = ["(Y)es", "(N)o", "(C)ancel"];+ assert_eq!(focused(&h, &labels), Some("(Y)es"));+ h.key_press(Key::ArrowRight);+ h.run_steps(2);+ assert_eq!(focused(&h, &labels), Some("(N)o"));+ h.key_press(Key::Enter);+ h.run_steps(2);+ assert_eq!(docs_left(&h), Some(1), "Enter pressed No");+ assert_eq!(focused(&h, &labels), Some("(Y)es"), "the next question starts on the default again");++ let mut h = prompt_on(egui::os::OperatingSystem::Mac);+ let labels = ["Don't Save", "Cancel", "Save"];+ assert_eq!(focused(&h, &labels), Some("Save"));+ h.key_press(Key::ArrowLeft);+ h.run_steps(2);+ assert_eq!(focused(&h, &labels), Some("Cancel"));+ }+#[test]fn windows_and_linux_ask_yes_no_cancel_with_the_default_first() {for os in [egui::os::OperatingSystem::Windows, egui::os::OperatingSystem::Nix] {let mut h = prompt_on(os);let labels = ["(Y)es", "(N)o", "(C)ancel"];assert_eq!(drawn_order(&h, labels), labels, "{os:?}");- tab_walks(&mut h, labels);+ tab_walks(&mut h, labels, 0);h.key_press(Key::N);h.run_steps(2);assert_eq!(docs_left(&h), Some(1), "N answered the first document");@@ -699,7 +741,7 @@ mod tests {let mut h = prompt_on(egui::os::OperatingSystem::Mac);let labels = ["Don't Save", "Cancel", "Save"];assert_eq!(drawn_order(&h, labels), labels);- tab_walks(&mut h, labels);+ tab_walks(&mut h, labels, 2);h.key_press(Key::D);h.run_steps(2);assert_eq!(docs_left(&h), Some(1), "D answered the first document");@@ -736,11 +778,9 @@ mod tests {h.run_steps(2);assert_eq!(asked.borrow().len(), 1, "Enter answered Yes, which saves");assert_eq!(docs_left(&h), Some(2));- // Tab to No: Enter now presses it.- for _ in 0..2 {- h.key_press(Key::Tab);- h.run_steps(2);- }+ // Tab from the focused Yes to No: Enter now presses it.+ h.key_press(Key::Tab);+ h.run_steps(2);h.key_press(Key::Enter);h.run_steps(2);assert_eq!(asked.borrow().len(), 1, "no second dialog");@@ -776,7 +816,7 @@ mod tests {assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits behind the dialog");answer(&mut h, None);assert_eq!(docs_left(&h), Some(1));- assert!(h.query_by_label("(Y)es").is_some());+ assert_eq!(focused(&h, &["(Y)es", "(N)o", "(C)ancel"]), Some("(Y)es"), "the prompt comes back with Yes focused");// Saving closes the document.h.key_press(Key::Y);h.run_steps(3);diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 7235790cb..48d7cc5ad 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -1193,16 +1193,24 @@ pub struct DialogButton<'a> {pub label: &'a str,pub min_width: f32,pub enabled: bool,+ /// Take keyboard focus this frame (see [`DialogButton::focus`]).+ pub focus: bool,}impl<'a> DialogButton<'a> {pub fn new(role: ButtonRole, label: &'a str, min_width: f32) -> Self {- Self { role, label, min_width, enabled: true }+ Self { role, label, min_width, enabled: true, focus: false }}pub fn enabled(self, enabled: bool) -> Self {Self { enabled, ..self }}++ /// Asks for keyboard focus for this button: from there the arrow keys move between the row's+ /// buttons and Enter or Space presses the focused one.+ pub fn focus(self, focus: bool) -> Self {+ Self { focus, ..self }+ }}/// A dialog's button row at the cursor, in the platform's order (see [`ButtonRole`]): every modal@@ -1225,6 +1233,9 @@ pub fn dialog_buttons(ui: &mut Ui, buttons: &[DialogButton]) -> Option<ButtonRolif b.role == ButtonRole::Default { primary_button(ui, b.label, b.min_width) } else { secondary_button(ui, b.label, b.min_width) }}).inner;+ if b.focus && b.enabled {+ r.request_focus();+ }if r.clicked() {hit = Some(b.role);}