diff --git a/crates/ui-egui/src/dialogs/guide_layout_ui.rs b/crates/ui-egui/src/dialogs/guide_layout_ui.rs index f44be59a84e..9fc3c72dd5c 100644 --- a/crates/ui-egui/src/dialogs/guide_layout_ui.rs +++ b/crates/ui-egui/src/dialogs/guide_layout_ui.rs @@ -2,6 +2,7 @@ use egui::{Color32, Stroke}; use photocraft_doc::{Document, Guides}; +use photocraft_engine::prefs::Unit; use serde_json::{Map, Value, json}; use crate::{PhotocraftApp, theme::Tokens, widgets}; @@ -31,6 +32,113 @@ pub fn owns(f: &Map) -> bool { f.contains_key(MARK) } +fn ruler_unit(app: &PhotocraftApp) -> Unit { + app.session.prefs().units_and_rulers.rulers +} + +fn with_unit(value: &str, unit: Unit) -> String { + format!("{value} {}", unit.suffix()) +} + +/// Decimals the reference application's guide layout fields show in every unit, trailing zeros +/// dropped: 20 px at 72 ppi opens as "0.706 cm", a typed "13.5 px" stays "13.5 px". +const FIELD_DECIMALS: usize = 3; + +/// Document pixels in the active document's ruler unit: "0.706 cm", "0.278 in", "20 px". +pub(crate) fn in_ruler_unit(app: &PhotocraftApp, px: f64, along_x: bool) -> String { + let units = &app.session.prefs().units_and_rulers; + let (dpi, extent) = app.session.active().map_or((72.0, 1.0), |st| { + let d = &st.doc; + (f64::from(d.resolution_dpi.max(1.0)), f64::from(if along_x { d.size.width } else { d.size.height })) + }); + let v = units.rulers.from_px(px, dpi, extent, units.point_size.per_inch()); + with_unit(&photocraft_engine::prefs::fmt_decimals(v, FIELD_DECIMALS), units.rulers) +} + +/// The unit a field's text names, or `fallback` when it names none. +fn text_unit(text: &str, fallback: Unit) -> Unit { + Unit::parse_length(text).and_then(|(_, unit)| unit).unwrap_or(fallback) +} + +/// The text a field settles on when it loses focus. A bare number takes `unit`, the unit the +/// field showed when it got focus (after "2 mm", a typed "5" becomes "5 mm"). +fn normalize_field_text(text: &str, app: &PhotocraftApp, along_x: bool, optional: bool, unit: Unit) -> Option { + let t = text.trim(); + if t.is_empty() { + if optional { + return Some(String::new()); + } else { + return Some(in_ruler_unit(app, 0.0, along_x)); + } + } + let (v, unit) = match Unit::parse_length(t) { + Some((v, typed)) => (v, typed.unwrap_or(unit)), + None => (widgets::parse_num(t)?, unit), + }; + Some(with_unit(&photocraft_engine::prefs::fmt_decimals(v, FIELD_DECIMALS), unit)) +} + +fn parse_length_str(text: &str, app: &PhotocraftApp, along_x: bool) -> Option { + let t = text.trim(); + if t.is_empty() { + return None; + } + let units = &app.session.prefs().units_and_rulers; + let (dpi, extent) = app.session.active().map_or((72.0, 1.0), |st| { + let d = &st.doc; + (f64::from(d.resolution_dpi.max(1.0)), f64::from(if along_x { d.size.width } else { d.size.height })) + }); + let ppi = units.point_size.per_inch(); + let ruler = units.rulers; + + if let Some((n, unit)) = Unit::parse_length(t) { + Some(unit.unwrap_or(ruler).to_px(n, dpi, extent, ppi)) + } else { + widgets::parse_num(t).map(|n| ruler.to_px(n, dpi, extent, ppi)) + } +} + +/// The percent a field's text gives ("10%", or a bare number while the rulers are in percent). +/// Percent stays percent all the way to the engine, which takes it of each target, so a selected +/// artboard smaller than the document gets its own share, not the document's. +fn percent_of(text: &str, ruler: Unit) -> Option { + match Unit::parse_length(text) { + Some((n, Some(Unit::Percent))) => Some(n), + Some((n, None)) if ruler == Unit::Percent => Some(n), + Some(_) => None, + None if ruler == Unit::Percent => widgets::parse_num(text), + None => None, + } +} + +fn format_stored_length(app: &PhotocraftApp, val: &Value, along_x: bool, optional: bool) -> Value { + match val { + Value::Number(n) => { + let px = n.as_f64().unwrap_or(0.0); + if optional && px <= 0.0 { Value::Null } else { json!(in_ruler_unit(app, px, along_x)) } + } + Value::String(s) => { + let t = s.trim(); + if t.is_empty() { + if optional { Value::Null } else { json!(in_ruler_unit(app, 0.0, along_x)) } + } else if let Some(pct) = percent_of(t, ruler_unit(app)) { + if optional && pct <= 0.0 { Value::Null } else { json!(with_unit(&photocraft_engine::prefs::fmt_decimals(pct, FIELD_DECIMALS), Unit::Percent)) } + } else if let Some(px) = parse_length_str(t, app, along_x) { + if optional && px <= 0.0 { Value::Null } else { json!(in_ruler_unit(app, px, along_x)) } + } else { + json!(s) + } + } + _ => { + if optional { + Value::Null + } else { + json!(in_ruler_unit(app, 0.0, along_x)) + } + } + } +} + /// Alt+Cancel (Reset): factory New Guide Layout values, not the last-used remembered layout. pub fn reset(app: &PhotocraftApp, f: &mut Map) { if !owns(f) { @@ -51,10 +159,12 @@ pub fn reset(app: &PhotocraftApp, f: &mut Map) { f.insert("__preset".into(), json!("custom")); f.insert("width".into(), Value::Null); f.insert("height".into(), Value::Null); - let margin = f.get("margin").cloned().unwrap_or(json!(0)); - if !margin.is_array() { - f.insert("margin".into(), json!([margin.clone(), margin.clone(), margin.clone(), margin])); - } + f.insert("gutter".into(), json!(in_ruler_unit(app, 20.0, true))); + f.insert("rowGutter".into(), json!(in_ruler_unit(app, 0.0, false))); + f.insert( + "margin".into(), + json!([in_ruler_unit(app, 0.0, false), in_ruler_unit(app, 0.0, true), in_ruler_unit(app, 0.0, false), in_ruler_unit(app, 0.0, true)]), + ); f.insert("__preview".into(), json!(true)); } @@ -80,18 +190,93 @@ pub fn open(app: &mut PhotocraftApp) -> u64 { f.entry("__preset").or_insert_with(|| json!("custom")); f.entry("width").or_insert(Value::Null); f.entry("height").or_insert(Value::Null); - let margin = f.get("margin").cloned().unwrap_or(json!(0)); - if !margin.is_array() { - f.insert("margin".into(), json!([margin.clone(), margin.clone(), margin.clone(), margin])); + + // Format fields in active ruler unit when opening the dialog + if let Some(gutter) = f.get("gutter").cloned() { + f.insert("gutter".into(), format_stored_length(app, &gutter, true, false)); + } else { + f.insert("gutter".into(), json!(in_ruler_unit(app, 20.0, true))); } + if let Some(row_gutter) = f.get("rowGutter").cloned() { + f.insert("rowGutter".into(), format_stored_length(app, &row_gutter, false, false)); + } else { + f.insert("rowGutter".into(), json!(in_ruler_unit(app, 0.0, false))); + } + if let Some(width) = f.get("width").cloned() { + f.insert("width".into(), format_stored_length(app, &width, true, true)); + } + if let Some(height) = f.get("height").cloned() { + f.insert("height".into(), format_stored_length(app, &height, false, true)); + } + + let margin = f.get("margin").cloned().unwrap_or(json!(0)); + let mut margins = if let Value::Array(a) = margin { if a.len() == 4 { a } else { vec![json!(0); 4] } } else { vec![margin.clone(); 4] }; + // Top, Left, Bottom, Right: Left and Right measure along x. + for (m, along_x) in margins.iter_mut().zip([false, true, false, true]) { + *m = format_stored_length(app, m, along_x, false); + } + f.insert("margin".into(), Value::Array(margins)); + for key in ["__previewGuides", "__previewParams", "__previewSource"] { f.remove(key); } app.ui.open_dialog(crate::state::DialogKind::Command, f) } -/// Preserve legacy command parameter names for automation and remembered defaults. +fn parse_length_value(val: Option<&Value>, app: Option<&PhotocraftApp>, along_x: bool, optional: bool) -> Value { + match val { + Some(Value::Number(n)) => { + if let Some(num) = n.as_f64() { + if optional && num <= 0.0 { Value::Null } else { json!(num) } + } else { + Value::Null + } + } + Some(Value::String(s)) => { + let t = s.trim(); + if t.is_empty() { + if optional { Value::Null } else { json!(0.0) } + } else if let Some(pct) = percent_of(t, app.map_or(Unit::Pixels, ruler_unit)) { + if optional && pct <= 0.0 { Value::Null } else { json!(format!("{pct}%")) } + } else { + let (dpi, extent, ppi, ruler) = match app { + Some(app) => { + let units = &app.session.prefs().units_and_rulers; + let (dpi, extent) = app.session.active().map_or((72.0, 1.0), |st| { + let d = &st.doc; + (f64::from(d.resolution_dpi.max(1.0)), f64::from(if along_x { d.size.width } else { d.size.height })) + }); + (dpi, extent, units.point_size.per_inch(), units.rulers) + } + None => (72.0, 1.0, 72.0, Unit::Pixels), + }; + + if let Some((n, unit)) = Unit::parse_length(t) { + let px = unit.unwrap_or(ruler).to_px(n, dpi, extent, ppi); + if optional && px <= 0.0 { Value::Null } else { serde_json::Number::from_f64(px).map(Value::Number).unwrap_or(Value::Null) } + } else if let Some(n) = widgets::parse_num(t) { + let px = ruler.to_px(n, dpi, extent, ppi); + if optional && px <= 0.0 { Value::Null } else { serde_json::Number::from_f64(px).map(Value::Number).unwrap_or(Value::Null) } + } else { + json!(s) + } + } + } + _ => { + if optional { + Value::Null + } else { + json!(0.0) + } + } + } +} + pub fn params(f: &Map) -> Value { + params_with(None, f) +} + +pub fn params_with(app: Option<&PhotocraftApp>, f: &Map) -> Value { let mut p: Map = ["columns", "rows", "width", "height", "gutter", "rowGutter", "margin", "centerColumns", "clearExisting", "target"] .into_iter() .filter_map(|k| f.get(k).cloned().map(|v| (k.to_string(), v))) @@ -103,17 +288,28 @@ pub fn params(f: &Map) -> Value { } if !on(f, "__marginEnabled", true) { p.insert("margin".into(), json!(0)); + } else if let Some(margin_val) = f.get("margin") { + let parsed = match margin_val { + Value::Array(arr) if arr.len() == 4 => { + let top = parse_length_value(Some(&arr[0]), app, false, false); + let left = parse_length_value(Some(&arr[1]), app, true, false); + let bottom = parse_length_value(Some(&arr[2]), app, false, false); + let right = parse_length_value(Some(&arr[3]), app, true, false); + json!([top, left, bottom, right]) + } + Value::Array(_) => json!(0), + other => { + let m = parse_length_value(Some(other), app, false, false); + json!([m.clone(), m.clone(), m.clone(), m]) + } + }; + p.insert("margin".into(), parsed); } - for key in ["width", "height"] { - if let Some(Value::String(s)) = p.get(key) { - let value = if s.trim().is_empty() { - Value::Null - } else { - widgets::parse_num(s).and_then(serde_json::Number::from_f64).map(Value::Number).unwrap_or_else(|| json!(s)) - }; - p.insert(key.into(), value); - } - } + p.insert("width".into(), parse_length_value(f.get("width"), app, true, true)); + p.insert("height".into(), parse_length_value(f.get("height"), app, false, true)); + p.insert("gutter".into(), parse_length_value(f.get("gutter"), app, true, false)); + p.insert("rowGutter".into(), parse_length_value(f.get("rowGutter"), app, false, false)); + // A disabled axis must not be rejected for a stale width or gap typed before disabling it. for (key, size, gap) in [("columns", "width", "gutter"), ("rows", "height", "rowGutter")] { if p.get(key).and_then(Value::as_u64) == Some(0) { @@ -133,7 +329,7 @@ fn calculate(app: &PhotocraftApp, f: &Map) -> Result) -> Result, key: &str, label: &str, value } -fn number(ui: &mut egui::Ui, f: &mut Map, key: &str, name: &str, count: bool) { +fn count_field(ui: &mut egui::Ui, f: &mut Map, key: &str, name: &str) { let mut value = f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; - if widgets::value_field(ui, &mut value, (if count { 1.0 } else { 0.0 })..=if count { 1000.0 } else { 300_000.0 }, if count { "" } else { "px" }, 68.0) + if widgets::value_field(ui, &mut value, 1.0..=1000.0, "", 68.0) .accessible_name(tl!(name)) .changed() // A disabled field still clamps its value into range (a zero count to 1); writing that // back would switch the axis on through its `positive` fallback (#5625). && ui.is_enabled() { - f.insert(key.into(), if count { json!(value.round() as u64) } else { json!(value) }); + f.insert(key.into(), json!(value.round() as u64)); } } -fn optional(ui: &mut egui::Ui, f: &mut Map, key: &str, label: egui::Id) { - let mut value = match f.get(key) { - Some(Value::String(s)) => s.clone(), - Some(v) if v.is_number() => v.to_string(), - _ => String::new(), +/// Tab selects the text even while a mouse button is held; a click places the caret. +fn should_select_all(response: &egui::Response, ui: &egui::Ui) -> bool { + response.gained_focus() + && (crate::field_tab::reached(ui.ctx(), response.id) + || (!response.clicked() && !response.dragged() && !ui.input(|i| i.pointer.any_click() || i.pointer.any_down()))) +} + +fn length_field(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, key: &str, label: egui::Id, optional: bool, along_x: bool) { + let mut value = f.get(key).cloned().unwrap_or(Value::Null); + let response = unit_edit(app, ui, key, &mut value, optional, along_x, 68.0).labelled_by(label); + if f.get(key).unwrap_or(&Value::Null) != &value { + f.insert(key.into(), value); + } + if optional { + response.on_hover_text(tl!("Leave empty for automatic size")); + } +} + +/// A length field that takes any unit. Its text is stored as typed and settles on lost focus. +fn unit_edit(app: &PhotocraftApp, ui: &mut egui::Ui, id_salt: &str, value: &mut Value, optional: bool, along_x: bool, width: f32) -> egui::Response { + let mut text = match value { + Value::String(s) => s.clone(), + Value::Number(n) => { + let px = n.as_f64().unwrap_or(0.0); + if optional && px <= 0.0 { String::new() } else { in_ruler_unit(app, px, along_x) } + } + _ if optional => String::new(), + _ => in_ruler_unit(app, 0.0, along_x), }; let t = Tokens::get(ui.ctx()); - let response = ui - .add(egui::TextEdit::singleline(&mut value).id_salt(key).desired_width(60.0).font(crate::theme::mono(12.0)).background_color(t.field)) - .labelled_by(label); + let response = ui.add(egui::TextEdit::singleline(&mut text).id_salt(id_salt).desired_width(width).font(crate::theme::mono(12.0)).background_color(t.field)); if ui.is_enabled() { crate::field_tab::register(ui.ctx(), response.id); } + let ruler = ruler_unit(app); if response.gained_focus() { - crate::field_tab::select_all(ui.ctx(), response.id, &value); + let unit = text_unit(&text, ruler); + ui.ctx().data_mut(|d| d.insert_temp(response.id, unit)); + } + if should_select_all(&response, ui) { + crate::field_tab::select_all(ui.ctx(), response.id, &text); } if response.changed() { - f.insert(key.into(), json!(value)); + *value = json!(text); } - response.on_hover_text(tl!("Leave empty for automatic size")); + if response.lost_focus() { + let unit = ui.ctx().data_mut(|d| d.remove_temp::(response.id)).unwrap_or(ruler); + // Leaving a field untouched keeps its stored value (an automatic size stays empty), so + // tabbing past it does not turn a named preset into Custom. + if let Some(normalized) = normalize_field_text(&text, app, along_x, optional, unit) + && normalized != text + { + *value = json!(normalized); + } + } + response } fn group(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R { @@ -230,7 +477,7 @@ fn group(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R { egui::Frame::new().stroke(Stroke::new(1.0, t.field_border)).inner_margin(8).show(ui, |ui| ui.vertical(content).inner).inner } -fn axis(ui: &mut egui::Ui, f: &mut Map, rows: bool) { +fn axis(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, rows: bool) { let (toggle, count, size, gap, title, size_label) = if rows { ("__rowsEnabled", "rows", "height", "rowGutter", tl!("Rows"), tl!("Height")) } else { @@ -245,13 +492,13 @@ fn axis(ui: &mut egui::Ui, f: &mut Map, rows: bool) { ui.add_enabled_ui(enabled, |ui| { egui::Grid::new(count).spacing([8.0, 6.0]).show(ui, |ui| { ui.label(tl!("Number")); - number(ui, f, count, "Number", true); + count_field(ui, f, count, "Number"); ui.end_row(); let size_label_resp = ui.label(size_label); - optional(ui, f, size, size_label_resp.id); + length_field(app, ui, f, size, size_label_resp.id, true, !rows); ui.end_row(); - ui.label(tl!("Spacing")); - number(ui, f, gap, "Spacing", false); + let gap_label_resp = ui.label(tl!("Spacing")); + length_field(app, ui, f, gap, gap_label_resp.id, false, !rows); ui.end_row(); }); }); @@ -275,18 +522,26 @@ fn main_fields(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map { let (cols, rows, gap) = match preset.as_str() { - "five" => (5, 3, 0), - "eight" => (8, 0, 20), - _ => (12, 0, 24), + "five" => (5, 3, 0.0), + "eight" => (8, 0, 20.0), + _ => (12, 0, 24.0), }; for (k, v) in [ ("columns", json!(cols)), ("rows", json!(rows)), - ("gutter", json!(gap)), - ("rowGutter", json!(0)), + ("gutter", json!(in_ruler_unit(app, gap, true))), + ("rowGutter", json!(in_ruler_unit(app, 0.0, false))), ("width", Value::Null), ("height", Value::Null), - ("margin", json!([0, 0, 0, 0])), + ( + "margin", + json!([ + in_ruler_unit(app, 0.0, false), + in_ruler_unit(app, 0.0, true), + in_ruler_unit(app, 0.0, false), + in_ruler_unit(app, 0.0, true) + ]), + ), ("__columnsEnabled", json!(true)), ("__rowsEnabled", json!(rows > 0)), ("__marginEnabled", json!(true)), @@ -328,24 +583,30 @@ fn main_fields(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { - let before = (params(f), on(f, "__preview", true), f.get("color").cloned()); + let before = (params_with(Some(app), f), on(f, "__preview", true), f.get("color").cloned()); let mut outcome = None; ui.horizontal_top(|ui| { ui.vertical(|ui| { @@ -390,7 +651,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, match calculate(app, f) { Ok(guides) => { f.insert("__previewGuides".into(), json!(guides)); - f.insert("__previewParams".into(), params(f)); + f.insert("__previewParams".into(), params_with(Some(app), f)); f.insert("__previewSource".into(), source(app)); } Err(error) => { @@ -401,7 +662,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, outcome = Some(true); } // The canvas paints before the dialog. Schedule the frame that displays this draft edit. - if before != (params(f), on(f, "__preview", true), f.get("color").cloned()) { + if before != (params_with(Some(app), f), on(f, "__preview", true), f.get("color").cloned()) { ui.ctx().request_repaint(); } outcome diff --git a/crates/ui-egui/src/dialogs/guide_layout_ui/tests.rs b/crates/ui-egui/src/dialogs/guide_layout_ui/tests.rs index 673f1663bf0..defb30814c4 100644 --- a/crates/ui-egui/src/dialogs/guide_layout_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/guide_layout_ui/tests.rs @@ -73,7 +73,7 @@ fn tab_includes_optional_sizes_and_shift_tab_selects_their_text() { assert_eq!((f["columns"].as_u64(), f["rows"].as_u64()), (Some(4), Some(2))); assert_eq!(params(f)["width"], 120.0); assert_eq!(params(f)["height"], 90.0); - assert_eq!(f["gutter"], 12.0); + assert_eq!(params(f)["gutter"], 12.0); h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Tab); h.run_steps(2); h.event(egui::Event::Text("3".into())); @@ -101,7 +101,7 @@ fn tab_skips_disabled_rows_and_margins() { let f = &h.state().ui.dialogs.first().unwrap().fields; assert_eq!(f["columns"], 6, "Tab wraps after column spacing, skipping disabled row and margin fields"); assert_eq!(params(f)["width"], 100.0); - assert_eq!(f["gutter"], 4.0); + assert_eq!(params(f)["gutter"], 4.0); } /// The disabled Number field must not clamp a zero count to 1 and so switch its axis on (#5625). @@ -173,7 +173,8 @@ fn alt_reset_restores_factory_layout() { app.ui.dialog_mut(id).unwrap().fields = fields; let f = &app.ui.dialog_mut(id).unwrap().fields; assert_eq!(f["columns"], json!(8)); - assert_eq!(f["gutter"], json!(20)); + assert_eq!(params(f)["gutter"], 20.0); + assert_eq!(f["gutter"], "20 px"); assert_eq!(f["__preset"], json!("custom")); assert!(app.ui.dialogs.iter().any(|d| d.id == id)); } @@ -324,3 +325,204 @@ fn preview_cache_tracks_document_revision() { app.run(COMMAND, json!({"margin":23})).unwrap(); assert!(preview(&app, &app.session.active().unwrap().doc).unwrap().0.vertical.contains(&23.0)); } + +#[test] +fn units_can_be_typed_and_convert_on_reopen() { + let mut app = app(); + let id = open(&mut app); + let f = { + let dialog = app.ui.dialog_mut(id).unwrap(); + dialog.fields.insert("gutter".into(), json!("1 in")); + dialog.fields.insert("margin".into(), json!(["2 cm", "10 mm", "0.5 in", "72 pt"])); + dialog.fields.clone() + }; + let p = params_with(Some(&app), &f); + assert_eq!(p["gutter"], 72.0); + let m = p["margin"].as_array().unwrap(); + assert!((m[0].as_f64().unwrap() - 2.0 / 2.54 * 72.0).abs() < 1e-3); + assert!((m[1].as_f64().unwrap() - 1.0 / 2.54 * 72.0).abs() < 1e-3); + assert_eq!(m[2], 36.0); + assert_eq!(m[3], 72.0); + + crate::dialogs::confirm(&mut app, id).unwrap(); + + app.session.prefs.edit(|p| p.units_and_rulers.rulers = photocraft_engine::prefs::Unit::Inches); + + let reopened = open(&mut app); + let rf = &app.ui.dialog_mut(reopened).unwrap().fields; + assert_eq!(rf["gutter"], "1 in"); + assert_eq!(rf["margin"][2], "0.5 in"); + assert_eq!(rf["margin"][3], "1 in"); +} + +#[test] +fn normalization_appends_the_field_unit_and_ensures_space() { + use photocraft_engine::prefs::Unit; + let mut app = app(); + let px = Unit::Pixels; + assert_eq!(normalize_field_text("10", &app, true, false, px), Some("10 px".into())); + assert_eq!(normalize_field_text("10px", &app, true, false, px), Some("10 px".into())); + assert_eq!(normalize_field_text("10cm", &app, true, false, px), Some("10 cm".into())); + assert_eq!(normalize_field_text("2in", &app, true, false, px), Some("2 in".into())); + assert_eq!(normalize_field_text("5mm", &app, false, false, px), Some("5 mm".into())); + + app.session.prefs.edit(|p| p.units_and_rulers.rulers = Unit::Centimeters); + assert_eq!(normalize_field_text("10", &app, true, false, Unit::Centimeters), Some("10 cm".into())); + assert_eq!(normalize_field_text("2.5", &app, true, false, Unit::Centimeters), Some("2.5 cm".into())); + assert_eq!(normalize_field_text("20px", &app, true, false, Unit::Centimeters), Some("20 px".into())); +} + +/// The reference application keeps three decimals in every unit: a typed "13.5 px" stays, it is +/// not rounded to whole pixels, and 20 px at 72 ppi opens as "0.706 cm". +#[test] +fn fields_keep_three_decimals_in_every_unit() { + use photocraft_engine::prefs::Unit; + let mut app = app(); + assert_eq!(normalize_field_text("13.5 px", &app, true, false, Unit::Pixels), Some("13.5 px".into())); + assert_eq!(normalize_field_text("5.123456", &app, true, false, Unit::Millimeters), Some("5.123 mm".into())); + app.session.prefs.edit(|p| p.units_and_rulers.rulers = Unit::Centimeters); + let dpi = f64::from(app.session.active().unwrap().doc.resolution_dpi); + assert_eq!(in_ruler_unit(&app, dpi * 0.70556 / 2.54, true), "0.706 cm"); +} + +/// After "2 mm", a bare number typed into the field is in millimetres, not the ruler unit. +#[test] +fn a_bare_number_takes_the_unit_the_field_showed() { + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("columns".into(), json!(2)); + f.insert("__rowsEnabled".into(), json!(false)); + f.insert("__marginEnabled".into(), json!(false)); + f.insert("gutter".into(), json!("2 mm")); + let mut h = harness(app); + h.run_steps(3); + // Number, Width, then Spacing (gutter). + for _ in 0..3 { + h.key_press(egui::Key::Tab); + h.run_steps(2); + } + h.event(egui::Event::Text("5".into())); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.first().unwrap().fields["gutter"], "5 mm"); +} + +/// Tabbing past fields without typing keeps a named preset: an empty Width stays automatic. +#[test] +fn tabbing_through_untouched_fields_keeps_the_preset() { + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("__preset".into(), json!("eight")); + f.insert("columns".into(), json!(8)); + f.insert("rows".into(), json!(0)); + f.insert("__rowsEnabled".into(), json!(false)); + f.insert("__marginEnabled".into(), json!(false)); + f.insert("width".into(), Value::Null); + f.insert("gutter".into(), json!(20)); + let mut h = harness(app); + h.run_steps(3); + // Number, Width, Spacing, then back to Number. + for _ in 0..4 { + h.key_press(egui::Key::Tab); + h.run_steps(2); + } + let f = &h.state().ui.dialogs.first().unwrap().fields; + assert_eq!(f["__preset"], "eight"); + assert_eq!(f["width"], Value::Null); +} + +fn gutter_dialog(gutter: &str) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("columns".into(), json!(2)); + f.insert("__rowsEnabled".into(), json!(false)); + f.insert("__marginEnabled".into(), json!(false)); + f.insert("gutter".into(), json!(gutter)); + let mut h = harness(app); + h.run_steps(3); + h +} + +/// Tab from the dialog's start to Spacing (gutter): Number, Width, then Spacing. +fn tab_to_gutter(h: &mut egui_kittest::Harness<'static, PhotocraftApp>) { + for _ in 0..3 { + h.key_press(egui::Key::Tab); + h.run_steps(2); + } +} + +/// Enter straight after typing a bare number applies it in the unit the field showed: "5" typed +/// over "2 mm" is 5 mm, not 5 px. +#[test] +fn enter_after_a_bare_number_applies_the_unit_the_field_showed() { + let mut h = gutter_dialog("2 mm"); + tab_to_gutter(&mut h); + h.event(egui::Event::Text("5".into())); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + let app = h.state(); + assert!(app.ui.dialogs.is_empty(), "Enter applies the layout"); + // Two automatic columns: the gutter is the gap between the second and third guide. + let v = &app.session.active().unwrap().doc.guides.vertical; + let gutter = v[2] - v[1]; + assert!((gutter - 5.0 / 25.4 * 72.0).abs() < 1e-2, "gutter {gutter} px in {v:?}"); +} + +/// A unitless length set over automation is remembered as the length it applied, so a later +/// ruler unit change does not reinterpret it. +#[test] +fn remembered_lengths_keep_their_size_when_the_ruler_unit_changes() { + use photocraft_engine::prefs::Unit; + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("gutter".into(), json!("5")); + f.insert("margin".into(), json!(["5", "5", "5", "5"])); + crate::dialogs::confirm(&mut app, id).unwrap(); + app.session.prefs.edit(|p| p.units_and_rulers.rulers = Unit::Millimeters); + let reopened = open(&mut app); + let rf = &app.ui.dialog_mut(reopened).unwrap().fields; + assert_eq!(rf["gutter"], "1.764 mm"); + assert_eq!(rf["margin"][0], "1.764 mm"); +} + +/// Tab selects the field it reaches even while a mouse button is held, so typing replaces the +/// value instead of appending to it. +#[test] +fn tab_selects_the_field_while_a_mouse_button_is_held() { + let mut h = gutter_dialog("2 mm"); + let at = egui_kittest::kittest::Queryable::get_all_by_label(&h, "Number").next().unwrap().rect().center(); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + tab_to_gutter(&mut h); + h.event(egui::Event::Text("5".into())); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.first().unwrap().fields["gutter"], "5"); +} + +/// Percent is of each selected artboard, not of the document: 50% of a 140 x 40 board is a +/// 70 px column, centred in it; the field reopens still in percent. +#[test] +fn percent_is_of_the_selected_artboard_and_stays_percent() { + let mut app = app(); + app.run("layer.new.artboard", json!({"rect": [200, 100, 140, 40]})).unwrap(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("target".into(), json!("selectedArtboards")); + f.insert("columns".into(), json!(1)); + f.insert("width".into(), json!("50 %")); + f.insert("centerColumns".into(), json!(true)); + f.insert("clearExisting".into(), json!(true)); + f.insert("__rowsEnabled".into(), json!(false)); + f.insert("__marginEnabled".into(), json!(false)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let g = &app.session.active().unwrap().doc.guides; + assert!(g.vertical.contains(&235.0) && g.vertical.contains(&305.0), "{:?}", g.vertical); + let reopened = open(&mut app); + assert_eq!(app.ui.dialog_mut(reopened).unwrap().fields["width"], "50 %"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 67c823b5c11..3170183d772 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -607,8 +607,8 @@ fn new_guide_layout_remembers_successful_values_not_cancelled_edits() { let (mut app, ctx) = app_with(1); let first = menu(&mut app, &ctx, "view.newGuideLayout", json!({})).unwrap()["dialog"].as_u64().unwrap(); assert_eq!(app.ui.dialog_mut(first).unwrap().fields["columns"], 8); - assert_eq!(app.ui.dialog_mut(first).unwrap().fields["gutter"], 20); - for (key, value) in [("columns", json!(2)), ("gutter", json!(0)), ("rows", json!(2)), ("rowGutter", json!(0))] { + assert_eq!(app.ui.dialog_mut(first).unwrap().fields["gutter"], "20 px"); + for (key, value) in [("columns", json!(2)), ("gutter", json!("0 px")), ("rows", json!(2)), ("rowGutter", json!("0 px"))] { app.ui.dialog_mut(first).unwrap().fields.insert(key.into(), value); } crate::dialogs::confirm(&mut app, first).unwrap(); @@ -616,9 +616,9 @@ fn new_guide_layout_remembers_successful_values_not_cancelled_edits() { let second = menu(&mut app, &ctx, "view.newGuideLayout", json!({})).unwrap()["dialog"].as_u64().unwrap(); let fields = &app.ui.dialog_mut(second).unwrap().fields; assert_eq!(fields["columns"], 2); - assert_eq!(fields["gutter"], 0); + assert_eq!(fields["gutter"], "0 px"); assert_eq!(fields["rows"], 2); - assert_eq!(fields["rowGutter"], 0); + assert_eq!(fields["rowGutter"], "0 px"); assert_eq!(fields["clearExisting"], false); // A cancelled edit must not replace the last successfully used values. app.ui.dialog_mut(second).unwrap().fields.insert("columns".into(), json!(9)); diff --git a/crates/ui-egui/src/widgets/field_tab.rs b/crates/ui-egui/src/widgets/field_tab.rs index 79d82170291..e50c009f566 100644 --- a/crates/ui-egui/src/widgets/field_tab.rs +++ b/crates/ui-egui/src/widgets/field_tab.rs @@ -23,6 +23,10 @@ fn pending_id() -> Id { Id::unique("pc-field-tab-pending") } +fn reached_id() -> Id { + Id::unique("pc-field-tab-reached") +} + /// Give `id` the focus from the next frame on. Focusing a widget after it was laid out would /// never read as "gained focus" to it (egui compares with the focus at the start of the frame), /// and that is what selects a field's text; so the move waits for [`take_step`] next frame. @@ -33,9 +37,14 @@ pub fn focus(ctx: &Context, id: Id) { /// Tab (+1) or ⇧Tab (−1) pressed this frame, taken from the input so nothing else acts on it; /// 0 when neither was. Also applies a pending [`focus`]. Call before the dialog is laid out. pub fn take_step(ctx: &Context) -> i32 { - if let Some(id) = ctx.data_mut(|d| d.remove_temp::>(pending_id())).flatten() { + let pending = ctx.data_mut(|d| d.remove_temp::>(pending_id())).flatten(); + if let Some(id) = pending { ctx.memory_mut(|m| m.request_focus(id)); } + // Tagged with this pass: `take_step` is skipped while a popup is open, and a marker left + // over from an earlier pass would make a later click into the field select all its text. + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(reached_id(), pending.map(|id| (id, pass)))); let step = ctx.input_mut(|i| { if i.consume_key(Modifiers::SHIFT, Key::Tab) { -1 @@ -52,6 +61,12 @@ pub fn take_step(ctx: &Context) -> i32 { step } +/// True in the frame a field gets the focus [`take_step`] handed it (Tab, ⇧Tab or [`focus`]), +/// whatever the mouse is doing meanwhile. +pub fn reached(ctx: &Context, id: Id) -> bool { + ctx.data(|d| d.get_temp::>(reached_id())).flatten() == Some((id, ctx.cumulative_pass_nr())) +} + /// Start collecting the fields of a dialog body. pub fn begin(ctx: &Context) { ctx.data_mut(|d| { @@ -215,6 +230,27 @@ mod tests { assert_eq!((d.name.as_str(), d.size.width, d.size.height), ("Flyer", 512, 310)); } + /// The field a Tab reached is "reached" only in the pass that handed it focus: while a popup + /// is open `take_step` is skipped, and a later click into the field must place the caret. + #[test] + fn reached_lasts_only_the_pass_that_applied_the_focus() { + let ctx = egui::Context::default(); + let id = egui::Id::unique("field"); + let mut seen = Vec::new(); + for apply in [true, false, false] { + ctx.run_ui(Default::default(), |ui| { + if apply { + super::focus(ui.ctx(), id); + super::take_step(ui.ctx()); + } + seen.push(super::reached(ui.ctx(), id)); + }) + .textures_delta + .clear(); + } + assert_eq!(seen, [true, false, false]); + } + /// Tab is the dialog's: the modal underneath never sees it, and a dialog with no fields swallows it. #[test] fn tab_in_a_dialog_without_fields_does_nothing() {