diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index b390bbe53c2..cd7ab66d958 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -75,6 +75,8 @@ impl PhotocraftApp { // maximize it into the work area once (#315). work_area::fit_window(ctx); discard_ui::guard_window_close(self, ctx); + // A zoom field being typed in: plays its alert, and notes a click on the pasteboard. + crate::zoom_field::tick(self, ctx); // Background jobs: apply finished ones, keep frames coming, Esc cancels (before the // shortcuts see Esc). if !screen_picker::tick(self, ctx) { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f479e675105..5295afdf0a1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -54,6 +54,7 @@ mod tool_input; mod transform_controls; mod view_xform; pub mod wheel_nav; +pub mod zoom_field; pub mod zoom_hold; pub mod zoom_levels; pub mod zoom_window_fit; diff --git a/crates/ui-egui/src/canvas/zoom_field.rs b/crates/ui-egui/src/canvas/zoom_field.rs new file mode 100644 index 00000000000..2debd40e79c --- /dev/null +++ b/crates/ui-egui/src/canvas/zoom_field.rs @@ -0,0 +1,515 @@ +//! Photoshop's rules for a zoom field (status bar, Navigator) while a number is typed into it. +//! +//! A typed zoom is held until Enter (or a click on something other than the pasteboard). Until +//! 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). +//! * 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. +//! * 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. +//! +//! 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: +//! [`editing`] (the shortcuts must not take Esc or Tab in the frame egui drops the focus), +//! [`is_focused`] (the menu bar must not take Alt) and [`tick`] (plays the alert, and tells the +//! field about a press on the pasteboard, which only the app can recognise). + +use egui::{Context, FocusDirection, Id, Key, Modifiers, SurrenderFocusOn, Ui}; + +fn editing_id() -> Id { + Id::unique("pc-zoom-field-editing") +} + +fn pasteboard_id() -> Id { + Id::unique("pc-zoom-field-pasteboard-press") +} + +fn menu_bar_rect_id() -> Id { + Id::unique("pc-zoom-field-menu-bar-rect") +} + +fn alert_id() -> Id { + Id::unique("pc-zoom-field-alert") +} + +fn taken_key_id() -> Id { + Id::unique("pc-zoom-field-taken-key") +} + +fn keep_pass_id() -> Id { + Id::unique("pc-zoom-field-keep-pass") +} + +fn select_until_id() -> Id { + Id::unique("pc-zoom-field-select-until") +} + +fn title_bar_rect_id() -> Id { + Id::unique("pc-zoom-field-title-bar-rect") +} + +/// What [`before`] decided for this frame, for [`after`] and the field. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Guard { + /// The setting to put back: egui's "surrender focus on" was switched off for this frame. + restore: Option, + /// Esc was pressed in the field: whatever was typed is dropped, the field leaves the keyboard. + esc: bool, + /// Whatever egui does with the typed text this frame, it must not reach the zoom: Esc, Tab, a + /// click that keeps the typed number, a window that has lost the keyboard. + veto: bool, +} + +impl Guard { + /// The field must not apply a typed number this frame (a scrub is not typed and is exempt). + pub(crate) fn vetoes_typed(self) -> bool { + self.veto + } +} + +/// Makes the `TextEdit` of the field being drawn select all of its text, the way Ctrl+A does: +/// the key is put in this frame's input, where the `TextEdit` reads it as typed. +fn select_all_by_key(ui: &Ui) { + let ctrl_a = egui::Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }; + 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. +/// +/// 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. +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); + let mut text: Vec = stored.clone().unwrap_or_else(|| shown.to_owned()).chars().collect(); + let len = text.len(); + let range = egui::TextEdit::load_state(ui.ctx(), id).and_then(|s| s.cursor.char_range()); + // Before the first key the whole number is selected, as the field is reached. + let mut sel = match (&stored, range) { + (Some(_), Some(r)) => { + let (a, b) = (r.primary.index.0, r.secondary.index.0); + (a.min(b).min(len), a.max(b).min(len)) + } + (Some(_), None) => (len, len), + (None, _) => (0, len), + }; + let allowed = |c: char| c.is_ascii_digit() || matches!(c, '.' | ',' | '/'); + 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) => { + 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); + } + let at = sel.0 + kept.chars().count(); + sel = (at, at); + *t = kept; + !t.is_empty() + } + egui::Event::Cut => { + text.drain(sel.0..sel.1); + sel = (sel.0, sel.0); + true + } + egui::Event::Key { key: key @ (Key::Backspace | Key::Delete), pressed: true, modifiers, .. } => { + if modifiers.is_none() || (*key == Key::Backspace && modifiers.shift_only()) { + if sel.0 != sel.1 { + text.drain(sel.0..sel.1); + sel = (sel.0, sel.0); + } else if *key == Key::Backspace && sel.0 > 0 { + text.remove(sel.0 - 1); + sel = (sel.0 - 1, sel.0 - 1); + } else if *key == Key::Delete && sel.0 < text.len() { + text.remove(sel.0); + } + } else { + stale = true; + } + true + } + egui::Event::Key { key: Key::Z | Key::Y, pressed: true, modifiers, .. } => { + stale |= modifiers.command; + true + } + _ => true, + }); + dropped + }); + if stale { + text.clear(); + } + ui.data_mut(|d| d.insert_temp(mirror, (shown.to_owned(), text.iter().collect::()))); + dropped +} + +/// Where this module keeps its copy of the text being edited in the field with `id`. +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 { + let ctx = ui.ctx(); + let pass = ctx.cumulative_pass_nr(); + let focused = ui.memory(|m| m.has_focus(id)); + // Esc: take it (no shortcut, no job cancel, no canvas acts on it), and drop what was typed. + // Whether egui dropped the focus already (the key's own frame) or not, the field applies + // nothing this frame (`Guard::vetoes_typed`) and leaves the keyboard (`after`). + let owner = focused || editing_field(ctx) == Some(id); + // Esc is also looked for in the frame's raw input: something may have consumed it before the + // field was drawn (a shortcut, a job), and egui has dropped the focus on it already. + let raw_esc = |ui: &Ui| { + ui.input(|i| i.raw.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, modifiers, .. } if modifiers.is_none()))) + }; + // 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))); + 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 + // some keys and a shortcut may then eat them, so the `DragValue` cannot rely on seeing them): + // 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))); + } + // 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 + // holds without the focus too (the click may have given it to another field earlier in this + // frame, and egui hands a field its lost focus, with the text, when it is next drawn), and for + // two frames after the click (the focus can go in one frame and be noticed in the next). + let gesture = pasteboard_press(ctx); + if gesture { + ctx.data_mut(|d| d.insert_temp(keep_pass_id(), pass)); + } + let recent = ctx.data(|d| d.get_temp::(keep_pass_id())).is_some_and(|p| pass <= p + 2); + // Enter in the field is a commit of its own, however soon after the click: egui draws few frames + // with the mouse still, so the Enter can land in that window. + let enter = focused && ui.input(|i| i.key_pressed(Key::Enter)); + let veto = (recent && !enter) || ui.input(|i| i.viewport().focused) == Some(false); + if !focused { + return Guard { veto, ..Default::default() }; + } + drop_taken_text(ctx); + if drop_unwanted_chars(ui, id, shown) { + request_alert(ctx); + } + // Tab: egui has already planned the move to the next widget; cancel it. The text is selected + // now, and again in the next frames until something is typed: whatever moves the text cursor + // meanwhile does not undo it. + let tab = ui.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::Tab) | i.consume_key(Modifiers::NONE, Key::Tab)); + if tab { + ctx.memory_mut(|m| m.move_focus(FocusDirection::None)); + request_alert(ctx); + select_all_by_key(ui); + ctx.data_mut(|d| d.insert_temp(select_until_id(), pass + 3)); + ctx.request_repaint(); + return Guard { veto: true, ..Default::default() }; + } + if let Some(until) = ctx.data(|d| d.get_temp::(select_until_id())) { + let acted = ui.input(|i| { + i.events.iter().any(|e| { + matches!( + e, + egui::Event::Text(_) | egui::Event::Paste(_) | egui::Event::Key { pressed: true, .. } | egui::Event::PointerButton { pressed: true, .. } + ) + }) + }); + if acted || pass > until { + ctx.data_mut(|d| d.remove_temp::(select_until_id())); + } else { + select_all_by_key(ui); + ctx.request_repaint(); + } + } + if gesture { + // egui drops the focus of the focused widget when a click lands elsewhere, and the + // `DragValue` then applies the text; for this frame, neither. + let prev = ctx.options(|o| o.input_options.surrender_focus_on); + 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()) { + select_all_by_key(ui); + } + return Guard { restore: Some(prev), veto: true, ..Default::default() }; + } + Guard { veto, ..Default::default() } +} + +/// Call right after the field's `DragValue` was added. +pub(crate) fn after(ui: &Ui, id: Id, guard: Guard) { + let ctx = ui.ctx(); + if let Some(prev) = guard.restore { + ctx.options_mut(|o| o.input_options.surrender_focus_on = prev); + } + 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))); + ui.memory_mut(|m| m.surrender_focus(id)); + ctx.request_repaint(); + return; + } + 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('/')) +} + +/// 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(',', ".")) +} + +fn editing_field(ctx: &Context) -> Option { + let (id, pass) = ctx.data(|d| d.get_temp::<(Id, u64)>(editing_id()))?; + // Drawn with the focus in the last frame (the one before this): in the frame egui drops + // the focus for Esc or Tab, nothing is focused any more, but the field is still the owner. + (pass + 1 >= ctx.cumulative_pass_nr()).then_some(id) +} + +/// A zoom field had the keyboard in the last frame. Like a layer rename, it keeps its keys even in +/// the frame egui drops its focus (Esc, Tab), so the shortcuts must treat it as text. +pub fn editing(ctx: &Context) -> bool { + editing_field(ctx).is_some() +} + +/// A zoom field has the keyboard right now. +pub fn is_focused(ctx: &Context) -> bool { + editing_field(ctx).is_some_and(|id| ctx.memory(|m| m.focused()) == Some(id)) +} + +/// A key the open menu took (a row's letter, Space) also arrives as typed text, in the same frame +/// or the next: while a zoom field has the keyboard, that text never reaches it, so the field +/// neither types it nor alerts. +pub(crate) fn drop_text(ctx: &Context, c: char) { + if is_focused(ctx) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(taken_key_id(), (c, pass))); + drop_taken_text(ctx); + } +} + +/// Takes the text of the key [`drop_text`] noted out of this frame's input, once, until the frame +/// after the key. +fn drop_taken_text(ctx: &Context) { + let Some((c, pass)) = ctx.data(|d| d.get_temp::<(char, u64)>(taken_key_id())) else { return }; + if pass + 1 < ctx.cumulative_pass_nr() { + ctx.data_mut(|d| d.remove_temp::<(char, u64)>(taken_key_id())); + return; + } + let same = |t: &str| t.chars().eq(c.to_lowercase()) || t.chars().eq(c.to_uppercase()); + let found = ctx.input_mut(|i| { + let at = i.events.iter().position(|e| matches!(e, egui::Event::Text(t) if same(t))); + at.map(|at| i.events.remove(at)).is_some() + }); + if found { + ctx.data_mut(|d| d.remove_temp::<(char, u64)>(taken_key_id())); + } +} + +/// The system alert (Windows: Asterisk) is wanted; [`tick`] plays it in the next frame. +pub fn request_alert(ctx: &Context) { + ctx.data_mut(|d| d.insert_temp(alert_id(), true)); + ctx.request_repaint(); +} + +/// Whether the alert is waiting to be played (tests). +#[cfg(test)] +pub(crate) fn alert_pending(ctx: &Context) -> bool { + ctx.data(|d| d.get_temp::(alert_id())).unwrap_or(false) +} + +/// Remembers the rectangle of the whole title bar (menus, the empty drag area, workspace switcher, +/// search and theme buttons, the caption buttons) for [`on_title_bar`]. +pub(crate) fn set_title_bar_rect(ctx: &Context, rect: egui::Rect) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(title_bar_rect_id(), (rect, pass))); +} + +/// Remembers the rectangle of the menu bar titles (`File` … `Help`) for [`on_menu_bar`]. +pub(crate) fn set_menu_bar_rect(ctx: &Context, rect: egui::Rect) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(menu_bar_rect_id(), (rect, pass))); +} + +/// Does the rectangle kept under `id` (with the pass it was drawn in) contain `pos`, and was it drawn +/// recently enough to still be there? Not drawn for a while (hidden by Tab or Full Screen Mode), its +/// rect is stale and must not catch a click. The one freshness rule of the title bar and the menu bar. +fn fresh_rect_contains(ctx: &Context, id: Id, pos: egui::Pos2) -> bool { + ctx.data(|d| d.get_temp::<(egui::Rect, u64)>(id)).is_some_and(|(r, pass)| pass + 2 >= ctx.cumulative_pass_nr() && r.contains(pos)) +} + +/// A button went down on the pasteboard while a zoom field was being edited, and is still down or +/// came up in this very frame. (egui drops the focus of a text field on the click, which is the +/// release, so the press alone is not the whole gesture.) +fn pasteboard_press(ctx: &Context) -> bool { + ctx.data(|d| d.get_temp::(pasteboard_id())).unwrap_or(false) +} + +/// Once per frame ([`tick`], tests): `pressed` says a button went down on the pasteboard in this +/// frame. The gesture lasts until the frame after the button came up. +pub(crate) fn track_pasteboard(ctx: &Context, pressed: bool) { + let (down, released) = ctx.input(|i| (i.pointer.any_down(), i.pointer.any_released())); + ctx.data_mut(|d| { + if pressed { + d.insert_temp(pasteboard_id(), true); + } else if !down && !released { + d.remove::(pasteboard_id()); + } + }); +} + +// ---- 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. +pub fn tick(app: &mut crate::PhotocraftApp, ctx: &Context) { + 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) + { + play(); + } + let press = + if editing(ctx) { ctx.input(|i| if i.pointer.any_pressed() { i.pointer.press_origin().or(i.pointer.interact_pos()) } else { None }) } else { None }; + track_pasteboard(ctx, press.is_some_and(|pos| on_pasteboard(app, ctx, pos) || on_menu_bar(ctx, pos) || on_title_bar(ctx, pos) || on_open_popup(ctx, pos))); +} + +/// Is screen point `pos` anywhere on the title bar: the menu titles and the gaps between them, the +/// workspace switcher (Essentials), search, the theme button, Minimise / Maximise / Close? +fn on_title_bar(ctx: &Context, pos: egui::Pos2) -> bool { + fresh_rect_contains(ctx, title_bar_rect_id(), pos) +} + +/// Is screen point `pos` on an open menu or dropdown (Help's "Search menus" field, a menu item, +/// the workspace list)? A menu or dropdown is open and `pos` is on a layer above the canvas. +fn on_open_popup(ctx: &Context, pos: egui::Pos2) -> bool { + (egui::Popup::is_any_open(ctx) || crate::menu_nav::is_open(ctx)) && ctx.layer_id_at(pos).is_some_and(|l| l.order != egui::Order::Background) +} + +/// Is screen point `pos` on one of the menu bar's top-level menu titles (`File`, `Edit`, …)? +fn on_menu_bar(ctx: &Context, pos: egui::Pos2) -> bool { + fresh_rect_contains(ctx, menu_bar_rect_id(), pos) +} + +/// Is screen point `pos` on the main canvas, outside the image, and not under a window or menu? +fn on_pasteboard(app: &crate::PhotocraftApp, ctx: &Context, pos: egui::Pos2) -> bool { + let (Some(xf), Some(st)) = (crate::canvas::ViewXform::active(app), app.session.active()) else { return false }; + let doc = xf.to_doc(pos); + let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); + xf.rect.contains(pos) + && doc.iter().all(|v| v.is_finite()) + && (doc[0] < 0.0 || doc[1] < 0.0 || doc[0] >= w || doc[1] >= h) + && ctx.layer_id_at(pos).is_some_and(|l| l.order == egui::Order::Background) +} + +#[cfg(test)] +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}"); + } + } + + #[test] + fn the_title_bar_keeps_a_click_wherever_it_is_drawn() { + let ctx = Context::default(); + let bar = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 32.0)); + assert!(!on_title_bar(&ctx, egui::pos2(10.0, 10.0)), "nothing drawn yet"); + set_title_bar_rect(&ctx, bar); + assert!(on_title_bar(&ctx, egui::pos2(790.0, 10.0)), "the far end: Essentials, Minimise, Close"); + assert!(on_title_bar(&ctx, egui::pos2(400.0, 10.0)), "the empty drag area between the menus and them"); + assert!(!on_title_bar(&ctx, egui::pos2(10.0, 100.0)), "below the bar is the app"); + } + + /// The menu bar rect goes stale like the title bar's: not drawn for a while, it catches nothing. + #[test] + fn a_menu_bar_that_is_no_longer_drawn_keeps_no_click() { + let ctx = Context::default(); + let bar = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(300.0, 32.0)); + let inside = egui::pos2(50.0, 10.0); + assert!(!on_menu_bar(&ctx, inside), "nothing drawn yet"); + // Drawn in the pass the clock is at now. + set_menu_bar_rect(&ctx, bar); + assert!(on_menu_bar(&ctx, inside), "just drawn"); + assert!(!on_menu_bar(&ctx, egui::pos2(500.0, 10.0)), "outside the titles"); + // A few passes later, with the menu bar not drawn again (hidden): the rect is stale. + for _ in 0..3 { + // The output is dropped: its texture deltas must be cleared first, or egui panics. + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!on_menu_bar(&ctx, inside), "stale: the bar is no longer drawn"); + // Drawn again: fresh again. + set_menu_bar_rect(&ctx, bar); + assert!(on_menu_bar(&ctx, inside), "drawn again"); + } +} diff --git a/crates/ui-egui/src/canvas/zoom_levels.rs b/crates/ui-egui/src/canvas/zoom_levels.rs index a77f6cc35c4..27572dbf9a5 100644 --- a/crates/ui-egui/src/canvas/zoom_levels.rs +++ b/crates/ui-egui/src/canvas/zoom_levels.rs @@ -90,6 +90,17 @@ pub fn step(zoom: f32, dir: i32, size: [u32; 2]) -> f32 { step_in_range(zoom, dir, min(size), MAX) } +/// Applies the percent a zoom field reported as changed, as Zoom In/Out and Actual Pixels do: the +/// zoom is set to the target at once, and the camera glides there when General › Animated Zoom is +/// on. A scrub (a drag on the field or its label) follows the pointer, with no glide. Any later zoom +/// replaces the transition, and the zoom lands exactly on the target. +pub fn set_from_field(view: &mut crate::state::View, scrub: bool, percent: f32, animated_zoom: bool) { + view.zoom = clamp(percent / 100.0, view.doc_size); + view.fit_pending = false; + view.fill_pending = false; + view.request_zoom_animation(!scrub && animated_zoom); +} + #[cfg(test)] mod tests { use super::*; @@ -170,4 +181,22 @@ mod tests { assert_eq!(clamp(f32::INFINITY, PHOTO), 1.0); assert_eq!(clamp(3.3, PHOTO), 3.3); } + + #[test] + fn a_typed_zoom_lands_exactly_and_glides_only_with_animated_zoom() { + let mut v = crate::state::View { zoom: 1.0, doc_size: PHOTO, fit_pending: true, ..Default::default() }; + set_from_field(&mut v, false, 1600.0, true); + assert_eq!(v.zoom, 16.0, "the target, exactly"); + assert!(v.zoom_animating && !v.fit_pending, "Animated Zoom on: the camera glides there"); + let mut v = crate::state::View { zoom: 1.0 / 7.5, doc_size: PHOTO, ..Default::default() }; + set_from_field(&mut v, false, 6400.0, false); + assert_eq!(v.zoom, 64.0); + assert!(!v.zoom_animating, "Animated Zoom off: a jump"); + assert_eq!(v.display_camera, Some((64.0, v.center))); + set_from_field(&mut v, true, 200.0, true); + assert_eq!(v.zoom, 2.0); + assert!(!v.zoom_animating, "a scrub follows the pointer, with no glide"); + set_from_field(&mut v, false, 1.0e9, true); + assert_eq!(v.zoom, MAX, "the target is clamped to the zoom range"); + } } diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 9881797a6e8..dcff8d4d2c0 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -140,8 +140,9 @@ pub fn claim_delete_keys(ctx: &egui::Context, id: egui::Id) { impl Focus { pub fn of(ctx: &egui::Context) -> Focus { - // A layer rename keeps its keys even in the frame egui drops its focus (Esc, Tab). - if ctx.text_edit_focused() || crate::layer_row_ui::rename_active(ctx) { + // A layer rename and a zoom field keep their keys even in the frame egui drops their + // focus (Esc, Tab). + if ctx.text_edit_focused() || crate::layer_row_ui::rename_active(ctx) || crate::zoom_field::editing(ctx) { Focus::Text } else if ctx.egui_wants_keyboard_input() { let owner = ctx.data(|d| d.get_temp::(delete_owner_id())); diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index a4c30646e72..00fce3da537 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -382,6 +382,7 @@ pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { } if let Some(job) = job_in_view(app) && !ctx.text_edit_focused() + && !crate::zoom_field::editing(ctx) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { cancel(app, job.id); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fead6c2c1e4..fea7a3b4f58 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -101,6 +101,7 @@ use canvas::tile_overlay; use canvas::tool_cursor; pub use canvas::tool_feedback; pub use canvas::wheel_nav; +pub use canvas::zoom_field; pub use canvas::zoom_hold; pub use canvas::zoom_levels; pub use canvas::zoom_window_fit; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index db9e8aeac3b..6047c8074b7 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -107,6 +107,9 @@ pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 { buttons.push(title); } edge = if rtl { buttons.iter().map(|b| b.rect.left()).fold(edge, f32::min) } else { buttons.iter().map(|b| b.rect.right()).fold(edge, f32::max) }; + if let (Some(first), Some(last)) = (buttons.first(), buttons.last()) { + crate::zoom_field::set_menu_bar_rect(ui.ctx(), first.rect.union(last.rect)); + } switch_on_hover(ui.ctx(), &buttons); // ← and → step to the menu on that side, so in screen order. let mut tops: Vec = buttons.iter().map(egui::Popup::default_response_id).collect(); diff --git a/crates/ui-egui/src/menus/menu_keys.rs b/crates/ui-egui/src/menus/menu_keys.rs index 903d2e683d5..cfdf2e92970 100644 --- a/crates/ui-egui/src/menus/menu_keys.rs +++ b/crates/ui-egui/src/menus/menu_keys.rs @@ -333,6 +333,12 @@ impl Keys { _ => {} } } + // Typing a zoom: Alt only answers with the system alert. The menu bar stays off and the + // field keeps its focus and its text. + if tap && crate::zoom_field::is_focused(ctx) { + crate::zoom_field::request_alert(ctx); + tap = false; + } if events.iter().any(|e| matches!(e, Event::PointerButton { pressed: true, .. })) { self.focus = None; self.underline = false; @@ -364,8 +370,10 @@ impl Keys { } if open { // A letter runs the row with that mnemonic in the level the arrows are in, unless it is - // typed into a field in the menu: Help › Search took "S" for System Info (#5996). - let typing = ctx.text_edit_focused(); + // typed into a field in the menu: Help › Search took "S" for System Info (#5996). A zoom + // field that kept the keyboard through the click on the menu title is not in the menu, + // but while Help › Search is open the letters are still typing. + let typing = ctx.text_edit_focused() && !(crate::zoom_field::is_focused(ctx) && !super::search::shown(ctx)); let letter = events.iter().filter(|_| !typing).find_map(|e| match e { Event::Key { key, pressed: true, modifiers, .. } if !modifiers.command && !modifiers.ctrl && !modifiers.alt => { key_char(*key).map(|c| (*key, c)) @@ -376,6 +384,7 @@ impl Keys { && let Some(row) = nav.row_with_mnemonic(c) { consume(Modifiers::NONE, key); + crate::zoom_field::drop_text(ctx, c); self.underline = true; if let Some(cmd) = row.command.clone() { *clicked = Some(cmd); diff --git a/crates/ui-egui/src/menus/menu_keys/harness_tests.rs b/crates/ui-egui/src/menus/menu_keys/harness_tests.rs index 1fcde2bd540..f4a5b796a71 100644 --- a/crates/ui-egui/src/menus/menu_keys/harness_tests.rs +++ b/crates/ui-egui/src/menus/menu_keys/harness_tests.rs @@ -504,3 +504,112 @@ fn alt_held_during_a_drag_is_no_tap() { alt_tap(&mut h); assert!(Keys::current(&h.ctx).focus.is_some(), "a lone tap still focuses the bar"); } + +/// Typing a zoom: Alt only asks for the system alert. The bar does not take the keyboard, and the +/// field keeps its focus and its text. +#[test] +fn alt_in_a_zoom_field_only_alerts() { + let mut h = Harness::builder().with_size(egui::vec2(1280.0, 720.0)).build_ui_state( + |ui, (app, pct): &mut (PhotocraftApp, f32)| { + crate::menus::menu_bar(app, ui); + crate::widgets::compact_wrapping_value_field(ui, pct, 0.0..=12800.0, "%", egui::vec2(90.0, 20.0)).accessible_name("Zoom"); + }, + (app(), 100.0), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run_steps(2); + for c in "200".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run_steps(2); + } + h.key_down(egui::Key::AltLeft); + h.run_steps(2); + h.key_up(egui::Key::AltLeft); + h.run_steps(3); + assert_eq!(Keys::current(&h.ctx).focus, None, "Alt does not put the keyboard on the bar"); + assert!(crate::zoom_field::alert_pending(&h.ctx), "it asks for the alert instead"); + assert_eq!(h.state().1, 100.0, "and the zoom stays"); + assert!(h.get_by_role(egui::accesskit::Role::SpinButton).is_focused(), "the field keeps the keyboard"); + // The text was not selected by Alt: this adds to 200 instead of replacing it. + h.event(egui::Event::Text("3".into())); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().1, 2003.0, "typing went on in the same text"); +} + +/// The menu bar and a zoom field, with `zoom_field::tick` as the app runs it. `beep` stands in for +/// the platform's alert. +fn bar_and_zoom_field(beep: fn()) -> Harness<'static, (PhotocraftApp, f32)> { + let mut app = app(); + app.services.beep = Some(beep); + let mut h = Harness::builder().with_size(egui::vec2(1280.0, 720.0)).build_ui_state( + |ui, (app, pct): &mut (PhotocraftApp, f32)| { + crate::zoom_field::tick(app, &ui.ctx().clone()); + crate::menus::menu_bar(app, ui); + crate::widgets::compact_wrapping_value_field(ui, pct, 0.0..=12800.0, "%", egui::vec2(90.0, 20.0)).accessible_name("Zoom"); + }, + (app, 100.0), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run_steps(2); + for c in "300".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run_steps(2); + } + h +} + +/// A letter as the platform sends it: the key, and the text it types. +fn letter(h: &mut Harness<'static, (PhotocraftApp, f32)>, c: char) { + let key = egui::Key::from_name(&c.to_string()).unwrap(); + h.event(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.event(egui::Event::Text(c.to_lowercase().to_string())); + h.event(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(6); +} + +/// A zoom field keeps the keyboard, and what was typed, through a click on a menu title. The menu +/// that click opened still takes its keys: → moves to the next menu and a letter runs its row, +/// without the letter also reaching the field. +#[test] +fn a_menu_opened_while_typing_a_zoom_takes_its_keys() { + static BEEPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let mut h = bar_and_zoom_field(|| { + BEEPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }); + h.get_by_label("Filter").click(); + h.run_steps(4); + assert!(is_open(&h.ctx), "the click opened Filter"); + assert!(crate::zoom_field::is_focused(&h.ctx), "the zoom field kept the keyboard"); + h.key_press(egui::Key::ArrowRight); + h.run_steps(5); + assert!(h.query_by_label_contains("Zoom In").is_some(), "→ moved to View"); + let row = Nav::current(&h.ctx).rows.first().and_then(|l| l.iter().find(|r| r.command.as_deref() == Some("view.zoomIn")).cloned()); + let c = row.and_then(|r| r.mnemonic).expect("Zoom In has a mnemonic"); + let zoom = h.state().0.ui.views[0].zoom; + letter(&mut h, c); + assert!(h.state().0.ui.views[0].zoom > zoom, "its letter ran Zoom In ({c})"); + assert_eq!(BEEPS.load(std::sync::atomic::Ordering::SeqCst), 0, "and did not reach the zoom field, which would alert"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().1, 300.0, "the field still holds the typed 300, nothing more"); +} + +/// Help has a text field of its own: while a zoom is typed, its letters stay typing, never run +/// Help's rows (#5996: S for System Info). +#[test] +fn help_letters_stay_typing_while_a_zoom_is_typed() { + let mut h = bar_and_zoom_field(|| {}); + h.get_by_label("Help").click(); + h.run_steps(4); + assert!(is_open(&h.ctx), "the click opened Help"); + let rows = Nav::current(&h.ctx).rows.first().cloned().unwrap_or_default(); + let c = rows.iter().find(|r| r.enabled && r.mnemonic.is_some()).and_then(|r| r.mnemonic).expect("a Help row with a mnemonic"); + letter(&mut h, c); + assert!(is_open(&h.ctx), "{c} ran no row: Help stays open"); +} diff --git a/crates/ui-egui/src/menus/menu_nav.rs b/crates/ui-egui/src/menus/menu_nav.rs index fb17c46643c..c7b3eb28f43 100644 --- a/crates/ui-egui/src/menus/menu_nav.rs +++ b/crates/ui-egui/src/menus/menu_nav.rs @@ -341,8 +341,10 @@ impl Nav { let level = self.level.min(self.rows.len().saturating_sub(1)); self.level = level; // A text field in the menu (Help › Search) keeps the keys that edit it: ← / → move its - // cursor and Space types a space. - let typing = ctx.text_edit_focused(); + // cursor and Space types a space. A zoom field keeps the keyboard while a menu title is + // clicked (zoom_field.rs), but is not in the menu: the menu takes the keys, unless it has + // a text field of its own (Help › Search, which the zoom field keeps out). + let typing = ctx.text_edit_focused() && !(crate::zoom_field::is_focused(ctx) && !super::search::shown(ctx)); let press = |k: Key| !(typing && matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::Space)) && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); let current = self.highlighted(level).and_then(|i| self.rows.get(level)?.get(i)).cloned(); let switch = |by: usize| { @@ -373,6 +375,7 @@ impl Nav { switch(tops.len() - 1); } } else if press(Key::Enter) || press(Key::Space) { + crate::zoom_field::drop_text(ctx, ' '); match current { Some(Row { enabled: true, command: Some(c), .. }) => { *clicked = Some(c); diff --git a/crates/ui-egui/src/menus/search.rs b/crates/ui-egui/src/menus/search.rs index a1eed7981cc..f51172892d4 100644 --- a/crates/ui-egui/src/menus/search.rs +++ b/crates/ui-egui/src/menus/search.rs @@ -44,6 +44,12 @@ pub fn search_items<'a>(items: &'a [MenuItem], query: &str, lang: crate::i18n::L hits.into_iter().filter(|(_, _, it)| seen.insert(it.id.as_str())).take(HELP_SEARCH_MAX).map(|(_, _, it)| it).collect() } +/// Help › Search was drawn in this frame (or the last): the open menu has a text field of its own. +pub(super) fn shown(ctx: &egui::Context) -> bool { + let pass_id = egui::Id::unique("help-menu-search").with("pass"); + ctx.data(|d| d.get_temp::(pass_id)).is_some_and(|p| p + 1 >= ctx.cumulative_pass_nr()) +} + /// Help › Search : a field at the top of the Help menu that finds any menu command /// by name. Results show their menu path; click, ↓ then ↩, or ↩ in the field runs one. /// `opening`: this frame's release ends the click on the Help title that opened the menu. @@ -60,7 +66,7 @@ pub(super) fn help_search(ui: &mut egui::Ui, items: &[MenuItem], opening: bool, let field = ui.add(egui::TextEdit::singleline(&mut query).id(text_id.with("field")).hint_text(crate::i18n::tr(lang, "Search menus")).desired_width(220.0)); // The menu opens on the press; the release a frame later completes a click on the title, // outside the field, and egui takes the focus away from it again (#1447, #1438). - if reopened || opening { + if (reopened || opening) && !crate::zoom_field::editing(&ctx) { field.request_focus(); } let results = search_items(items, &query, lang); diff --git a/crates/ui-egui/src/panels/chrome_ui.rs b/crates/ui-egui/src/panels/chrome_ui.rs index f5e58a455dc..82a70fd408d 100644 --- a/crates/ui-egui/src/panels/chrome_ui.rs +++ b/crates/ui-egui/src/panels/chrome_ui.rs @@ -157,14 +157,11 @@ pub fn status_bar_pro(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ); let mut pct = app.ui.views[i].zoom * 100.0; let control_h = crate::panels::status_bar_heights(&t).1; - if widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", vec2(64.0, control_h)) - .accessible_name(tl!("Zoom")) - .changed() - { - app.ui.views[i].zoom = crate::zoom_levels::clamp(pct / 100.0, app.ui.views[i].doc_size); - app.ui.views[i].zoom_animating = false; - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fit_pending = false; + let field = widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", vec2(64.0, control_h)) + .accessible_name(tl!("Zoom")); + if field.changed() { + let animated = app.session.prefs().general.animated_zoom; + crate::zoom_levels::set_from_field(&mut app.ui.views[i], field.dragged() || field.drag_started(), pct, animated); } ui.add_space(12.0); ui.label(RichText::new(tl!(&text)).color(t.text_dim).size(12.0)); diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index b588288c477..256d0577dab 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -121,7 +121,8 @@ pub(super) fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let field = widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[idx]), "%", vec2(64.0, NAV_ROW_H)) .accessible_name(tl!("Zoom")); if field.changed() { - set(app, pct / 100.0, false); + let animated = app.session.prefs().general.animated_zoom; + crate::zoom_levels::set_from_field(&mut app.ui.views[idx], field.dragged() || field.drag_started(), pct, animated); } let out = crate::brush_picker::named(icons::button(ui, "minus", NAV_ROW_H, false, tl!("Zoom Out")), "Zoom Out"); if out.clicked() { diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs index 79ca2ef3555..4313e648399 100644 --- a/crates/ui-egui/src/panels/status_bar.rs +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -31,14 +31,12 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let (w, h, mode, bits, layers) = (st.doc.size.width, st.doc.size.height, crate::canvas::mode_label(&st.doc), st.doc.depth.bits(), st.doc.layer_count()); let mut pct = app.ui.views[i].zoom * 100.0; - if widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", vec2(78.0, control_h)) - .accessible_name(tl!("Zoom")) - .changed() - { - app.ui.views[i].zoom = crate::zoom_levels::clamp(pct / 100.0, app.ui.views[i].doc_size); - app.ui.views[i].zoom_animating = false; - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fit_pending = false; + let field = + widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", vec2(78.0, control_h)) + .accessible_name(tl!("Zoom")); + if field.changed() { + let animated = app.session.prefs().general.animated_zoom; + crate::zoom_levels::set_from_field(&mut app.ui.views[i], field.dragged() || field.drag_started(), pct, animated); } widgets::vline(ui, 16.0); label(ui, &crate::i18n::fmt(tl!("{mode} Color · {bits} bit"), &[("mode", mode), ("bits", &bits.to_string())])); diff --git a/crates/ui-egui/src/panels/title_bar.rs b/crates/ui-egui/src/panels/title_bar.rs index 6586b98a36b..fd760ec7111 100644 --- a/crates/ui-egui/src/panels/title_bar.rs +++ b/crates/ui-egui/src/panels/title_bar.rs @@ -147,6 +147,8 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().galley(egui::pos2(x, full.center().y - g.size().y / 2.0), g, t.text_dim); } }); + // A click anywhere on the bar keeps a zoom being typed (zoom_field.rs). + crate::zoom_field::set_title_bar_rect(ui.ctx(), bar.response.rect); if custom { crate::titlebar::caption_buttons(app, ui, bar.response.rect); } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 276682e577c..1bcaf89e328 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -417,6 +417,10 @@ pub struct Services { /// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a /// background job finishes successfully. `None` in the web build (and in tests). pub beep: Option, + /// The system's alert sound, played when a key does nothing in a zoom field being typed in + /// (Tab, Alt; see `zoom_field`). No platform sets it yet, so the alert falls back to + /// [`Self::beep`]. + pub alert: Option, /// Starts a background check for published releases (desktop, outside Flatpak). pub check_updates: Option, /// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as diff --git a/crates/ui-egui/src/status_bar_tests.rs b/crates/ui-egui/src/status_bar_tests.rs index 1d42a655608..9d4bcd42ea0 100644 --- a/crates/ui-egui/src/status_bar_tests.rs +++ b/crates/ui-egui/src/status_bar_tests.rs @@ -218,3 +218,45 @@ fn appearance_toggle_preserves_pro_layout_and_has_no_fit_button() { assert!(Tokens::get(&h.ctx).pro); assert!(h.query_by_label("Fit").is_none(), "Fit button must not appear in light mode (#5016)"); } + +/// A zoom typed into the status bar, then any other zoom before the first one has settled: the new +/// zoom wins and lands exactly, with nothing of the typed one left to multiply it (Ctrl+1 right +/// after a typed 1600 % is 100 %, not about 240 %). A typed zoom also lands exactly on its target. +#[test] +fn a_typed_zoom_leaves_nothing_for_the_next_zoom_and_lands_exactly() { + for animated in [true, false] { + 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.run("prefs.set", json!({"values": {"general.animatedZoom": animated}})).unwrap(); + app.sync_views(); + let mut h = Harness::builder().with_size(SIZE).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let canvas = Rect::from_min_size(pos2(0.0, 0.0), vec2(SIZE.x, 120.0)); + let view = app.ui.views[0].clone(); + app.ui.views[0] = crate::canvas::canvas_view(app, ui, 0, canvas, view, true); + 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); + for (typed, want) in [("1600", 16.0), ("200", 2.0), ("6400", 64.0)] { + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run_steps(2); + h.event(egui::Event::Text(typed.into())); + h.key_press(egui::Key::Enter); + h.run_steps(60); + assert_eq!(h.state().ui.views[0].zoom, want, "typed {typed}, animated {animated}"); + } + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run_steps(2); + h.event(egui::Event::Text("1600".into())); + h.key_press(egui::Key::Enter); + h.run_steps(1); + crate::panels::actions::run_view(h.state_mut(), "view.actualPixels", serde_json::Value::Null).unwrap(); + h.run_steps(60); + assert_eq!(h.state().ui.views[0].zoom, 1.0, "Actual Pixels after a typed 1600 %, animated {animated}"); + } +} diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index 439662724ed..7e6c9709d6e 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -48,9 +48,11 @@ pub fn compact_value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeI value_field_box(ui, value, range, suffix, vec2(width, height), 0.0, FieldOpts::default(), None).0 } -/// A compact field whose mouse scrub wraps at the native fullscreen viewport's horizontal edges. +/// A compact field whose mouse scrub wraps at the native fullscreen viewport's horizontal edges, +/// and whose typed number applies on Enter or click-away, never on Esc, Tab or Alt: the zoom +/// fields (see `zoom_field`). pub(crate) fn compact_wrapping_value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, size: Vec2) -> Response { - value_field_box(ui, value, range, suffix, size, 0.0, FieldOpts { wrap_drag: true, ..Default::default() }, None).0 + value_field_box(ui, value, range, suffix, size, 0.0, FieldOpts { wrap_drag: true, hold_typed: true, ..Default::default() }, None).0 } /// How a [`value_field_in`] shows and reads its number, beyond its suffix. @@ -65,6 +67,10 @@ pub(super) struct FieldOpts { /// The length (px) 100 % stands for, so lengths and percentages convert into each other. pub(super) extent: Option, pub(super) wrap_drag: bool, + /// A typed number waits for Enter or click-away, as arithmetic does, instead of applying per + /// keystroke (the zoom fields: typing `150` over `50` must not zoom to 1 % on the way). Esc, + /// Tab and Alt do not apply it (`zoom_field`). + pub(super) hold_typed: bool, } /// Arrow-key and drag step for a value field: [`FieldOpts::step_from_decimals`] uses `decimals`; @@ -110,7 +116,7 @@ fn value_field_box( opts: FieldOpts, name: Option<&str>, ) -> (Response, Rect) { - let FieldOpts { decimals, step_from_decimals, units, extent, wrap_drag } = opts; + let FieldOpts { decimals, step_from_decimals, units, extent, .. } = opts; let t = Tokens::get(ui.ctx()); let (rect, slot) = ui.allocate_exact_size(size, Sense::hover()); let last_editor = ui.data(|d| d.get_temp::(slot.id)); @@ -190,7 +196,7 @@ fn value_field_box( ui.spacing_mut().button_padding = Vec2::ZERO; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let layout = egui::Layout::centered_and_justified(ui.layout().main_dir()); - ui.allocate_ui_with_layout(field.size(), layout, |ui| number_edit(ui, value, range, fine, decimals, units, wrap_drag)).inner + ui.allocate_ui_with_layout(field.size(), layout, |ui| number_edit(ui, value, range, fine, units, opts)).inner }) .inner } @@ -367,18 +373,34 @@ pub fn popup_value_field(ui: &mut Ui, name: &str, value: &mut f32, range: std::o pub(super) const NUMERIC_INPUT_LIMIT: usize = 128; -/// The number in a [`value_field`]. A typed number applies as it's typed; arithmetic waits for -/// Enter, Tab or click-away, because per keystroke `5/2` would land first and a caller that -/// rounds it would cut `5/2*2` short. `changed()` means a new value, not just a keystroke. +/// Drops text events longer than [`NUMERIC_INPUT_LIMIT`] from this frame's input: oversized events +/// must never reach text layout. +fn drop_oversized_input(ui: &Ui) { + ui.input_mut(|input| { + input.events.retain(|event| { + let text = match event { + egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => text, + egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => text, + _ => return true, + }; + text.chars().nth(NUMERIC_INPUT_LIMIT).is_none() + }); + }); +} + +/// The number in a [`value_field`]. A typed number applies as it's typed, unless `opts.hold_typed`; +/// arithmetic always waits for Enter, Tab or click-away, because per keystroke `5/2` would land +/// first and a caller that rounds it would cut `5/2*2` short. `changed()` means a new value, not +/// just a keystroke. fn number_edit( ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, fine: bool, - decimals: Option, units: crate::numeric_expression::Units, - wrap_drag: bool, + opts: FieldOpts, ) -> Response { + let FieldOpts { decimals, wrap_drag, hold_typed, .. } = opts; let (id, ctx) = (ui.next_auto_id(), ui.ctx().clone()); // Focused before the DragValue is drawn, so it gains focus this frame and selects its text. if ui.data_mut(|d| d.remove_temp::(first_field_id())).unwrap_or(false) { @@ -388,6 +410,23 @@ fn number_edit( if ui.is_enabled() { crate::field_tab::register(&ctx, id); } + // 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)), + }; + // 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) + } else { + Default::default() + }; // Use DragValue's focus check before it builds its TextEdit: oversized events must never // reach text layout. Registering interest also handles focus arriving by Tab this frame. let editing = ui.is_enabled() @@ -396,16 +435,7 @@ fn number_edit( m.has_focus(id) }); if editing { - ui.input_mut(|input| { - input.events.retain(|event| { - let text = match event { - egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => text, - egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => text, - _ => return true, - }; - text.chars().nth(NUMERIC_INPUT_LIMIT).is_none() - }); - }); + drop_oversized_input(ui); } let held = id.with("arithmetic"); let math = ui.memory(|m| m.has_focus(id)) && ui.data(|d| d.get_temp(held)).unwrap_or(false); @@ -414,8 +444,13 @@ fn number_edit( let speed = if fine { 0.01 } else { 0.5 }; let wrapping = wrap_drag && crate::scrub_wrap::active(ui); let wrapped_drag = wrapping && ui.input(|i| i.pointer.primary_down()); + // A zoom field edits a copy: what egui reports as typed is applied below, when nothing vetoes + // it (Esc, Tab, a click that keeps it, a window that lost the keyboard), whatever egui itself + // does with the key or the click. + let mut typed = *value; + let target: &mut f32 = if hold_typed { &mut typed } else { &mut *value }; let mut resp = ui.add( - egui::DragValue::new(value) + egui::DragValue::new(target) .range(range.clone()) // Only edits are clamped (below): showing a value past the range, such as a type layer // scaled to 2400 pt in a 1296 pt field, must not change it (#5717). @@ -427,14 +462,28 @@ fn number_edit( None if fine => fmt_num2(v), None => fmt_num(v), }) - .update_while_editing(!math) + .update_while_editing(!math && !hold_typed) // Focus is read when parsing, not above: Tab hands it on inside `ui.add`. .custom_parser(move |s| { // Short events can accumulate: reject before either parser normalizes the text. 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. + 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 + } 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 }; 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())); @@ -443,6 +492,14 @@ fn number_edit( v }), ); + if hold_typed { + // A scrub always applies; a typed value applies unless this frame's guard vetoes it. + let scrub = resp.dragged() || resp.drag_started() || resp.drag_stopped(); + if typed != before && (scrub || !guard.vetoes_typed()) { + *value = typed; + } + crate::zoom_field::after(ui, id, guard); + } if wrap_drag { crate::scrub_wrap::update(ui, &resp, value, before, range.clone(), speed, wrapping); } diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index f0971e053d1..59133da3852 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -834,6 +834,331 @@ fn value_field_holds_arithmetic_until_committed() { assert_eq!(*h.state(), (25.0, 3)); } +/// What stands in for the app around a zoom field in the tests below. +#[derive(Clone, Copy, PartialEq)] +enum EscEater { + /// Nothing takes Esc. + Nobody, + /// Like `shortcuts::handle`: Esc is taken when no text field has the keyboard. + Shortcuts, + /// Esc is taken before the field can see it, whatever the focus. + Always, +} + +/// The zoom field alone, with a button after it (so Tab has somewhere to go). The state is the +/// field's value and how many times it reported a change. `on_pasteboard` stands in for +/// `zoom_field::tick`: a press at the right of the window is a press on the pasteboard. +fn zoom_harness(start: f32, eater: EscEater, on_pasteboard: bool) -> egui_kittest::Harness<'static, (f32, u32)> { + egui_kittest::Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + move |ui, (v, changes): &mut (f32, u32)| { + let ctx = ui.ctx().clone(); + let typing = ctx.text_edit_focused() || crate::zoom_field::editing(&ctx); + if eater == EscEater::Always || (eater == EscEater::Shortcuts && !typing) { + ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + } + let pressed = on_pasteboard && ctx.input(|i| i.pointer.any_pressed() && i.pointer.press_origin().is_some_and(|p| p.x > 150.0)); + crate::zoom_field::track_pasteboard(&ctx, pressed); + if super::compact_wrapping_value_field(ui, v, 0.0..=12800.0, "%", egui::vec2(90.0, 20.0)).accessible_name("Zoom").changed() { + *changes += 1; + } + let _ = ui.button("next"); + }, + (start, 0), + ) +} + +fn zoom_field_node<'a>(h: &'a egui_kittest::Harness<'static, (f32, u32)>) -> egui_kittest::Node<'a> { + use egui_kittest::kittest::Queryable; + h.get_by_role(egui::accesskit::Role::SpinButton) +} + +/// Clicks the field and types `text` over its selected number, one key at a time. +fn click_and_type(h: &mut egui_kittest::Harness<'static, (f32, u32)>, text: &str) { + zoom_field_node(h).click(); + h.run(); + for c in text.chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } +} + +/// A button down (and up) at `pos`. +fn click_at(h: &mut egui_kittest::Harness<'static, (f32, u32)>, pos: egui::Pos2, button: egui::PointerButton) { + h.event(egui::Event::PointerMoved(pos)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }); + h.run(); + } +} + +/// The zoom field applies a typed number once, on Enter, however many digits it has: never the +/// number its first keys spell on the way (`1`, `12` on the way to `1200`), and always clamped. +#[test] +fn a_typed_zoom_is_applied_once_on_enter() { + // (zoom before, typed, zoom after). The range is 0..=12800. + let cases = [(100.0, "200", 200.0), (3.0, "1200", 1200.0), (800.0, "5", 5.0), (25.0, "99999", 12800.0), (7.0, "7", 7.0)]; + for (before, typed, after) in cases { + let mut h = zoom_harness(before, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + assert_eq!(*h.state(), (before, 0), "{typed} over {before}: nothing applies while typing"); + h.key_press(egui::Key::Enter); + h.run(); + let changes = u32::from(after != before); + assert_eq!(*h.state(), (after, changes), "{typed} over {before}: Enter applies it once"); + } +} + +/// Esc drops what was typed, whoever else wants the key, and the field is the zoom again. +#[test] +fn esc_drops_the_typed_zoom() { + for eater in [EscEater::Nobody, EscEater::Shortcuts, EscEater::Always] { + let mut h = zoom_harness(200.0, eater, false); + click_and_type(&mut h, "40"); + click_and_type_more(&mut h, "50"); + h.key_press(egui::Key::Escape); + h.run(); + assert_eq!(*h.state(), (200.0, 0), "Esc does not apply 40 or 50"); + assert_eq!(h.ctx.memory(|m| m.focused()), None, "Esc leaves the field"); + // Nothing typed 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(), (200.0, 0), "the field shows the zoom, 200, again"); + } +} + +/// Types more into the field that already has the keyboard. +fn click_and_type_more(h: &mut egui_kittest::Harness<'static, (f32, u32)>, text: &str) { + // The first number is still selected only when the field was just reached: select it as + // Photoshop's user would, with Ctrl+A. + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run(); + for c in text.chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } +} + +/// Tab (and ⇧Tab) in the zoom field: the alert, the text selected, the focus kept, nothing applied. +#[test] +fn tab_in_the_zoom_field_alerts_and_selects_the_text() { + use egui_kittest::kittest::Queryable; + for modifiers in [egui::Modifiers::NONE, egui::Modifiers::SHIFT] { + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "200"); + assert!(!crate::zoom_field::alert_pending(&h.ctx), "typing is silent"); + h.key_press_modifiers(modifiers, egui::Key::Tab); + h.run_steps(2); + assert_eq!(*h.state(), (100.0, 0), "Tab leaves the zoom alone"); + assert!(zoom_field_node(&h).is_focused(), "and the focus in the field"); + assert!(!h.get_by_label("next").is_focused(), "not on the next widget"); + assert!(crate::zoom_field::alert_pending(&h.ctx), "and asks for the alert"); + // The text is selected: this replaces 200 instead of making it 2003. + for c in "3".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (3.0, 1)); + } +} + +/// A zoom field reads `1/2` as 50 % and `5/2` as 250 %, like Photoshop. +#[test] +fn a_zoom_field_reads_a_division_as_a_ratio() { + for (typed, after) in [("1/2", 50.0), ("5/2", 250.0), ("4/1", 400.0)] { + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (after, 1), "{typed}"); + } +} + +/// `,` is a decimal point in a zoom field, like `.`: `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)] { + let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + 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. +#[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"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (2000.0, 1)); +} + +/// At most one `.` or `,`, never both, and no `.` next to a `/`: the key is dropped, with the alert. +#[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)] + { + let mut h = zoom_harness(50.0, EscEater::Shortcuts, false); + click_and_type(&mut h, typed); + 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"); +} + +/// 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. +#[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(); + 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::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)); +} + +/// 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. +#[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"); +} + +/// A pasted `100/5.0` stays in the field and asks for the alert; Enter puts the zoom back. +#[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"); + 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)); +} + +/// Only digits, the two separators 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() { + let mut h = zoom_harness(100.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "2"); + assert!(!crate::zoom_field::alert_pending(&h.ctx), "a digit is silent"); + h.event(egui::Event::Text("a".into())); + h.run(); + assert!(crate::zoom_field::alert_pending(&h.ctx), "a letter asks for the alert"); + for c in "00".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (200.0, 1), "the letter was not inserted: 2, then 00"); +} + +/// A click, with either button, on the pasteboard keeps the typed zoom and selects it; a click +/// on anything else applies it, as before. +#[test] +fn a_click_on_the_pasteboard_selects_the_typed_zoom_and_applies_nothing() { + let away = egui::pos2(250.0, 80.0); + for button in [egui::PointerButton::Primary, egui::PointerButton::Secondary] { + let mut h = zoom_harness(40.0, EscEater::Shortcuts, true); + click_and_type(&mut h, "50"); + click_at(&mut h, away, button); + assert_eq!(*h.state(), (40.0, 0), "{button:?}: the zoom stays"); + assert!(zoom_field_node(&h).is_focused(), "{button:?}: the field keeps the keyboard"); + h.event(egui::Event::Text("7".into())); + h.run(); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (7.0, 1), "{button:?}: the text was selected, 7 replaced 50"); + } + let mut h = zoom_harness(40.0, EscEater::Shortcuts, false); + click_and_type(&mut h, "50"); + click_at(&mut h, away, egui::PointerButton::Primary); + assert_eq!(*h.state(), (50.0, 1), "a click elsewhere applies the typed zoom"); +} + +/// Enter right after a click on the pasteboard, in the frames egui draws next (the release's frame, +/// one more for its events, then the Enter, with the mouse still): the typed zoom is applied. +#[test] +fn enter_right_after_a_click_on_the_pasteboard_applies_the_typed_zoom() { + let away = egui::pos2(250.0, 80.0); + let mut h = zoom_harness(40.0, EscEater::Shortcuts, true); + click_and_type(&mut h, "50"); + h.event(egui::Event::PointerMoved(away)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: away, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(1); + assert_eq!(*h.state(), (40.0, 0), "the click applied nothing"); + h.key_press(egui::Key::Enter); + h.run_steps(1); + assert_eq!(*h.state(), (50.0, 1), "Enter applies the typed 50"); +} + /// #5717: a value past the range shows as it is without reporting a change; an edit is clamped. #[test] fn value_field_keeps_a_shown_value_past_its_range_and_clamps_edits() {