diff --git a/crates/ui-egui/src/prefs/prefs_ui/custom_rows.rs b/crates/ui-egui/src/prefs/prefs_ui/custom_rows.rs index 83815809410..92cbda9b71f 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/custom_rows.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/custom_rows.rs @@ -3,6 +3,7 @@ //! (`craft::automation::ui::agents`), drawn whole on the desktop. Every row edits the window's draft; nothing is //! written before Apply or OK. +use craft::behavior::NumberCodec; use craft::theme::variant::Tone; use craft::theme::{ModeChoice, Size, ThemeId}; use craft::theme_store::ui::AppearancePage; @@ -15,10 +16,10 @@ use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::patterns::preferences::PathSetting; use craft::ui::pickers::Select; -use craft::ui::runtime::env::system_appearance; +use craft::ui::runtime::env::{Env, system_appearance}; use craft::ui::sections::Section; use craft::ui::style::TypeRole; -use craft::ui::text::{NumberField, TextField}; +use craft::ui::text::{NumberField, TextField, TextWords}; use serde_json::{Value, json}; use super::fields::{PrefPages, choice_label}; @@ -37,6 +38,7 @@ const LIGHT_THEME: &str = "interface.lightTheme"; const DARK_THEME: &str = "interface.darkTheme"; const FAVORITE_THEMES: &str = "interface.favoriteThemes"; const DENSITY: &str = "interface.density"; +const RAW_RESOLUTION: &str = "rawDefaults.resolution"; /// The page agents' settings live on, drawn whole by [`craft::automation::ui::agents::AgentsPage`]. #[cfg(not(target_arch = "wasm32"))] pub(super) const AGENTS_PAGE: &str = "integrations"; @@ -95,6 +97,7 @@ impl CustomSettings for PrefsCustom { "tools.pressureCurve" => pressure_curve_row(ui, draft), "tools.tabletInput" => tablet_input_row(ui, draft), APPEARANCE_MODE => self.appearance_row(ui, draft), + RAW_RESOLUTION => raw_resolution_row(ui, draft), _ => {} } false @@ -153,6 +156,36 @@ fn choices_of(path: &str) -> Vec<(String, String)> { prefs::choices(path).unwrap_or(&[]).iter().map(|o| (o.to_string(), choice_label(o))).collect() } +/// Where [`raw_resolution_row`] leaves the message of a value it clamped, in the frame's memory: the row has no app to +/// open an alert on, so the window takes the message after its pass. +pub(super) fn range_alert_id() -> egui::Id { + egui::Id::unique("photocraft.preferences.range-alert") +} + +/// RAW Defaults › Resolution: whole numbers within [`prefs::RawDefaults::RESOLUTION`], as the reference application's +/// field takes them (#18027). A typed comma is dropped, so "72,5" is 725. A typed value past the range keeps the +/// closest end and leaves the message that says so under [`range_alert_id`]. +fn raw_resolution_row(ui: &mut egui::Ui, draft: &mut SettingsDraft) { + let (lo, hi) = prefs::RawDefaults::RESOLUTION.into_inner(); + let (lo, hi) = (f64::from(lo), f64::from(hi)); + let stored: u32 = draft.get(RAW_RESOLUTION).unwrap_or_else(|| prefs::RawDefaults::default().resolution); + let start = f64::from(stored); + let env = Env::of(ui); + // The reader's expressions and relative input stay; only the comma goes before it reads. + let reader = env.units().reader(None); + let codec = NumberCodec::new(reader.clone(), 0).parse_with(move |text| reader.read(&text.replace(',', ""), Some(start)).ok()); + let shown = NumberField::new(tl!("Resolution"), Bind::given(Some(start))).range(lo..=hi).step(1.0).codec(codec).show(ui); + if let Some(next) = shown.edit.events.landed().cloned().flatten() { + draft.set(RAW_RESOLUTION, &(next.round().clamp(lo, hi) as u32)); + } + if shown.out_of_range.is_some() { + // The sentence of a value with a unit: the reference words this field's alert with "A value". + let (low, high) = (env.units().number(lo, 0..=0), env.units().number(hi, 0..=0)); + let message = env.words::().range_value.fill(&[("low", low.as_str()), ("high", high.as_str())]); + ui.data_mut(|data| data.insert_temp(range_alert_id(), message)); + } +} + /// A checkbox enabling a 1–95 % field; off stores no value. fn memory_percent_row(ui: &mut egui::Ui, draft: &mut SettingsDraft) { let stored: Option = draft.get(MEMORY_PERCENT); @@ -406,3 +439,6 @@ fn tablet_input_row(ui: &mut egui::Ui, draft: &mut SettingsDraft) { ); help(ui, tl!("Applies at next launch.")); } + +#[cfg(test)] +mod raw_resolution_alert_tests; diff --git a/crates/ui-egui/src/prefs/prefs_ui/custom_rows/raw_resolution_alert_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/custom_rows/raw_resolution_alert_tests.rs new file mode 100644 index 00000000000..c16f9768848 --- /dev/null +++ b/crates/ui-egui/src/prefs/prefs_ui/custom_rows/raw_resolution_alert_tests.rs @@ -0,0 +1,119 @@ +//! #18027: RAW Defaults › Resolution in the Preferences window. A value typed past 1 … 999 keeps the closest end and +//! says so once, in an alert with OK; a typed comma is dropped, so "72,5" is 725 and raises no alert. Both as measured +//! in the reference application. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::Value; + +use super::super::{apply_window, open_preferences, window_open}; +use crate::PhotocraftApp; + +type H = Harness<'static, Box>; + +const ALERT: &str = "A value between 1 and 999 is required. Closest value inserted."; + +/// An app with Preferences open on RAW Defaults. +fn window() -> H { + let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + open_preferences(&mut app, "rawDefaults"); + app + }); + h.run_steps(4); + assert!(window_open(h.state()), "Preferences did not open"); + h +} + +/// The Resolution field: the page's one number field. +fn field<'a>(h: &'a H) -> egui_kittest::Node<'a> { + let named = |n: &egui_kittest::Node<'_>| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Resolution"); + let found = h.query_all_by_role(Role::SpinButton).find(named); + found.unwrap_or_else(|| { + panic!("no Resolution field among {:?}", h.query_all_by_role(Role::SpinButton).map(|n| n.accesskit_node().label()).collect::>()) + }) +} + +/// Types `text` over the field's number and presses `key`, as a person would. +fn type_and_press(h: &mut H, text: &str, key: egui::Key) { + field(h).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(key); + h.run_steps(4); +} + +/// Types `text` over the field's number and leaves the field with Tab. +fn type_resolution(h: &mut H, text: &str) { + type_and_press(h, text, egui::Key::Tab); +} + +/// The number the field shows. +fn shown(h: &H) -> String { + field(h).accesskit_node().value().unwrap_or_default() +} + +/// The resolution in the window's draft: what Apply or OK would write. +fn drafted(h: &H) -> Value { + let open = h.state().framework.dialogs.open_dialogs(); + let values = open.iter().find_map(|d| d.fields.as_ref()?.get("values").cloned()).expect("the Preferences window is open"); + values["rawDefaults"]["resolution"].clone() +} + +/// The messages of the alerts on screen. +fn alerts(h: &H) -> Vec { + h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// Clicks OK on the alert, not on the Preferences window under it. +fn ok_on_the_alert(h: &mut H) { + h.get_by_role(Role::AlertDialog).get_by_label("OK").click(); + h.run_steps(4); +} + +#[test] +fn a_value_typed_past_the_range_keeps_the_closest_end_and_alerts_once() { + for (typed, end) in [("0", 1), ("99999", 999)] { + let mut h = window(); + type_resolution(&mut h, typed); + assert_eq!(alerts(&h), [ALERT], "{typed}: the alert says what was done"); + assert_eq!(drafted(&h), end, "{typed}: the closest end is kept"); + h.run_steps(4); + assert_eq!(alerts(&h).len(), 1, "{typed}: one alert, not one per frame"); + ok_on_the_alert(&mut h); + assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert"); + assert!(window_open(h.state()), "{typed}: Preferences stays open under the alert"); + assert_eq!(shown(&h), end.to_string(), "{typed}: the field holds the closest end after OK"); + type_resolution(&mut h, "240"); + assert!(alerts(&h).is_empty(), "{typed}, then 240: a value in range raises no alert"); + assert_eq!(drafted(&h), 240); + apply_window(h.state_mut()).unwrap(); + assert_eq!(h.state().session.prefs().raw_defaults.resolution, 240, "{typed}, then 240: Apply writes the field's value"); + } +} + +/// Enter commits the field and is the window's OK in the same pass, so the window that held the alert is gone by +/// the time it would open. The value is still clamped, and the alert still says so. +#[test] +fn enter_in_the_field_still_alerts() { + let mut h = window(); + type_and_press(&mut h, "0", egui::Key::Enter); + assert_eq!(alerts(&h), [ALERT]); + let kept = if window_open(h.state()) { drafted(&h) } else { h.state().session.prefs().raw_defaults.resolution.into() }; + assert_eq!(kept, 1, "the closest end is kept"); +} + +#[test] +fn a_typed_comma_is_dropped_without_an_alert() { + let mut h = window(); + type_resolution(&mut h, "72,5"); + assert!(alerts(&h).is_empty(), "725 is in range: {:?}", alerts(&h)); + assert_eq!(drafted(&h), 725); + assert_eq!(shown(&h), "725"); + apply_window(h.state_mut()).unwrap(); + assert_eq!(h.state().session.prefs().raw_defaults.resolution, 725); +} diff --git a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs index a6f83ff0b6a..dbb08f59926 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs @@ -99,8 +99,9 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V /// The edits Apply or OK made, as the `values` of `prefs.set` and the paths `prefs.reset` takes. type Edits = (Value, Vec); -/// What OK answers with: the edits the window made that no pass has handed on yet. -pub(crate) struct PrefsAnswer(Vec); +/// What OK answers with: the edits the window made that no pass has handed on yet, and the range alert of a value +/// clamped in the pass that closed it (Enter in a field is also the window's OK). +pub(crate) struct PrefsAnswer(Vec, Option); /// The open Preferences window, a dialog on the framework's host under the key `preferences`. pub(crate) struct PrefsDialog { @@ -119,6 +120,8 @@ pub(crate) struct PrefsDialog { custom: PrefsCustom, /// The colour row whose swatch was pressed, until `take` opens the picker for it. pick: Option, + /// The message of a typed value a custom row clamped to its range, until `take` opens the alert for it. + range_alert: Option, /// The edits Apply or OK made, until `take` writes them. edits: Vec, } @@ -197,16 +200,19 @@ impl StackDialog for PrefsDialog { if let Some(request) = out.pick_color { self.pick = Some(request); } + if let Some(message) = ui.data_mut(|data| data.remove_temp::(super::custom_rows::range_alert_id())) { + self.range_alert = Some(message); + } self.file_edits(); out.closed.map(|closed| match closed { - Closed::Ok => DialogResult::Ok(PrefsAnswer(std::mem::take(&mut self.edits))), + Closed::Ok => DialogResult::Ok(PrefsAnswer(std::mem::take(&mut self.edits), self.range_alert.take())), _ => DialogResult::Cancel, }) } fn confirm(&mut self, _ctx: &egui::Context) -> Option { self.apply().ok()?; - Some(PrefsAnswer(std::mem::take(&mut self.edits))) + Some(PrefsAnswer(std::mem::take(&mut self.edits), self.range_alert.take())) } fn json_fields(&self) -> Option { @@ -258,7 +264,8 @@ pub fn open_preferences(app: &mut PhotocraftApp, section: &str) { let custom = PrefsCustom::new(app, false); let saved_rev = app.session.prefs.rev(); let words = Arc::new(Words::from_i18n(Arc::clone(crate::i18n::framework_i18n()), host.lang())); - app.framework.dialogs.open(PrefsDialog { doc: Some(doc), state, saved_rev, labels: host.lang(), words, custom, pick: None, edits: Vec::new() }); + let dialog = PrefsDialog { doc: Some(doc), state, saved_rev, labels: host.lang(), words, custom, pick: None, range_alert: None, edits: Vec::new() }; + app.framework.dialogs.open(dialog); } /// The language the draft's `interface.language` names, as the code stored in the draft. @@ -315,20 +322,24 @@ pub(crate) fn feed(app: &mut PhotocraftApp) { /// Carries the window's requests out after a host pass: the answer it ended with, the edits Apply filed, the colour /// picker its swatch asked for and the picker's answer. A window that is gone takes its picker with it. pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { - let mut batches = match app.framework.dialogs.take::() { - Some(DialogResult::Ok(PrefsAnswer(edits))) => edits, - _ => Vec::new(), + let (mut batches, mut range_alert) = match app.framework.dialogs.take::() { + Some(DialogResult::Ok(PrefsAnswer(edits, range_alert))) => (edits, range_alert), + _ => (Vec::new(), None), }; let mut picked = None; if let Some(dialog) = app.framework.dialogs.get_mut::() { batches.append(&mut dialog.edits); picked = dialog.pick.take(); + range_alert = dialog.range_alert.take().or(range_alert); } else { crate::color_picker_ui::cancel_window_picker(app, ctx, PickWindow::Preferences); } if let Some(request) = picked { crate::color_picker_ui::open_for_window(app, PickWindow::Preferences, request); } + if let Some(message) = range_alert { + let _ = crate::dialogs::alerts::alert(app, message); + } if let Some((key, color)) = crate::color_picker_ui::answer_for_window(app, PickWindow::Preferences) && let Some(doc) = app.framework.dialogs.get_mut::().and_then(|d| d.doc.as_mut()) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 6f6d636e8e9..1942c3d1e0c 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -168,6 +168,9 @@ pub(super) fn rules(ctx: &egui::Context) -> Vec { for path in ["performance.gpuAdapter", "tools.pressureCurve", "scratchDisks.disks", "fileHandling.recentFiles", "type.favoriteFonts"] { tweak(&mut rules, path, |r| r.custom()); } + // RAW Defaults › Resolution drops a typed comma and alerts when it clamps (#18027), which the window's own + // whole-number row does not. + tweak(&mut rules, "rawDefaults.resolution", |r| r.custom()); // Rows that draw their own label or heading, so the window adds none: the Appearance page (Appearance Mode, the // themes), Rendering Mode's select, the Memory Usage block and its labelled percent checkbox. for path in ["interface.appearanceMode", "performance.renderingMode", "performance.memoryUsageMb", "performance.memoryUsagePercent"] {