From 8467488c2683bd22b1a79dd182cde5465174e183 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 21:01:36 +0100 Subject: [PATCH] Integration: zoom field follows the system decimal separator, takes a second one with the invalid-entry message, Tab rewrites the number (#6647) Checked against the reference application on a German Windows: - The decimal separator is the system's (Windows: Region's decimal symbol, read from HKCU\Control Panel\International\sDecimal through winsafe's safe registry binding; the `advapi` feature of the winsafe already in the lock). On a comma system a typed or pasted `.` is refused with the alert and `,` is the decimal point, on a dot system the other way round; ratios follow it (`100/5,0`). Where the separator can't be read (macOS, Linux, web) both are taken. The field shows its zoom with that separator (`12,5`), so its own text can be typed. - A second separator (`80,,2`) is now typed in, not dropped. Enter (or a click that applies) opens the "Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted." message in the app's error dialog (the field's range, two decimals, the system separator; translated in every catalog) and applies the number before the second separator (80 %). Esc, Tab and kept clicks show nothing. A paste follows the same rules. - Tab and a click that keeps the typed number (pasteboard, title bar, open menu) write it as the zoom Enter would make of it (`045` and `45,0` -> `45`, `1/2` -> `50`, past the range -> its end) and select it; the `%` stays outside the field. Text with a second separator stays, and so does text after a key the field's copy can't follow (a word deletion, an undo). Tests: a_zoom_field_takes_only_the_systems_decimal_separator, a_zoom_field_shows_the_systems_decimal_separator, a_second_separator_is_typed_and_enter_applies_the_number_before_it_with_the_message, esc_and_tab_with_a_second_separator_show_no_message, a_paste_follows_the_typing_rules, tab_writes_the_typed_number_as_the_zoom_it_makes, a_click_on_the_pasteboard_writes_the_typed_number_as_the_zoom_it_makes, tab_after_a_word_deletion_leaves_the_text_as_it_is, the status bar's a_second_separator_in_the_zoom_field_opens_the_invalid_entry_message_and_applies_the_leading_number, and unit tests for the separator, the reading and the message. Each fails with its fix reverted. Co-authored-by: sn-o-w <2406819+sn-o-w@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/Cargo.toml | 7 +- crates/ui-egui/src/canvas/zoom_field.rs | 272 ++++++++++++++++------- crates/ui-egui/src/i18n.rs | 4 +- crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/system.rs | 84 ++++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/status_bar_tests.rs | 45 ++++ crates/ui-egui/src/widgets/fields.rs | 63 ++++-- crates/ui-egui/src/widgets/tests.rs | 274 ++++++++++++++++-------- 28 files changed, 581 insertions(+), 189 deletions(-) diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index c95da851e04..326e6bf7a7d 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -50,10 +50,11 @@ rayon = { workspace = true } # Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency. sys-locale = "=0.3.2" -# Installed RAM for the GPU memory budget (`gpu_canvas::physical_memory`): the safe binding the -# desktop app already uses, pinned to the same version. +# Installed RAM for the GPU memory budget (`gpu_canvas::physical_memory`) and the user's decimal +# symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already +# uses, pinned to the same version. [target.'cfg(target_os = "windows")'.dependencies] -winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi"] } +winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] } [dev-dependencies] # egui's own default fonts in tests: the oracle for egui_fonts.rs, and contexts made with diff --git a/crates/ui-egui/src/canvas/zoom_field.rs b/crates/ui-egui/src/canvas/zoom_field.rs index 2debd40e79c..4f256e44b0f 100644 --- a/crates/ui-egui/src/canvas/zoom_field.rs +++ b/crates/ui-egui/src/canvas/zoom_field.rs @@ -4,21 +4,24 @@ //! then the image keeps its zoom, and these keys never apply what was typed: //! //! * Esc drops it: the field shows the current zoom again. -//! * Tab and ⇧Tab keep the focus in the field, select its text so typing replaces it, and play -//! the system alert (Windows: the Asterisk sound). +//! * Tab and ⇧Tab keep the focus in the field, write the typed number as the field shows a zoom +//! (`045` and `45,0` become `45`, `1/2` becomes `50`; the `%` is drawn beside the field), select +//! it so typing replaces it, and play the system alert (Windows: the Asterisk sound). //! * Alt (tapped) does only that alert: it neither puts the keyboard on the menu bar nor leaves //! the field. //! * A click, with either button, on the pasteboard (the canvas around the image), anywhere on the //! title bar (menu titles, the empty drag area, the workspace switcher, search, the theme //! button, Minimise / Maximise / Close), or on an open menu or dropdown (Help's "Search menus" -//! field included), keeps the typed number unapplied and selects the text again, as Tab does. +//! field included), keeps the typed number unapplied, rewritten and selected as Tab does it. //! * Whatever the key or click, a typed number is never applied while the window is not focused. -//! * Only digits, `.`, `,` and `/` can be typed or pasted; any other character is dropped and asks for -//! the same alert, without touching the text. -//! * `,` is a decimal point like `.` (`100,90` is `100.90`). The text holds at most one of them: a -//! second `.` or `,`, a `,` next to a `.` (`1,000.5`) and a `.` next to a `/` (`100/5.0`; the ratio -//! takes `100/5,0`) are typed away like any other character: dropped, with the alert. A paste is -//! not cut up: `100/5.0` stays in the field, asks for the alert, and Enter puts the current zoom back. +//! * Only digits, `/` and the system's decimal separator ([`crate::i18n::decimal_separator`]: `,` on +//! a German Windows, `.` on an English one, in ratios too: `100/5,0`) can be typed or pasted; any +//! other character (the other separator too) is dropped and asks for the same alert, without +//! touching the text. Where the system's separator is not known, both `.` and `,` are taken. The +//! field shows its zoom with that separator (`33,33`). +//! * A second separator can be typed (`80,,2`), and pasted. Enter (or a click that applies) then +//! shows Photoshop's "Invalid numeric entry" message with the field's range and applies the number +//! before the second separator (`80`), as Photoshop does after its OK. //! //! The field itself is `widgets::number_edit` (with `hold_typed`), which calls [`before`] and //! [`after`] around the egui `DragValue`. The rest is bookkeeping other parts of the app read: @@ -86,22 +89,25 @@ fn select_all_by_key(ui: &Ui) { ui.input_mut(|i| i.events.push(ctrl_a)); } -/// A zoom takes digits, `.`, `,` and `/` only (`/` for a ratio: `1/2` is 50 %, `5/2` is 250 %; -/// the `%` is drawn beside the field, never typed). Anything else typed or pasted is taken out of this -/// frame's input before the field sees it; true when something was. -/// -/// A typed `.`, `,` or `/` that would make the text [`violates`] the rules (a second separator, `,` -/// with `.`, `.` with `/`) is taken out too. The text it would land in is the one the `DragValue` -/// keeps (`shown` before the first key), minus the selection. A paste is only filtered by -/// character, so what is invalid stays in the field, for the alert in [`after`] and for Enter. +/// Can `c` be typed into a zoom field? Digits, `/` (for a ratio: `1/2` is 50 %, `5/2` is 250 %; +/// the `%` is drawn beside the field, never typed) and the decimal separator `sep` (both `.` and `,` +/// when it is not known). +fn accepted(c: char, sep: Option) -> bool { + c.is_ascii_digit() || c == '/' || sep.map_or(matches!(c, '.' | ','), |s| c == s) +} + +/// Takes out of this frame's input whatever a zoom field does not take ([`accepted`]) before the +/// field sees it; true when something was. A second separator is not refused here (Photoshop types +/// it, and refuses the number on Enter: [`read`]). /// /// egui keeps the text being edited in a private `EditState`, out of reach, so this module keeps -/// its own copy under [`mirror_id`]: what the field showed when it got the keyboard, with the keys -/// applied that are seen here (typed, pasted, cut, Backspace, Delete). A key that changes the text -/// in a way not followed (undo, a word deletion) makes the copy empty: the rules then only look at -/// what is typed from there on, and Enter still refuses text that [`violates`] them. The copy is kept -/// with the `shown` it started from: when the value changes under the focused field (ArrowUp, the -/// wheel, another zoom), the field shows the new number, and the copy starts again from it. +/// its own copy under [`mirror_id`], for Tab and a click that keeps the number to rewrite it +/// ([`canonical`]): what the field showed when it got the keyboard, with the keys applied that are +/// seen here (typed, pasted, cut, Backspace, Delete). A key that changes the text in a way not +/// followed (undo, a word deletion) makes the copy empty and marks it lost ([`lost_id`]): the text +/// is then only selected, never rewritten, until the field is left. The copy is kept with the `shown` it started from: when the value changes under the +/// focused field (ArrowUp, the wheel, another zoom), the field shows the new number, and the copy +/// starts again from it. fn drop_unwanted_chars(ui: &Ui, id: Id, shown: &str) -> bool { let mirror = mirror_id(id); let stored = ui.data(|d| d.get_temp::<(String, String)>(mirror)).filter(|(from, _)| from == shown).map(|(_, text)| text); @@ -117,36 +123,24 @@ fn drop_unwanted_chars(ui: &Ui, id: Id, shown: &str) -> bool { (Some(_), None) => (len, len), (None, _) => (0, len), }; - let allowed = |c: char| c.is_ascii_digit() || matches!(c, '.' | ',' | '/'); + let sep = crate::i18n::decimal_separator(); + let allowed = |c: char| accepted(c, sep); let mut stale = false; let dropped = ui.input_mut(|i| { let mut dropped = false; i.events.retain_mut(|e| match e { - egui::Event::Text(t) => { - let mut kept = String::new(); - for c in t.chars() { - let mut next = text.clone(); - next.drain(sel.0..sel.1); - next.insert(sel.0, c); - if c.is_ascii_digit() || (allowed(c) && !violates(&next.iter().collect::())) { - text = next; - sel = (sel.0 + 1, sel.0 + 1); - kept.push(c); - } - } - dropped |= kept.chars().count() != t.chars().count(); - *t = kept; - !t.is_empty() - } - egui::Event::Paste(t) => { + egui::Event::Text(t) | egui::Event::Paste(t) => { let kept: String = t.chars().filter(|&c| allowed(c)).collect(); dropped |= kept.chars().count() != t.chars().count(); - text.drain(sel.0..sel.1); - for (n, c) in kept.chars().enumerate() { - text.insert(sel.0 + n, c); + // Nothing kept: the event goes, and the text stays as it is. + if !kept.is_empty() { + text.drain(sel.0..sel.1); + for (n, c) in kept.chars().enumerate() { + text.insert(sel.0 + n, c); + } + let at = sel.0 + kept.chars().count(); + sel = (at, at); } - let at = sel.0 + kept.chars().count(); - sel = (at, at); *t = kept; !t.is_empty() } @@ -181,6 +175,9 @@ fn drop_unwanted_chars(ui: &Ui, id: Id, shown: &str) -> bool { }); if stale { text.clear(); + // Lost for good, until the field is left or shows another value: what is typed from here on + // is only part of the text. + ui.data_mut(|d| d.insert_temp(lost_id(id), shown.to_owned())); } ui.data_mut(|d| d.insert_temp(mirror, (shown.to_owned(), text.iter().collect::()))); dropped @@ -191,9 +188,24 @@ fn mirror_id(id: Id) -> Id { id.with("pc-zoom-field-text") } -/// Call right before the field's `DragValue` is added; `id` is that `DragValue`'s id and `shown` the -/// text it shows when nothing was typed yet. -pub(crate) fn before(ui: &Ui, id: Id, shown: &str) -> Guard { +/// Where this module notes that its copy of the text lost track of it (with the `shown` it was +/// kept for), so the copy is never written back over the real text ([`rewrite`]). +fn lost_id(id: Id) -> Id { + id.with("pc-zoom-field-text-lost") +} + +/// Drops the copy of the typed text, and with it the note that it was lost. +fn forget_text(ui: &Ui, id: Id) { + ui.data_mut(|d| { + d.remove_temp::<(String, String)>(mirror_id(id)); + d.remove_temp::(lost_id(id)); + }); +} + +/// Call right before the field's `DragValue` is added; `id` is that `DragValue`'s id, `shown` the +/// text it shows when nothing was typed yet, and `canon` writes a typed text as the field would +/// show the zoom Enter makes of it (`None`: it makes none). +pub(crate) fn before(ui: &Ui, id: Id, shown: &str, canon: &dyn Fn(&str) -> Option) -> Guard { let ctx = ui.ctx(); let pass = ctx.cumulative_pass_nr(); let focused = ui.memory(|m| m.has_focus(id)); @@ -208,7 +220,7 @@ pub(crate) fn before(ui: &Ui, id: Id, shown: &str) -> Guard { }; // Only the field that owns the keyboard takes Esc: any other must leave it to whoever wants it. if owner && (ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) | raw_esc(ui)) { - ui.data_mut(|d| d.remove_temp::<(String, String)>(mirror_id(id))); + forget_text(ui, id); return Guard { esc: true, veto: true, ..Default::default() }; } // The focus left before the field was drawn, and no click took it (egui drops the focus on @@ -216,7 +228,7 @@ pub(crate) fn before(ui: &Ui, id: Id, shown: &str) -> Guard { // the copy of the typed text is dropped. Nothing vetoes the `DragValue` here, so a click away // still applies what was typed. if !focused { - ui.data_mut(|d| d.remove_temp::<(String, String)>(mirror_id(id))); + forget_text(ui, id); } // A click that keeps what was typed (pasteboard, title bar, open menu), or a window that has // lost the keyboard: whatever egui does with the typed text, it does not reach the zoom. This @@ -246,6 +258,7 @@ pub(crate) fn before(ui: &Ui, id: Id, shown: &str) -> Guard { if tab { ctx.memory_mut(|m| m.move_focus(FocusDirection::None)); request_alert(ctx); + rewrite(ui, id, shown, canon); select_all_by_key(ui); ctx.data_mut(|d| d.insert_temp(select_until_id(), pass + 3)); ctx.request_repaint(); @@ -274,6 +287,7 @@ pub(crate) fn before(ui: &Ui, id: Id, shown: &str) -> Guard { ctx.options_mut(|o| o.input_options.surrender_focus_on = SurrenderFocusOn::Never); // Selected when the button goes down and when it comes up, not on every frame it is held. if ui.input(|i| i.pointer.any_pressed() || i.pointer.any_released()) { + rewrite(ui, id, shown, canon); select_all_by_key(ui); } return Guard { restore: Some(prev), veto: true, ..Default::default() }; @@ -281,6 +295,28 @@ pub(crate) fn before(ui: &Ui, id: Id, shown: &str) -> Guard { Guard { veto, ..Default::default() } } +/// Writes the typed text as the field shows its zoom ([`canonical`]), as Photoshop does on Tab and +/// on a click that keeps it: all of it is selected and replaced in this frame's input. +fn rewrite(ui: &Ui, id: Id, shown: &str, canon: &dyn Fn(&str) -> Option) { + // The copy lost track of the text (an undo, a word deletion): the text is only selected. + if ui.data(|d| d.get_temp::(lost_id(id))).is_some_and(|from| from == shown) { + return; + } + let mirror = mirror_id(id); + let text = ui.data(|d| d.get_temp::<(String, String)>(mirror)).filter(|(from, _)| from == shown).map_or_else(|| shown.to_owned(), |(_, t)| t); + let Some(new) = canonical(&text, canon) else { return }; + select_all_by_key(ui); + ui.input_mut(|i| i.events.push(egui::Event::Text(new.clone()))); + ui.data_mut(|d| d.insert_temp(mirror, (shown.to_owned(), new))); +} + +/// What [`rewrite`] puts in place of `text`, when that changes it: `canon` of it, for text that +/// holds a number Enter takes as it is. Text Enter refuses ([`read`]) stays. +fn canonical(text: &str, canon: &dyn Fn(&str) -> Option) -> Option { + let Entry::Number(_) = read(text) else { return None }; + canon(text).filter(|new| new != text && !new.is_empty()) +} + /// Call right after the field's `DragValue` was added. pub(crate) fn after(ui: &Ui, id: Id, guard: Guard) { let ctx = ui.ctx(); @@ -289,7 +325,7 @@ pub(crate) fn after(ui: &Ui, id: Id, guard: Guard) { } if guard.esc { // Esc: the typed text goes, and so does the keyboard, so the field shows the zoom again. - ui.data_mut(|d| d.remove_temp::<(String, String)>(mirror_id(id))); + forget_text(ui, id); ui.memory_mut(|m| m.surrender_focus(id)); ctx.request_repaint(); return; @@ -297,28 +333,73 @@ pub(crate) fn after(ui: &Ui, id: Id, guard: Guard) { if !ui.memory(|m| m.has_focus(id)) { return; } - // Text the rules refuse, which only a paste can bring in: it stays (Enter then restores the zoom), - // but every key or paste into it asks for the alert. - let edited = ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Paste(_)))); - if edited && ui.data(|d| d.get_temp::<(String, String)>(mirror_id(id))).is_some_and(|(_, t)| violates(&t)) { - request_alert(ctx); - } let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|d| d.insert_temp(editing_id(), (id, pass))); } -/// What a zoom field's text must not hold: more than one `.`, more than one `,`, a `,` with a `.` -/// (`1,000.5`), or a `.` with a `/` (`100/5.0`: the decimal separator of a ratio is the comma, -/// `100/5,0`). -fn violates(text: &str) -> bool { - let (points, commas) = (text.matches('.').count(), text.matches(',').count()); - points + commas > 1 || (points > 0 && text.contains('/')) +/// How Enter reads the text of a zoom field. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Entry { + /// At most one decimal separator: this text (`,` made `.`) for the number parser. + Number(String), + /// More than one (`80,,2`, `1,5,2`): an invalid numeric entry. Photoshop says so and then takes + /// the number before the second separator: this text for the parser (`80,` as `80.`), if any. + Invalid(Option), } -/// The text of a zoom field as the number parser must read it: `,` is a decimal point, and text that -/// [`violates`] the rules is no number at all (`None`). -pub(crate) fn parse_ready(text: &str) -> Option { - (!violates(text)).then(|| text.replace(',', ".")) +/// Reads a zoom field's text for Enter: a decimal separator is `,` or `.` (only the system's one +/// can be typed, [`accepted`]), and the text holds at most one. +pub(crate) fn read(text: &str) -> Entry { + let is_sep = |c: char| matches!(c, '.' | ','); + let Some((second, _)) = text.char_indices().filter(|&(_, c)| is_sep(c)).nth(1) else { + return Entry::Number(text.replace(',', ".")); + }; + let lead = text.get(..second).unwrap_or_default(); + Entry::Invalid((!lead.is_empty()).then(|| lead.replace(',', "."))) +} + +/// `text` (a number formatted with `.`) with the system's decimal separator, as the field shows it. +pub(crate) fn localize(text: String) -> String { + match crate::i18n::decimal_separator() { + Some(',') => text.replace('.', ","), + _ => text, + } +} + +fn invalid_entry_id() -> Id { + Id::unique("pc-zoom-field-invalid-entry") +} + +/// The field with `id` read an invalid entry ([`Entry::Invalid`]) this frame; see [`take_invalid`]. +pub(crate) fn note_invalid(ctx: &Context, id: Id) { + ctx.data_mut(|d| d.insert_temp(invalid_entry_id().with(id), true)); +} + +/// Did the field with `id` read an invalid entry this frame ([`note_invalid`])? Taken once. +pub(crate) fn take_invalid(ctx: &Context, id: Id) -> bool { + ctx.data_mut(|d| d.remove_temp::(invalid_entry_id().with(id))).unwrap_or(false) +} + +/// Photoshop's "Invalid numeric entry" message for a field whose range is `range` (in %): [`tick`] +/// opens it in the next frame. +pub(crate) fn request_invalid_entry(ctx: &Context, range: (f32, f32)) { + ctx.data_mut(|d| d.insert_temp(invalid_entry_id(), range)); + ctx.request_repaint(); +} + +/// The message waiting to be shown, with its range (tests). +#[cfg(test)] +pub(crate) fn invalid_entry_pending(ctx: &Context) -> Option<(f32, f32)> { + ctx.data(|d| d.get_temp::<(f32, f32)>(invalid_entry_id())) +} + +/// The English text of the message; `{min}` and `{max}` are the range, with two decimals. +pub const INVALID_ENTRY: &str = "Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted."; + +/// The message for a range, in the UI language and with the system's decimal separator. +pub fn invalid_entry_message((min, max): (f32, f32)) -> String { + let pct = |v: f32| localize(format!("{v:.2}")); + crate::i18n::fmt(tl!(INVALID_ENTRY), &[("min", &pct(min)), ("max", &pct(max))]) } fn editing_field(ctx: &Context) -> Option { @@ -422,8 +503,18 @@ pub(crate) fn track_pasteboard(ctx: &Context, pressed: bool) { // ---- What needs the application: services and the document's geometry. ---- -/// Once per frame, before the panels: plays a requested alert and follows a press on the pasteboard. +/// Once per frame, before the panels: shows a requested "Invalid numeric entry" message, plays a +/// requested alert and follows a press on the pasteboard. pub fn tick(app: &mut crate::PhotocraftApp, ctx: &Context) { + if let Some(range) = ctx.data_mut(|d| d.remove_temp::<(f32, f32)>(invalid_entry_id())) { + let message = invalid_entry_message(range); + // One commit can be read in more than one pass of a frame: one message, not a stack of them. + let open = + app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !open { + app.ui.open_dialog(crate::state::DialogKind::Error, serde_json::json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + } if ctx.data_mut(|d| d.remove_temp::(alert_id())).unwrap_or(false) // The platform's alert, else its plain beep: an app that only sets `beep` still answers. && let Some(play) = app.services.alert.or(app.services.beep) @@ -468,18 +559,43 @@ mod tests { use super::*; #[test] - fn a_comma_is_a_decimal_point_and_a_point_with_a_ratio_is_invalid() { - assert_eq!(parse_ready("100,90").as_deref(), Some("100.90")); - assert_eq!(parse_ready("100.90").as_deref(), Some("100.90")); - assert_eq!(parse_ready("100/5,0").as_deref(), Some("100/5.0")); - assert_eq!(parse_ready("100/5.0"), None); - assert_eq!(parse_ready("1.5/2"), None); - assert_eq!(parse_ready("1,5/2").as_deref(), Some("1.5/2")); - for refused in ["1,000.5", "1.000,5", "1.5.2", "1,5,2", "1,5/2,5"] { - assert_eq!(parse_ready(refused), None, "{refused}"); + fn enter_reads_one_separator_and_the_number_before_a_second_one() { + let number = |t: &str| Entry::Number(t.into()); + assert_eq!(read("100,90"), number("100.90")); + assert_eq!(read("100.90"), number("100.90")); + assert_eq!(read("100/5,0"), number("100/5.0")); + assert_eq!(read("100/5.0"), number("100/5.0")); + assert_eq!(read("45"), number("45")); + assert_eq!(read(""), number("")); + let invalid = |t: Option<&str>| Entry::Invalid(t.map(str::to_owned)); + assert_eq!(read("80,,2"), invalid(Some("80."))); + assert_eq!(read("1,5,2"), invalid(Some("1.5"))); + assert_eq!(read("1,000.5"), invalid(Some("1.000"))); + assert_eq!(read("100/5,0,1"), invalid(Some("100/5.0"))); + assert_eq!(read(",,"), invalid(Some("."))); + assert_eq!(read("..5"), invalid(Some("."))); + } + + #[test] + fn only_the_systems_decimal_separator_can_be_typed() { + for (sep, point, comma) in [(Some(','), false, true), (Some('.'), true, false), (None, true, true)] { + assert_eq!(accepted('.', sep), point, "{sep:?}"); + assert_eq!(accepted(',', sep), comma, "{sep:?}"); + assert!(accepted('7', sep) && accepted('/', sep) && !accepted('%', sep) && !accepted('a', sep)); } } + #[test] + fn the_invalid_entry_message_names_the_range_with_the_systems_separator() { + let want = |s: &str| format!("Invalid numeric entry. An integer between {s} is required. Previous value was inserted."); + crate::i18n::with_decimal_separator(Some(','), || { + assert_eq!(invalid_entry_message((0.25, 12800.0)), want("0,25% and 12800,00%")); + assert_eq!(localize("33.33".into()), "33,33"); + }); + crate::i18n::with_decimal_separator(Some('.'), || assert_eq!(invalid_entry_message((0.25, 12800.0)), want("0.25% and 12800.00%"))); + assert_eq!(localize("33.33".into()), "33.33", "unknown: as formatted"); + } + #[test] fn the_title_bar_keeps_a_click_wherever_it_is_drawn() { let ctx = Context::default(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 51f6d1872f5..6e22f1fe8fc 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -23,7 +23,9 @@ mod catalog; mod system; -pub use system::system_lang; +#[cfg(test)] +pub(crate) use system::with_decimal_separator; +pub use system::{decimal_separator, system_lang}; use std::cell::Cell; use std::sync::OnceLock; diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ad024ccd973..b64e36d300a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4235,3 +4235,4 @@ cameraRaw Dehaze Odstranění oparu Font size presets Předvolby velikosti písma Leading presets Předvolby prokladu Tracking presets Předvolby prostrkání + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Neplatná číselná hodnota. Je vyžadováno celé číslo mezi {min}% a {max}%. Byla vložena předchozí hodnota. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c1dfc027ed9..579dd9f7439 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3509,3 +3509,4 @@ curves Smooth Glätten Font size presets Schriftgrößen-Vorgaben Leading presets Zeilenabstand-Vorgaben Tracking presets Laufweiten-Vorgaben + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Ungültige Zahleneingabe. Es ist eine ganze Zahl zwischen {min}% und {max}% erforderlich. Der vorherige Wert wurde eingesetzt. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b2b35dbbdce..6a8e24e2fcd 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4188,3 +4188,4 @@ curves Smooth Εξομάλυνση Font size presets Προεπιλογές μεγέθους γραμματοσειράς Leading presets Προεπιλογές διάστιχου Tracking presets Προεπιλογές διαστήματος χαρακτήρων + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Μη έγκυρη αριθμητική τιμή. Απαιτείται ακέραιος αριθμός μεταξύ {min}% και {max}%. Εισήχθη η προηγούμενη τιμή. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b42f3be02cc..1068678b87c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4447,3 +4447,4 @@ navigator Zoom Zoom Font size presets Valores predefinidos de tamaño de fuente Leading presets Valores predefinidos de interlineado Tracking presets Valores predefinidos de tracking + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Entrada numérica no válida. Se requiere un número entero entre {min}% y {max}%. Se ha insertado el valor anterior. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3bad30d474f..e24a5ece002 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4527,3 +4527,4 @@ shape Appearance Apparence Font size presets Tailles de police prédéfinies Leading presets Interlignages prédéfinis Tracking presets Approches prédéfinies + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Entrée numérique non valide. Un entier compris entre {min}% et {max}% est requis. La valeur précédente a été insérée. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3d6ddab7cb6..f259e73986b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -563,3 +563,4 @@ cameraRaw Yellow पीला Target लक्ष्य Units इकाइयाँ Demosaic डिमोज़ेक + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. अमान्य संख्यात्मक प्रविष्टि। {min}% और {max}% के बीच एक पूर्णांक आवश्यक है। पिछला मान डाला गया। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d632cb52f16..e49bf3ed170 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4399,3 +4399,4 @@ cameraRaw Yellow Sárga Font size presets Betűméret-előbeállítások Leading presets Sorköz-előbeállítások Tracking presets Betűköz-előbeállítások + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Érvénytelen számbevitel. {min}% és {max}% közötti egész szám szükséges. Az előző érték lett beillesztve. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 771e04e80a5..4387320d717 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3507,3 +3507,4 @@ curves Smooth Haluskan Font size presets Preset ukuran font Leading presets Preset leading Tracking presets Preset tracking + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Entri numerik tidak valid. Diperlukan bilangan bulat antara {min}% dan {max}%. Nilai sebelumnya telah disisipkan. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b1598ac237e..8bee64aa8f0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4602,3 +4602,4 @@ shape Appearance Aspetto Font size presets Predefiniti dimensione font Leading presets Predefiniti interlinea Tracking presets Predefiniti spaziatura + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Valore numerico non valido. È richiesto un numero intero compreso tra {min}% e {max}%. È stato inserito il valore precedente. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 435813b0c7e..a7067eb2a05 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4164,3 +4164,4 @@ curves Smooth スムーズ Font size presets フォントサイズのプリセット Leading presets 行送りのプリセット Tracking presets トラッキングのプリセット + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. 無効な数値です。{min}% から {max}% までの整数が必要です。以前の値が挿入されました。 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 30ab8cb165f..35a45b17d39 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3704,3 +3704,4 @@ curves Smooth 매끄럽게 Font size presets 글꼴 크기 사전 설정 Leading presets 행간 사전 설정 Tracking presets 자간 사전 설정 + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. 잘못된 숫자 입력입니다. {min}%에서 {max}% 사이의 정수가 필요합니다. 이전 값이 입력되었습니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d03260ecaf8..478672032f4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4245,3 +4245,4 @@ curves Smooth Vloeiend maken Font size presets Voorinstellingen lettergrootte Leading presets Voorinstellingen interlinie Tracking presets Voorinstellingen spatiëring + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Ongeldige numerieke invoer. Er is een geheel getal tussen {min}% en {max}% vereist. De vorige waarde is ingevoegd. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ba41a4e34d4..26c62dbe043 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4105,3 +4105,4 @@ curves Smooth Wygładź Font size presets Ustawienia wstępne rozmiaru czcionki Leading presets Ustawienia wstępne interlinii Tracking presets Ustawienia wstępne światła + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Nieprawidłowa wartość liczbowa. Wymagana jest liczba całkowita od {min}% do {max}%. Wstawiono poprzednią wartość. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f3335cd9c6e..41628eb4281 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4415,3 +4415,4 @@ layerLabel No Color Sem cor Font size presets Predefinições de tamanho da fonte Leading presets Predefinições de entrelinha Tracking presets Predefinições de tracking + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Entrada numérica inválida. É necessário um número inteiro entre {min}% e {max}%. O valor anterior foi inserido. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b74c3983129..8cc0f7d83d8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4688,3 +4688,4 @@ shape Appearance Оформление Font size presets Наборы размеров шрифта Leading presets Наборы интерлиньяжа Tracking presets Наборы трекинга + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Недопустимое числовое значение. Требуется целое число от {min}% до {max}%. Вставлено предыдущее значение. diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index a81eb06da2d..5c5dd06aa96 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4557,3 +4557,4 @@ shape Appearance Izgled Font size presets Unapred podešene veličine fonta Leading presets Unapred podešeni proredi Tracking presets Unapred podešeni razmaci slova + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Neispravan numerički unos. Potreban je ceo broj između {min}% i {max}%. Umetnuta je prethodna vrednost. diff --git a/crates/ui-egui/src/i18n/system.rs b/crates/ui-egui/src/i18n/system.rs index 25cc9fec4f8..5c7a258a5e9 100644 --- a/crates/ui-egui/src/i18n/system.rs +++ b/crates/ui-egui/src/i18n/system.rs @@ -57,6 +57,69 @@ fn detect_system_tags() -> Vec { Vec::new() } +/// The decimal separator of the system's number format (Windows: Region › Decimal symbol), when it +/// is `.` or `,` and can be read: Photoshop's numeric fields take only that one (a German Windows +/// refuses a typed `.`). `None` where it can't be read (macOS, Linux and the web for now, or another +/// symbol): the fields then take both. +pub fn decimal_separator() -> Option { + #[cfg(test)] + { + TEST_DECIMAL.get() + } + #[cfg(not(test))] + { + static SYSTEM: std::sync::OnceLock> = std::sync::OnceLock::new(); + *SYSTEM.get_or_init(detect_decimal_separator) + } +} + +/// `.` or `,` as a decimal separator; anything else (empty, `٫`, two characters) is not one. +#[cfg_attr(not(any(test, target_os = "windows")), allow(dead_code))] +fn separator_from(text: &str) -> Option { + match text.trim() { + "." => Some('.'), + "," => Some(','), + _ => None, + } +} + +/// The user's own number format (`HKCU\Control Panel\International\sDecimal`, where Windows keeps +/// the decimal symbol of the format chosen in Region, with any change made to it), read through a +/// safe binding. +#[cfg(target_os = "windows")] +fn detect_decimal_separator() -> Option { + use winsafe::{self as w, co}; + match w::HKEY::CURRENT_USER.RegGetValue(Some("Control Panel\\International"), Some("sDecimal"), co::RRF::RT_REG_SZ) { + Ok(w::RegistryValue::Sz(text)) => separator_from(&text), + _ => None, + } +} + +#[cfg(all(not(test), not(target_os = "windows")))] +fn detect_decimal_separator() -> Option { + None +} + +#[cfg(test)] +thread_local! { + // Tests take both separators unless they choose one (`with_decimal_separator`), whatever the + // developer's own number format is. + static TEST_DECIMAL: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Runs `run` as on a system whose decimal separator is `sep` (`None`: unknown, both taken). +#[cfg(test)] +pub(crate) fn with_decimal_separator(sep: Option, run: impl FnOnce() -> R) -> R { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + TEST_DECIMAL.set(self.0); + } + } + let _restore = Restore(TEST_DECIMAL.replace(sep)); + run() +} + #[cfg(test)] thread_local! { // Keep ordinary tests independent of the developer's locale, without mutating OS or @@ -119,6 +182,27 @@ mod tests { assert_eq!(system_lang(), Lang::EN); } + #[test] + fn only_a_point_or_a_comma_is_a_decimal_separator() { + assert_eq!(separator_from(","), Some(',')); + assert_eq!(separator_from(" . "), Some('.')); + for other in ["", "\u{66b}", ",,", "'", "x"] { + assert_eq!(separator_from(other), None, "{other:?}"); + } + assert_eq!(decimal_separator(), None, "tests take both unless they choose"); + with_decimal_separator(Some(','), || assert_eq!(decimal_separator(), Some(','))); + assert_eq!(decimal_separator(), None); + } + + /// The real Windows number format is read (the developer's or CI's: `,` or `.`). + #[cfg(target_os = "windows")] + #[test] + fn the_windows_number_format_has_a_decimal_separator() { + let sep = detect_decimal_separator(); + eprintln!("Windows decimal separator: {sep:?}"); + assert!(matches!(sep, Some('.' | ',')), "{sep:?}"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn native_locale_results_are_bounded_and_trimmed() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f5b9d13fd6f..5e883df029d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4213,3 +4213,4 @@ cameraData Lens Lens Font size presets Yazı tipi boyutu hazır ayarları Leading presets Satır aralığı hazır ayarları Tracking presets İzleme hazır ayarları + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Geçersiz sayısal giriş. {min}% ile {max}% arasında bir tam sayı gerekiyor. Önceki değer eklendi. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8d911b19a83..e7b9adb9d40 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4198,3 +4198,4 @@ curves Smooth Згладити Font size presets Набори розмірів шрифту Leading presets Набори інтерліньяжу Tracking presets Набори трекінгу + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Неприпустиме числове значення. Потрібне ціле число від {min}% до {max}%. Вставлено попереднє значення. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f3486629750..98d37c2620c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3983,3 +3983,4 @@ curves Smooth Làm mượt Font size presets Cỡ chữ đặt sẵn Leading presets Giãn dòng đặt sẵn Tracking presets Khoảng cách chữ đặt sẵn + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. Giá trị số không hợp lệ. Cần một số nguyên từ {min}% đến {max}%. Đã chèn giá trị trước đó. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9f437214ad..f6cfa9e6051 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3168,3 +3168,4 @@ curves Smooth 平滑 Font size presets 字号预设 Leading presets 行距预设 Tracking presets 字距调整预设 + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. 数值输入无效。需要介于 {min}% 和 {max}% 之间的整数。已插入先前的值。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9d46dcb21e8..f463adebf9d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3124,3 +3124,4 @@ curves Smooth 平滑 Font size presets 字體大小預設 Leading presets 行距預設 Tracking presets 字距調整預設 + Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. 數值輸入無效。需要介於 {min}% 和 {max}% 之間的整數。已插入先前的值。 diff --git a/crates/ui-egui/src/status_bar_tests.rs b/crates/ui-egui/src/status_bar_tests.rs index 9d4bcd42ea0..551eee0e61b 100644 --- a/crates/ui-egui/src/status_bar_tests.rs +++ b/crates/ui-egui/src/status_bar_tests.rs @@ -260,3 +260,48 @@ fn a_typed_zoom_leaves_nothing_for_the_next_zoom_and_lands_exactly() { assert_eq!(h.state().ui.views[0].zoom, 1.0, "Actual Pixels after a typed 1600 %, animated {animated}"); } } + +/// `80,,2` typed into the status bar's zoom field: Enter opens Photoshop's "Invalid numeric entry" +/// message (the field's range with the system's decimal separator) and applies 80 %. +#[test] +fn a_second_separator_in_the_zoom_field_opens_the_invalid_entry_message_and_applies_the_leading_number() { + crate::i18n::with_decimal_separator(Some(','), || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1080, "height": 1080, "resolution": 72, "background": "white"})).unwrap(); + app.sync_views(); + let mut h = Harness::builder().with_size(SIZE).build_ui_state( + |ui, app: &mut PhotocraftApp| { + crate::zoom_field::tick(app, &ui.ctx().clone()); + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::panels::status_bar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, ThemeKind::ProMedium); + h.run_steps(3); + let range = crate::zoom_levels::percent_range(&h.state().ui.views[0]); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run_steps(2); + for c in "80,,2".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run_steps(1); + } + assert!(h.state().ui.dialogs.is_empty(), "no message while typing"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().ui.views[0].zoom, 0.8, "the number before the second separator"); + let messages: Vec = h + .state() + .ui + .dialogs + .iter() + .filter(|d| d.kind == crate::state::DialogKind::Error) + .filter_map(|d| d.fields.get("message")?.as_str().map(String::from)) + .collect(); + let pct = |v: f32| format!("{v:.2}").replace('.', ","); + let want = + format!("Invalid numeric entry. An integer between {}% and {}% is required. Previous value was inserted.", pct(*range.start()), pct(*range.end())); + assert_eq!(messages, [want], "one message, in the dialog the app shows errors in"); + }); +} diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index 7e6c9709d6e..c0030bd9c8f 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -413,17 +413,26 @@ fn number_edit( // Esc, Tab, a click on the pasteboard, the title bar or an open menu, and a window that lost the // keyboard leave what was typed unapplied (zoom_field.rs). This runs before the field registers its interest in // the focus: Tab would otherwise already have handed the focus on to the next widget. - let guard = if hold_typed { - let shown = match decimals { - Some(d) => fmt_num_prec(f64::from(*value), d), - None if fine => fmt_num2(f64::from(*value)), - None => fmt_num(f64::from(*value)), + // A zoom field shows its number with the system's decimal separator (`12,5` on a German + // Windows), as Photoshop does, so the text it shows is one that can be typed. + let format = move |v: f64| { + let text = match decimals { + Some(d) => fmt_num_prec(v, d), + None if fine => fmt_num2(v), + None => fmt_num(v), }; + if hold_typed { crate::zoom_field::localize(text) } else { text } + }; + let guard = if hold_typed { + let shown = format(f64::from(*value)); // The zoom field reads the keys here, before the check below: oversized events go first. if ui.memory(|m| m.has_focus(id)) { drop_oversized_input(ui); } - crate::zoom_field::before(ui, id, &shown) + // Tab and a click that keeps the typed number write it as the zoom Enter would make of it. + let (lo, hi) = (f64::from(*range.start()), f64::from(*range.end())); + let canon = move |t: &str| zoom_number(t, units).filter(|v| v.is_finite()).map(|v| format(if lo <= hi { v.clamp(lo, hi) } else { v })); + crate::zoom_field::before(ui, id, &shown, &canon) } else { Default::default() }; @@ -457,11 +466,7 @@ fn number_edit( .clamp_existing_to_range(false) // A warp is an absolute-position jump. The scoped scrub below removes that jump. .speed(if wrapped_drag { 0.0 } else { speed }) - .custom_formatter(move |v, _| match decimals { - Some(d) => fmt_num_prec(v, d), - None if fine => fmt_num2(v), - None => fmt_num(v), - }) + .custom_formatter(move |v, _| format(v)) .update_while_editing(!math && !hold_typed) // Focus is read when parsing, not above: Tab hands it on inside `ui.add`. .custom_parser(move |s| { @@ -469,21 +474,24 @@ fn number_edit( if s.chars().nth(NUMERIC_INPUT_LIMIT).is_some() { return None; } - // A zoom field takes `,` as a decimal point (`100,90` is `100.90`), and no `.` next - // to a `/` (`100/5.0` is invalid, `100/5,0` is 2000 %), as Photoshop does. + // A zoom field takes `,` or `.` as its decimal point (`100,90` is `100.90`) and reads + // a division as a ratio (`1/2` is 50 %, `100/5,0` is 2000 %), as Photoshop does. With + // a second separator (`80,,2`) it says the entry is invalid and takes the number + // before it (80 %). let ready = if hold_typed { - let Some(ready) = crate::zoom_field::parse_ready(s) else { - ctx.data_mut(|d| d.insert_temp(held, false)); - return None; - }; - ready + match crate::zoom_field::read(s) { + crate::zoom_field::Entry::Number(ready) => ready, + crate::zoom_field::Entry::Invalid(lead) => { + crate::zoom_field::note_invalid(&ctx, id); + ctx.data_mut(|d| d.insert_temp(held, false)); + return lead.and_then(|lead| zoom_number(&lead, units)); + } + } } else { s.to_owned() }; let s = ready.as_str(); - let v = parse_num_in(s, units); - // A zoom field reads a division as a ratio, as Photoshop does: 1/2 is 50 %, 5/2 is 250 %. - let v = if hold_typed && s.contains('/') { v.map(|r| r * 100.0) } else { v }; + let v = if hold_typed { zoom_number(s, units) } else { parse_num_in(s, units) }; if ctx.memory(|m| m.has_focus(id)) && plain(s).is_none() { // Still typing arithmetic: hold it, and stop applying keystrokes once it parses. ctx.data_mut(|d| d.insert_temp(held, v.is_some())); @@ -498,6 +506,10 @@ fn number_edit( if typed != before && (scrub || !guard.vetoes_typed()) { *value = typed; } + // An invalid entry that was applied (not one a vetoed commit read) gets Photoshop's message. + if crate::zoom_field::take_invalid(ui.ctx(), id) && !guard.vetoes_typed() { + crate::zoom_field::request_invalid_entry(ui.ctx(), (*range.start(), *range.end())); + } crate::zoom_field::after(ui, id, guard); } if wrap_drag { @@ -512,6 +524,15 @@ fn number_edit( resp } +/// The zoom a zoom field's text stands for, with at most one decimal separator (`,` or `.`): a +/// number, or a ratio (`1/2` is 50 %, `5/2` is 250 %). `None` when it is neither, or holds a +/// second separator (`zoom_field::read` takes that apart). +fn zoom_number(text: &str, units: crate::numeric_expression::Units) -> Option { + let crate::zoom_field::Entry::Number(ready) = crate::zoom_field::read(text) else { return None }; + let v = parse_num_in(&ready, units); + if ready.contains('/') { v.map(|r| r * 100.0) } else { v } +} + /// Increments a numerical field with the up/down arrow keys. Increments by 1 by default, 10 with shift, and 0.1 with ctrl/cmd. /// Returns the amount to add, and what to round the value to first. fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32) -> (f32, f32) { diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index 59133da3852..d4c1bd81b31 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -977,128 +977,230 @@ fn a_zoom_field_reads_a_division_as_a_ratio() { } } -/// `,` is a decimal point in a zoom field, like `.`: `100,90` is `100.90`. +/// Where the system's decimal separator is not known, `,` and `.` are both a decimal point in a +/// zoom field: `100,90` is `100.90`. #[test] fn a_zoom_field_reads_a_comma_as_a_decimal_point() { - for (typed, after) in [("100,90", 100.9), ("100.90", 100.9), ("12,5", 12.5), ("200,", 200.0)] { + for (typed, after) in [("100,90", 100.9), ("100.90", 100.9), ("12,5", 12.5), ("200,", 200.0), ("100/5,0", 2000.0), ("100/5.0", 2000.0)] { let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); click_and_type(&mut h, typed); + assert!(!crate::zoom_field::alert_pending(&h.ctx), "{typed}: silent"); h.key_press(egui::Key::Enter); h.run(); assert_eq!(*h.state(), (after, 1), "{typed}"); } } -/// With a `/`, only `,` is a decimal point: `100/5,0` is 2000 %, `100/5.0` is not a number. +/// The system's decimal separator is the zoom field's, as in Photoshop: on a German Windows a typed +/// `.` is refused with the alert (and not inserted) and `,` is the decimal point; on an English one +/// the other way round. Ratios follow it (`100/5,0` is 2000 % on German). #[test] -fn a_zoom_field_takes_a_comma_but_no_point_in_a_ratio() { - let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); - click_and_type(&mut h, "100/5,0"); - assert!(!crate::zoom_field::alert_pending(&h.ctx), "a comma in a ratio is silent"); +fn a_zoom_field_takes_only_the_systems_decimal_separator() { + // (system separator, typed, alert, zoom after Enter) + let cases = [ + (',', "12,5", false, 12.5), + (',', "12.5", true, 125.0), + (',', "100/5,0", false, 2000.0), + (',', "100/5.0", true, 200.0), + ('.', "12.5", false, 12.5), + ('.', "12,5", true, 125.0), + ('.', "100/5.0", false, 2000.0), + ('.', "100/5,0", true, 200.0), + ]; + for (sep, typed, alert, after) in cases { + crate::i18n::with_decimal_separator(Some(sep), || { + let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + assert_eq!(crate::zoom_field::alert_pending(&h.ctx), alert, "{sep} {typed}: alert"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (after, 1), "{sep} {typed}"); + assert_eq!(crate::zoom_field::invalid_entry_pending(&h.ctx), None, "{sep} {typed}: a valid entry"); + }); + } +} + +/// The field shows its zoom with the system's decimal separator (Photoshop's `12,5%`), so its own +/// text is one that can be typed. +#[test] +fn a_zoom_field_shows_the_systems_decimal_separator() { + use egui_kittest::kittest::Queryable; + for (sep, shown) in [(Some(','), "12,5"), (Some('.'), "12.5"), (None, "12.5")] { + crate::i18n::with_decimal_separator(sep, || { + let mut h = zoom_harness(12.5, EscEater::Shortcuts, false); + h.run(); + let text = h.get_by_role(egui::accesskit::Role::SpinButton).value(); + assert!(text.as_deref().is_some_and(|t| t.contains(shown)), "{sep:?}: {text:?}"); + }); + } +} + +/// A second separator can be typed (`80,,2`), silently. Enter asks for Photoshop's "Invalid numeric +/// entry" message, with the field's range, and applies the number before the second separator. +#[test] +fn a_second_separator_is_typed_and_enter_applies_the_number_before_it_with_the_message() { + // (system separator, typed, zoom after Enter) + let cases = [ + (Some(','), "80,,2", 80.0), + (Some(','), "1,5,2", 1.5), + (Some(','), "100/5,0,1", 2000.0), + (Some('.'), "80..2", 80.0), + (None, "1,000.5", 1.0), + (None, "12.5,", 12.5), + ]; + for (sep, typed, after) in cases { + crate::i18n::with_decimal_separator(sep, || { + let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + assert!(!crate::zoom_field::alert_pending(&h.ctx), "{typed}: typed, silently"); + assert_eq!(crate::zoom_field::invalid_entry_pending(&h.ctx), None, "{typed}: no message before Enter"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (after, 1), "{typed}: the number before the second separator"); + assert_eq!(crate::zoom_field::invalid_entry_pending(&h.ctx), Some((0.0, 12800.0)), "{typed}: the message, with the range"); + }); + } + // The number before it is the zoom already: nothing changes, but the message still comes. + let mut h = zoom_harness(80.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "80,,2"); h.key_press(egui::Key::Enter); h.run(); - assert_eq!(*h.state(), (2000.0, 1)); + assert_eq!(*h.state(), (80.0, 0)); + assert!(crate::zoom_field::invalid_entry_pending(&h.ctx).is_some()); + // No number before it at all: the zoom stays, with the message. + let mut h = zoom_harness(80.0, EscEater::Shortcuts, false); + click_and_type(&mut h, ",,5"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (80.0, 0)); + assert!(crate::zoom_field::invalid_entry_pending(&h.ctx).is_some()); } -/// At most one `.` or `,`, never both, and no `.` next to a `/`: the key is dropped, with the alert. +/// Esc, or Tab, with a second separator typed: no message, nothing applied. #[test] -fn a_zoom_field_types_away_a_second_separator_and_a_point_in_a_ratio() { - // (typed, zoom after Enter) - for (typed, after) in - [("1.5.2", 1.52), ("1,5,2", 1.52), ("1,5.2", 1.52), ("1.5,2", 1.52), ("1,000.5", 1.0005), ("1.5/2", 1.52), ("100/5.0", 200.0), ("100/5,0", 2000.0)] - { +fn esc_and_tab_with_a_second_separator_show_no_message() { + for key in [egui::Key::Escape, egui::Key::Tab] { let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); - click_and_type(&mut h, typed); + click_and_type(&mut h, "80,,2"); + h.key_press(key); + h.run_steps(2); + assert_eq!(*h.state(), (50.0, 0), "{key:?}"); + assert_eq!(crate::zoom_field::invalid_entry_pending(&h.ctx), None, "{key:?}"); + } +} + +/// A paste is filtered like typing: the other separator is dropped with the alert (`100/5.0` on a +/// German system is `100/50`), and a second separator stays for Enter's message. +#[test] +fn a_paste_follows_the_typing_rules() { + crate::i18n::with_decimal_separator(Some(','), || { + let mut h = zoom_harness(150.0, EscEater::Shortcuts, false); + zoom_field_node(&h).click(); + h.run(); + h.event(egui::Event::Paste("100/5.0".into())); + h.run(); + assert!(crate::zoom_field::alert_pending(&h.ctx), "the `.` asks for the alert"); + assert_eq!(*h.state(), (150.0, 0), "and the paste applies nothing yet"); h.key_press(egui::Key::Enter); h.run(); - assert_eq!(*h.state(), (after, 1), "{typed}"); - } - let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); - click_and_type(&mut h, "1,5"); - assert!(!crate::zoom_field::alert_pending(&h.ctx), "the first separator is silent"); - h.event(egui::Event::Text(".".into())); - h.run(); - assert!(crate::zoom_field::alert_pending(&h.ctx), "a `.` next to the `,` asks for the alert"); + assert_eq!(*h.state(), (200.0, 1), "100/50"); + assert_eq!(crate::zoom_field::invalid_entry_pending(&h.ctx), None); + + let mut h = zoom_harness(150.0, EscEater::Shortcuts, false); + zoom_field_node(&h).click(); + h.run(); + h.event(egui::Event::Paste("80,,2".into())); + h.run(); + assert!(!crate::zoom_field::alert_pending(&h.ctx), "a second separator is pasted silently, as it is typed"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (80.0, 1)); + assert!(crate::zoom_field::invalid_entry_pending(&h.ctx).is_some(), "Enter's message"); + }); } -/// The rules follow the text through Backspace and the cursor: with the `.` deleted, a new one is -/// silent; with it still there, it is typed away. +/// Tab writes the typed number as the field shows a zoom (`045` is `45`, `45,0` is `45`, `1/2` is +/// `50`, past the range is its end) and selects it, without applying it. #[test] -fn a_zoom_field_follows_backspace_and_the_cursor_when_it_checks_the_separators() { - let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); - click_and_type(&mut h, "1.5"); - h.key_press(egui::Key::ArrowLeft); - h.run(); +fn tab_writes_the_typed_number_as_the_zoom_it_makes() { + use egui_kittest::kittest::Queryable; + for (typed, shown) in [("045", "45"), ("45,0", "45"), ("45.50", "45.5"), ("1/2", "50"), ("99999", "12800"), ("80,,2", "80,,2")] { + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(*h.state(), (100.0, 0), "{typed}: Tab applies nothing"); + let text = h.get_by_role(egui::accesskit::Role::SpinButton).value(); + assert_eq!(text.as_deref(), Some(shown), "{typed}"); + // Selected: a digit replaces it. + h.event(egui::Event::Text("7".into())); + h.run(); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (7.0, 1), "{typed}: the text was selected"); + } + // With the system's comma, the comma is kept. + crate::i18n::with_decimal_separator(Some(','), || { + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "045,50"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(h.get_by_role(egui::accesskit::Role::SpinButton).value().as_deref(), Some("45,5")); + }); + // The copy follows Backspace: `450` with the `0` deleted is `45`. + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "0450"); h.key_press(egui::Key::Backspace); h.run(); - h.event(egui::Event::Text(".".into())); - h.run(); - assert!(!crate::zoom_field::alert_pending(&h.ctx), "the `.` was deleted, so the new one is silent"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(h.get_by_role(egui::accesskit::Role::SpinButton).value().as_deref(), Some("45")); h.key_press(egui::Key::Enter); h.run(); - assert_eq!(*h.state(), (1.5, 1)); - - let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); - click_and_type(&mut h, "1.5"); - h.key_press(egui::Key::ArrowLeft); - h.run(); - h.event(egui::Event::Text(".".into())); - h.run(); - assert!(crate::zoom_field::alert_pending(&h.ctx), "the `.` is still there, so a second one is typed away"); - h.key_press(egui::Key::Enter); - h.run(); - assert_eq!(*h.state(), (1.5, 1)); + assert_eq!(*h.state(), (45.0, 1), "Enter then applies it"); } -/// When the value changes under the focused field (ArrowUp, another zoom), the field shows the new -/// number, and the separator rules check that number, not the text typed before it. +/// After a key the field's copy of the text can't follow (a word deletion, an undo), Tab only +/// selects the text: it never writes the digits typed since over the whole of it. #[test] -fn a_zoom_field_checks_the_separators_against_a_value_that_changed_under_it() { - let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); - click_and_type(&mut h, "1.5"); - h.key_press(egui::Key::ArrowUp); - h.run(); - assert_eq!(h.state().0, 101.0, "ArrowUp steps the zoom"); - h.key_press(egui::Key::End); - h.run(); - h.event(egui::Event::Text(".".into())); - h.run(); - assert!(!crate::zoom_field::alert_pending(&h.ctx), "101 has no `.` yet: the new one is silent"); - - let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); - click_and_type(&mut h, "1.5"); - h.state_mut().0 = 400.0; - h.run(); - h.key_press(egui::Key::End); - h.run(); - h.event(egui::Event::Text(".".into())); - h.run(); - assert!(!crate::zoom_field::alert_pending(&h.ctx), "another zoom made it 400: the new `.` is silent"); +fn tab_after_a_word_deletion_leaves_the_text_as_it_is() { + use egui_kittest::kittest::Queryable; + for (mods, key) in [(egui::Modifiers::COMMAND, egui::Key::Backspace), (egui::Modifiers::COMMAND, egui::Key::Z)] { + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "450"); + h.key_press(egui::Key::End); + h.run(); + h.key_press_modifiers(mods, key); + h.run(); + h.key_press(egui::Key::End); + h.run(); + for c in "05".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + let typed = h.get_by_role(egui::accesskit::Role::SpinButton).value(); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(h.get_by_role(egui::accesskit::Role::SpinButton).value(), typed, "{key:?}: Tab leaves {typed:?} as it is"); + assert_eq!(*h.state(), (100.0, 0), "{key:?}"); + } } -/// A pasted `100/5.0` stays in the field and asks for the alert; Enter puts the zoom back. +/// A click on the pasteboard writes the typed number like Tab does. #[test] -fn a_pasted_ratio_with_a_point_alerts_and_enter_restores_the_zoom() { - let mut h = zoom_harness(150.0, EscEater::Shortcuts, false); - zoom_field_node(&h).click(); - h.run(); - assert!(!crate::zoom_field::alert_pending(&h.ctx)); - h.event(egui::Event::Paste("100/5.0".into())); - h.run(); - assert!(crate::zoom_field::alert_pending(&h.ctx), "the paste asks for the alert"); - assert_eq!(*h.state(), (150.0, 0), "and applies nothing"); +fn a_click_on_the_pasteboard_writes_the_typed_number_as_the_zoom_it_makes() { + use egui_kittest::kittest::Queryable; + let mut h = zoom_harness(40.0, EscEater::Shortcuts, true); + click_and_type(&mut h, "045,0"); + click_at(&mut h, egui::pos2(250.0, 80.0), egui::PointerButton::Primary); + assert_eq!(*h.state(), (40.0, 0), "the zoom stays"); + assert_eq!(h.get_by_role(egui::accesskit::Role::SpinButton).value().as_deref(), Some("45")); h.key_press(egui::Key::Enter); h.run(); - assert_eq!(*h.state(), (150.0, 0), "Enter keeps the zoom it had"); - // Nothing of the paste is left to come back with the next click and Enter. - zoom_field_node(&h).click(); - h.run(); - h.key_press(egui::Key::Enter); - h.run(); - assert_eq!(*h.state(), (150.0, 0)); + assert_eq!(*h.state(), (45.0, 1)); } -/// Only digits, the two separators and `/` go into a zoom field: any other key (`%` too, which +/// Only digits, the decimal separator and `/` go into a zoom field: any other key (`%` too, which /// is drawn beside the field) asks for the alert and leaves the text as it was. #[test] fn a_zoom_field_takes_digits_and_separators_only() {