mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Validate Fit Image dialog dimensions
This commit is contained in:
1 parent
de93ee2d38
commit
799d3bf41a
3 files changed
+262
-3
No files matched your search
@@ -724,9 +724,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
crate::widgets::hairline(ui);
|
||||
ui.add_space(8.0);
|
||||
crate::field_tab::begin(ui.ctx());
|
||||
if let Some(done) = dialog_body(app, ui, &d, &mut fields, id, interactive) {
|
||||
outcome = Some(done);
|
||||
}
|
||||
let fit_image_alert = if fit_image_range::owns(&fields) {
|
||||
fit_image_range::body(ui, &mut fields)
|
||||
} else {
|
||||
if let Some(done) = dialog_body(app, ui, &d, &mut fields, id, interactive) {
|
||||
outcome = Some(done);
|
||||
}
|
||||
None
|
||||
};
|
||||
crate::field_tab::end(ui.ctx(), tab);
|
||||
if let Some(Value::String(key)) = fields.remove(BROWSE_FIELD) {
|
||||
browse_field(app, d.id, &fields, &key);
|
||||
@@ -752,6 +757,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
apply_requested |= apply;
|
||||
});
|
||||
}
|
||||
if interactive
|
||||
&& outcome != Some(false)
|
||||
&& let Some(alert) = fit_image_alert
|
||||
{
|
||||
crate::panels::options_bar::range_alert(&mut app.ui, alert.message());
|
||||
if alert == fit_image_range::Alert::Invalid {
|
||||
outcome = None;
|
||||
}
|
||||
}
|
||||
// The frame around the content (Frame::popup's margin and stroke).
|
||||
ui.min_rect().expand(ui.spacing().menu_margin.sum().max_elem() + 2.0)
|
||||
});
|
||||
@@ -1171,6 +1185,14 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, Str
|
||||
|
||||
pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
|
||||
confirm_preflight(app, id)?;
|
||||
if let Some(dialog) = app.ui.dialog_mut(id).filter(|dialog| fit_image_range::owns(&dialog.fields))
|
||||
&& let Some(alert) = fit_image_range::validate(&mut dialog.fields)
|
||||
{
|
||||
crate::panels::options_bar::range_alert(&mut app.ui, alert.message());
|
||||
if alert == fit_image_range::Alert::Invalid {
|
||||
return Err(tl!(alert.message()).into());
|
||||
}
|
||||
}
|
||||
let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
|
||||
match d.kind {
|
||||
DialogKind::NewDocument => {
|
||||
@@ -1318,6 +1340,9 @@ pub mod filter_dialog;
|
||||
pub(super) mod filter_preview_ui;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) mod filter_preview_worker;
|
||||
mod fit_image_range;
|
||||
#[cfg(test)]
|
||||
mod fit_image_range_tests;
|
||||
pub mod gallery_ui;
|
||||
pub(crate) mod guide_edit;
|
||||
pub mod guide_layout_ui;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Fit Image's bounds belong to its dialog. The engine still accepts an unconstrained side.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::Fields;
|
||||
|
||||
const COMMAND: &str = "file.automate.fitImage";
|
||||
const RANGE: std::ops::RangeInclusive<f64> = 1.0..=300_000.0;
|
||||
const SIDES: [&str; 2] = ["width", "height"];
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Alert {
|
||||
Closest,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl Alert {
|
||||
pub(super) fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Closest => "A value between 1 and 300000 is required. Closest value inserted.",
|
||||
Self::Invalid => "Invalid numeric entry. A value between 1 and 300000 is required. Previous value inserted.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn owns(fields: &Fields) -> bool {
|
||||
fields.contains_key("__form") && fields.get("__command").and_then(Value::as_str) == Some(COMMAND)
|
||||
}
|
||||
|
||||
fn bounded(number: Option<f64>, alert: &Cell<Option<Alert>>) -> Option<f64> {
|
||||
let Some(number) = number.filter(|value| value.is_finite()) else {
|
||||
alert.set(Some(Alert::Invalid));
|
||||
return None;
|
||||
};
|
||||
if !RANGE.contains(&number) {
|
||||
alert.set(Some(Alert::Closest));
|
||||
}
|
||||
Some(number.clamp(*RANGE.start(), *RANGE.end()))
|
||||
}
|
||||
|
||||
/// Covers dialog confirmation when automation supplies values without rendering the fields.
|
||||
pub(super) fn validate(fields: &mut Fields) -> Option<Alert> {
|
||||
let mut result = None;
|
||||
for key in SIDES {
|
||||
let alert = Cell::new(None);
|
||||
let number = fields.get(key).and_then(|value| value.as_f64().or_else(|| value.as_str().and_then(crate::widgets::parse_num)));
|
||||
let value = bounded(number, &alert).or_else(|| fields.get("__formOrig")?.get(key)?.as_f64()).unwrap_or(*RANGE.start());
|
||||
fields.insert(key.into(), json!(value.clamp(*RANGE.start(), *RANGE.end()) as i64));
|
||||
// An invalid entry needs acknowledgment before the dialog can run.
|
||||
if result != Some(Alert::Invalid) {
|
||||
result = alert.get().or(result);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn body(ui: &mut egui::Ui, fields: &mut Fields) -> Option<Alert> {
|
||||
let mut alert = None;
|
||||
egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
|
||||
for key in crate::view_cmds::form_keys(fields) {
|
||||
match key.as_str() {
|
||||
"width" => alert = side(ui, fields, &key, tl!("Width")).or(alert),
|
||||
"height" => alert = side(ui, fields, &key, tl!("Height")).or(alert),
|
||||
"dontEnlarge" => {
|
||||
ui.label("");
|
||||
let mut enabled = fields.get(&key).and_then(Value::as_bool).unwrap_or(false);
|
||||
ui.checkbox(&mut enabled, tl!("Don't enlarge"));
|
||||
fields.insert(key, json!(enabled));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
alert
|
||||
}
|
||||
|
||||
fn side(ui: &mut egui::Ui, fields: &mut Fields, key: &str, label: &str) -> Option<Alert> {
|
||||
let Some(mut value) = fields.get(key).and_then(Value::as_i64) else {
|
||||
// Leave automation-supplied strings for the same validation at confirmation.
|
||||
ui.label(label);
|
||||
ui.label(fields.get(key).and_then(Value::as_str).unwrap_or_default());
|
||||
return None;
|
||||
};
|
||||
let alert = Cell::new(None);
|
||||
ui.label(label);
|
||||
crate::field_tab::register(ui.ctx(), ui.next_auto_id());
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut value)
|
||||
.range(RANGE)
|
||||
.clamp_existing_to_range(false)
|
||||
.update_while_editing(false)
|
||||
.custom_parser(|text| bounded(crate::widgets::parse_num(text), &alert)),
|
||||
)
|
||||
.accessible_name(label);
|
||||
fields.insert(key.into(), json!(value));
|
||||
alert.get()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use egui::{Event, Key, Modifiers, accesskit::Role};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{fit_image_range::Alert, show};
|
||||
use crate::{PhotocraftApp, Services, state::DialogKind};
|
||||
|
||||
const FIT_IMAGE: &str = "file.automate.fitImage";
|
||||
|
||||
fn open() -> (Harness<'static, PhotocraftApp>, u64) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
let ctx = h.ctx.clone();
|
||||
let id = crate::menus::invoke(h.state_mut(), &ctx, FIT_IMAGE, json!({})).unwrap()["dialog"].as_u64().unwrap();
|
||||
h.run_steps(4);
|
||||
(h, id)
|
||||
}
|
||||
|
||||
fn type_side(h: &mut Harness<'static, PhotocraftApp>, label: &str, input: &str) {
|
||||
let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().label() == Some(label)).unwrap();
|
||||
field.click();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
|
||||
if input.is_empty() {
|
||||
h.key_press(Key::Backspace);
|
||||
} else {
|
||||
h.event(Event::Text(input.into()));
|
||||
}
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn field(h: &Harness<'_, PhotocraftApp>, id: u64, key: &str) -> Value {
|
||||
h.state().ui.dialogs.iter().find(|dialog| dialog.id == id).unwrap().fields[key].clone()
|
||||
}
|
||||
|
||||
fn alert(h: &Harness<'_, PhotocraftApp>, expected: Alert) {
|
||||
let top = h.state().ui.dialogs.last().unwrap();
|
||||
assert_eq!(top.kind, DialogKind::Error);
|
||||
assert_eq!(top.fields["message"], expected.message());
|
||||
}
|
||||
|
||||
fn dimensions(h: &Harness<'_, PhotocraftApp>) -> (u32, u32) {
|
||||
let size = h.state().session.active().unwrap().doc.size;
|
||||
(size.width, size.height)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_clamps_both_sides_and_the_next_tab_accepts_each_boundary() {
|
||||
let (mut h, id) = open();
|
||||
for (label, key, input, boundary) in [("Width", "width", "-50", 1), ("Height", "height", "300001", 300_000)] {
|
||||
type_side(&mut h, label, input);
|
||||
h.key_press(Key::Tab);
|
||||
h.run_steps(4);
|
||||
alert(&h, Alert::Closest);
|
||||
assert_eq!(field(&h, id, key), boundary);
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(3);
|
||||
|
||||
type_side(&mut h, label, &boundary.to_string());
|
||||
h.key_press(Key::Tab);
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.dialogs.len(), 1);
|
||||
assert_eq!(field(&h, id, key), boundary);
|
||||
}
|
||||
assert_eq!(dimensions(&h), (400, 300));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_and_empty_entries_restore_the_last_accepted_value() {
|
||||
let (mut h, id) = open();
|
||||
type_side(&mut h, "Width", "600/2");
|
||||
h.key_press(Key::Tab);
|
||||
h.run_steps(4);
|
||||
assert_eq!(field(&h, id, "width"), 300);
|
||||
for input in ["abc", "", "NaN", "1/0", "1e999", &"9".repeat(1100)] {
|
||||
type_side(&mut h, "Width", input);
|
||||
h.key_press(Key::Tab);
|
||||
h.run_steps(4);
|
||||
alert(&h, Alert::Invalid);
|
||||
assert_eq!(field(&h, id, "width"), 300, "{input}");
|
||||
assert_eq!(field(&h, id, "height"), 300);
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_on_submit_resizes_once_using_one_pixel() {
|
||||
for click in [false, true] {
|
||||
let (mut h, id) = open();
|
||||
h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("height".into(), json!(1000));
|
||||
h.run_steps(2);
|
||||
let past = h.state().session.active().unwrap().history.past_len();
|
||||
type_side(&mut h, "Width", "0");
|
||||
if click {
|
||||
h.get_by_label("OK").click();
|
||||
} else {
|
||||
h.key_press(Key::Enter);
|
||||
}
|
||||
h.run_steps(4);
|
||||
assert_eq!(dimensions(&h), (1, 1));
|
||||
assert_eq!(h.state().session.active().unwrap().history.past_len(), past + 1);
|
||||
assert!(h.state().ui.dialogs.iter().all(|dialog| dialog.id != id));
|
||||
alert(&h, Alert::Closest);
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(dimensions(&h), (400, 300));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_submit_keeps_the_dialog_open_without_resizing() {
|
||||
let (mut h, id) = open();
|
||||
type_side(&mut h, "Width", "abc");
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(4);
|
||||
alert(&h, Alert::Invalid);
|
||||
assert_eq!(field(&h, id, "width"), 400);
|
||||
assert_eq!(dimensions(&h), (400, 300));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn programmatic_dialog_confirmation_validates_both_sides() {
|
||||
let (mut h, id) = open();
|
||||
let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields;
|
||||
fields.insert("width".into(), json!("abc"));
|
||||
fields.insert("height".into(), json!(-1));
|
||||
assert!(super::confirm(h.state_mut(), id).is_err());
|
||||
alert(&h, Alert::Invalid);
|
||||
assert_eq!(field(&h, id, "width"), 400);
|
||||
assert_eq!(field(&h, id, "height"), 1);
|
||||
assert_eq!(dimensions(&h), (400, 300));
|
||||
}
|
||||
Reference in new issue
Block a user