diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 12cebda239..4953bffcf1 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -172,6 +172,8 @@ pub struct NumberCodec { /// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]). share: bool, signed_zoom: bool, + /// A positive value is written with its `+` ([`NumberCodec::explicit_plus`]). + plus: bool, } impl fmt::Debug for NumberCodec { @@ -183,6 +185,7 @@ impl fmt::Debug for NumberCodec { .field("zoom", &self.zoom) .field("share", &self.share) .field("signed_zoom", &self.signed_zoom) + .field("plus", &self.plus) .field("custom", &self.custom.is_some()) .field("primary", &self.primary.is_some()) .finish() @@ -207,6 +210,7 @@ impl PartialEq for NumberCodec { && self.zoom == other.zoom && self.share == other.share && self.signed_zoom == other.signed_zoom + && self.plus == other.plus && same_custom && same_primary } @@ -242,7 +246,17 @@ const NUMBER_SAMPLE: &str = "0000.00"; impl NumberCodec { /// A codec reading with `reader` and writing at most `decimals` decimal places. pub fn new(reader: Reader, decimals: usize) -> Self { - NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false } + NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false, plus: false } + } + + /// The same codec writing a positive value with its sign ("+2.50"), as an angle or an offset from a neutral value + /// reads; a value that rounds to zero at the codec's decimals stays unsigned ("0.00"). A leading `+` in typed text + /// is then the number's sign, as the field writes it, not the relative `+` of a plain field (which adds to the + /// value the edit started from). An authoritative [`parse_with`](Self::parse_with) reader still receives the whole + /// input, including the sign. + pub fn explicit_plus(mut self) -> Self { + self.plus = true; + self } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -322,6 +336,25 @@ impl NumberCodec { self } + fn parse_builtin(&self, trimmed: &str, start: Option) -> Result<(Option, ParseNote), NotAValue> { + if self.zoom { + return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); + } + // Without an edit-start operand the reader already treats a leading `+` as a unary sign. Take that + // path directly rather than retrying each shorter suffix, and leave signed shares as absolute amounts. + let absolute_plus = self.plus && trimmed.starts_with('+'); + if self.share + && !absolute_plus + && let Some(share_of_start) = self.reader.share(trimmed) + { + return start.map(|start| (Some(start * share_of_start), ParseNote::default())).ok_or(NotAValue); + } + match self.reader.read_tagged(trimmed, if absolute_plus { None } else { start }) { + Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), + Err(rejected) => self.custom.as_ref().and_then(|parse| parse(trimmed)).map(|number| (Some(number), ParseNote::default())).ok_or(rejected), + } + } + /// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of /// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized /// for any value it shows in it. @@ -346,6 +379,12 @@ impl NumberCodec { pub fn reader(&self) -> &Reader { &self.reader } + + /// Whether the codec writes a positive value with its `+` ([`NumberCodec::explicit_plus`]): its own text then + /// starts with a sign that is the number's, not a relative edit. + pub fn writes_sign(&self) -> bool { + self.plus + } } impl Default for NumberCodec { @@ -372,7 +411,9 @@ impl Codec for NumberCodec { } else { fixed }; - trimmed.replace('.', &self.reader.decimal_separator().to_string()) + let shown = trimmed.replace('.', &self.reader.decimal_separator().to_string()); + let zero = trimmed.bytes().all(|byte| matches!(byte, b'0' | b'.')); + if self.plus && !trimmed.starts_with('-') && !zero { format!("+{shown}") } else { shown } } fn parse(&self, text: &str, start: &Option) -> Result, NotAValue> { @@ -389,20 +430,7 @@ impl Codec for NumberCodec { if let Some(parse) = &self.primary { return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue); } - if self.zoom { - return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); - } - if self.share - && let Some(share) = self.reader.share(trimmed) - { - return start.map(|start| (Some(start * share), ParseNote::default())).ok_or(NotAValue); - } - match self.reader.read_tagged(text, *start) { - Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), - Err(rejected) => { - self.custom.as_ref().and_then(|parse| parse(text.trim())).map(|number| (Some(number), ParseNote::default())).ok_or(rejected) - } - } + self.parse_builtin(trimmed, *start) } /// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character. @@ -427,4 +455,83 @@ mod tests { assert_eq!(one.format(&Some(-0.06)), "-0.1"); assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0"); } + + #[test] + fn an_explicit_plus_codec_writes_the_sign_of_a_positive_value() { + let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus(); + assert_eq!(angle.format(&Some(2.5)), "+2.50"); + assert_eq!(angle.format(&Some(-3.25)), "-3.25"); + assert_eq!(angle.format(&Some(0.0)), "0.00", "zero is unsigned"); + assert_eq!(angle.format(&Some(0.004)), "0.00", "a value that rounds to zero is unsigned"); + assert_eq!(angle.format(&Some(-0.004)), "0.00"); + assert_eq!(angle.format(&None), ""); + assert_eq!(NumberCodec::new(Reader::new(), 2).explicit_plus().format(&Some(1.5)), "+1.5", "trimmed decimals keep the sign"); + assert_eq!(NumberCodec::new(Reader::new(), 2).fixed().format(&Some(2.5)), "2.50", "without it a positive value has no sign"); + } + + #[test] + fn an_explicit_plus_codec_reads_a_leading_plus_as_the_sign() { + let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus(); + assert_eq!(angle.parse("+2.50", &Some(10.0)).ok(), Some(Some(2.5)), "the written text reads back as itself, not added to the start"); + assert_eq!(angle.parse(&angle.format(&Some(7.25)), &Some(-1.0)).ok(), Some(Some(7.25))); + assert_eq!(angle.parse("-3.25", &Some(10.0)).ok(), Some(Some(-3.25))); + assert_eq!(angle.parse("4", &None).ok(), Some(Some(4.0))); + assert!(angle.parse("+", &Some(1.0)).is_err(), "a lone plus is no number"); + let plain = NumberCodec::new(Reader::new(), 2); + assert_eq!(plain.parse("+2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's leading plus still adds to the start"); + } +} + +#[cfg(test)] +mod review_tests { + use super::*; + + /// The `+` a field writes may be typed back with a space after it: "+ 2.50" is the number 2.5, not the relative + /// "+ 2.50" added to the start value. + #[test] + fn an_explicit_plus_codec_reads_the_space_after_the_sign() { + let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus(); + assert_eq!(angle.parse("+ 2.50", &Some(10.0)).ok(), Some(Some(2.5)), "a space after the sign keeps it the number's own"); + assert_eq!(angle.parse("+\t7", &Some(10.0)).ok(), Some(Some(7.0))); + assert!(angle.parse("+", &Some(10.0)).is_err(), "a lone plus stays no number"); + let plain = NumberCodec::new(Reader::new(), 2); + assert_eq!(plain.parse("+ 2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's plus still adds to the start"); + // The digit after the sign may be written in any script the reader reads: Arabic-Indic ٣ is 3. + assert_eq!(angle.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "a sign before an Arabic-Indic digit is still the number's"); + // The signed text is absolute for every lead the reader accepts, an expression too: "+(2+3)" is 5, not 15. + assert_eq!(angle.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(5.0)), "a signed expression is the number, not added to the start"); + assert_eq!(angle.parse("+2+3", &Some(10.0)).ok(), Some(Some(5.0)), "and a signed sum reads the same as without the sign"); + assert_eq!(angle.parse("-(2+3)", &Some(10.0)).ok(), Some(Some(-5.0)), "a minus stays absolute, as it was"); + assert_eq!(plain.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(15.0)), "a plain field still adds a leading plus to the start"); + // A word the field's own parser stands for is given the text as it was typed, `+` and all. + let named = NumberCodec::new(Reader::new(), 2).explicit_plus().or_parse(|text| (text == "+Auto").then_some(42.0)); + assert_eq!(named.parse("+Auto", &Some(10.0)).ok(), Some(Some(42.0)), "a custom parser still sees the signed text"); + assert_eq!(named.parse("+2", &Some(10.0)).ok(), Some(Some(2.0)), "while a number after the sign stays absolute"); + assert_eq!(angle.parse("\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "and the reader reads that digit as before"); + assert_eq!(plain.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(13.0)), "a plain field still adds it to the start"); + } + + /// A share field's signed percentage is that number, not a share of the start value again. + #[test] + fn an_explicit_plus_share_codec_reads_a_signed_percentage_as_the_number() { + let share = NumberCodec::new(Reader::new().unit("%", 1.0), 0).share_of_start().explicit_plus(); + assert_eq!(share.parse("+50%", &Some(10.0)).ok(), Some(Some(50.0)), "a signed percentage is absolute"); + assert_eq!(share.parse("50%", &Some(10.0)).ok(), Some(Some(5.0)), "an unsigned one is the share of the start"); + assert_eq!(share.parse("+50", &Some(10.0)).ok(), Some(Some(50.0)), "and a signed number is absolute too"); + } + #[test] + fn explicit_plus_still_gives_the_authoritative_reader_the_whole_signed_input() { + let codec = NumberCodec::default().parse_with(|text| (text == "+12").then_some(17.0)).explicit_plus(); + assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(17.0))); + assert_eq!(codec.parse("+(2+3)", &Some(50.0)), Err(NotAValue), "rejects instead of falling back to the expression reader"); + assert_eq!(codec.format(&Some(17.0)), "+17"); + } + + #[test] + fn an_explicit_plus_codec_reads_a_long_run_of_unary_signs_without_recursing() { + let codec = NumberCodec::default().explicit_plus(); + let long = "+ ".repeat(32_768); + assert_eq!(codec.parse(&format!("{long}--(2+3)"), &Some(10.0)), Ok(Some(5.0))); + assert_eq!(codec.parse(&long, &Some(10.0)), Err(NotAValue)); + } } diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index af3c06e5d1..5fc76f2b05 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -7,7 +7,7 @@ use crate::codec::NotAValue; const DIGIT_BLOCKS: [u32; 5] = [0x30, 0x660, 0x6F0, 0x966, 0xFF10]; /// The value of a decimal digit of any supported script. -fn digit(c: char) -> Option { +pub(crate) fn digit(c: char) -> Option { DIGIT_BLOCKS.iter().find_map(|&zero| (zero..zero + 10).contains(&(c as u32)).then(|| c as u32 - zero)) } @@ -198,15 +198,12 @@ impl Parse<'_> { /// A factor; `scaled` says it starts a term, where a number with no unit counts as the reader's bare factor. /// Otherwise it is a multiplier, which may be a percentage. fn factor(&mut self, scaled: bool) -> Result { - match self.peek() { - Some('-') => { - self.at += 1; - self.factor(scaled).map(|value| -value) - } - Some('+') => { - self.at += 1; - self.factor(scaled) - } + let mut negative = false; + while let Some(sign @ ('+' | '-')) = self.peek() { + negative ^= sign == '-'; + self.at += 1; + } + let value = match self.peek() { Some('(') => { self.at += 1; let value = self.expr()?; @@ -214,7 +211,8 @@ impl Parse<'_> { Ok(value) } _ => self.quantity(scaled), - } + }?; + Ok(if negative { -value } else { value }) } /// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a diff --git a/crates/ui-widgets/src/form/slider_field.rs b/crates/ui-widgets/src/form/slider_field.rs index 27e0deee64..0e0fbf752d 100644 --- a/crates/ui-widgets/src/form/slider_field.rs +++ b/crates/ui-widgets/src/form/slider_field.rs @@ -164,6 +164,10 @@ pub struct SliderField<'a> { /// ([`NumberField::select_on_focus`]): a click on the value selects it, a drag across it keeps the range. #[prop(flag)] select_on_focus: bool, + /// The number field writes a positive value with its sign ([`NumberField::explicit_plus`]), and a value that + /// rounds to zero unsigned: the slider and its field show that value the same way. + #[prop(flag)] + explicit_plus: bool, /// The number field's width from this pass's measure (its `Proposal::Ideal` call, which runs before `paint`). field_width: f32, /// The field's range alert of this pass, which `finish` reports. @@ -230,6 +234,7 @@ impl<'a> SliderField<'a> { marks: None, short: false, select_on_focus: false, + explicit_plus: false, field_width: 0.0, out_of_range: None, } @@ -275,6 +280,7 @@ impl<'a> SliderField<'a> { marks: self.marks.clone(), short: self.short, select_on_focus: self.select_on_focus, + explicit_plus: self.explicit_plus, } } } @@ -313,6 +319,7 @@ struct Look { marks: Option, short: bool, select_on_focus: bool, + explicit_plus: bool, } /// The composite's check, which its children check their values with. @@ -452,6 +459,7 @@ impl Look { None => field, }; let field = if self.select_on_focus { field.select_on_focus() } else { field }; + let field = if self.explicit_plus { field.explicit_plus() } else { field }; let field = match self.field_sizing { Some(sizing) => field.sizing(sizing), None => field, diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 9320e25b0c..f0c4a7b811 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -222,6 +222,10 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// The field writes exactly this many decimals, zeros included ("1.00"), when it has no codec of its own. #[prop] fixed_decimals: Option, + /// A positive value is written with its `+` and a value that rounds to zero unsigned (`NumberCodec::explicit_plus`), + /// whichever codec the field reads with: a rotation angle or an offset from a neutral value. + #[prop(flag)] + explicit_plus: bool, /// The number the held name stands for: while the value is a name, the field shows this number in parentheses in /// place of the name's label; the presets row keeps the label. #[prop(quantity = "field value")] @@ -316,6 +320,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { derived: false, commit_decimals: None, fixed_decimals: None, + explicit_plus: false, name_number: None, max_decimals: None, lengths: None, @@ -524,6 +529,12 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { /// The field's codec: the one set, else the env's locale and the spellings of the unit kind (a length field /// reads every length spelling). fn number_codec(&self, units: &Units) -> NumberCodec { + let codec = self.own_codec(units); + if self.explicit_plus { codec.explicit_plus() } else { codec } + } + + /// [`number_codec`](Self::number_codec) before the field's sign rule. + fn own_codec(&self, units: &Units) -> NumberCodec { self.codec.clone().unwrap_or_else(|| { let reader = match self.lengths { Some(lengths) => units.length_reader(lengths), diff --git a/crates/ui-widgets/src/text/number/rule.rs b/crates/ui-widgets/src/text/number/rule.rs index 349df97df7..9088d11c64 100644 --- a/crates/ui-widgets/src/text/number/rule.rs +++ b/crates/ui-widgets/src/text/number/rule.rs @@ -230,7 +230,14 @@ impl Codec for Ruled { } fn applies_as_typed(&self, text: &str) -> bool { - !self.snap && !self.mixed && is_plain(self.unwritten(text)) && matches!(self.inner.parse(self.unwritten(text), &None), Ok(Some(_))) + let text = self.unwritten(text); + // The `+` an explicit-plus field writes is the number's own sign, so its own text is plain input there, as a + // negative number's `-` is; on a plain field a leading `+` stays the relative input `is_plain` refuses. + let plain = match text.trim_start().strip_prefix('+') { + Some(rest) if self.inner.writes_sign() => rest, + _ => text, + }; + !self.snap && !self.mixed && is_plain(plain) && matches!(self.inner.parse(text, &None), Ok(Some(_))) } fn filter(&self, c: char) -> bool { diff --git a/crates/ui-widgets/tests/it/text/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index 371139f9f5..a441dbb28e 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -13,6 +13,7 @@ pub(crate) mod number; pub(crate) mod number_derived; pub(crate) mod number_length; pub(crate) mod number_look; +pub(crate) mod number_plus; pub(crate) mod number_scrub_step; pub(crate) mod number_select; pub(crate) mod number_width; diff --git a/crates/ui-widgets/tests/it/text/number_plus.rs b/crates/ui-widgets/tests/it/text/number_plus.rs new file mode 100644 index 0000000000..41e15a0176 --- /dev/null +++ b/crates/ui-widgets/tests/it/text/number_plus.rs @@ -0,0 +1,90 @@ +//! `NumberField::explicit_plus`: a positive value shows its sign, zero shows none, and the shown text reads back as +//! itself. + +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::form::SliderField; +use craft_ui::runtime::env::{LengthUnits, UnitKind}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; +use egui::{Key, Modifiers}; +use std::cell::Cell; +use std::rc::Rc; + +fn angle(start: f64) -> (Fixture, Rc>>) { + let value = Rc::new(Cell::new(Some(start))); + let held = Rc::clone(&value); + let mut fixture = Fixture::new(move |ui| { + let mut now = held.get(); + NumberField::new("Angle", Bind::bound(&mut now)).range(-45.0..=45.0).step(0.01).fixed_decimals(2).explicit_plus().show(ui); + held.set(now); + }); + fixture.settle(); + (fixture, value) +} + +#[trial] +fn an_explicit_plus_field_writes_a_positive_angle_with_its_sign() { + for (value, shown) in [(2.5, "+2.50"), (-3.25, "-3.25"), (0.0, "0.00")] { + let (fixture, _) = angle(value); + assert!(fixture.texts().iter().any(|painted| painted.text == shown), "{value} shows as {shown}: {:?}", fixture.texts()); + } +} + +#[trial] +fn committing_an_explicit_plus_fields_text_unchanged_keeps_its_value() { + let (mut fixture, value) = angle(2.5); + let field = fixture.by_label("Angle").expect("the field"); + fixture.click(&field).settle(); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!(value.get(), Some(2.5), "\"+2.50\" reads back as 2.5, not 2.5 added to the start"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("+1.25"); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!(value.get(), Some(1.25), "a typed leading plus is the sign"); +} + +/// The field's own text, "+7", is a plain number: it applies as it is typed, not on commit, as "-7" does. +#[trial] +fn an_explicit_plus_fields_own_text_applies_as_it_is_typed() { + let (mut fixture, value) = angle(2.5); + let field = fixture.by_label("Angle").expect("the field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("+7").settle(); + assert_eq!(value.get(), Some(7.0), "the typed value applies before Enter"); +} + +/// A slider field forwards the sign rule to its number field, so the two children show the value alike. +#[trial] +fn a_slider_field_writes_its_value_with_the_sign_it_is_given() { + let value = Rc::new(Cell::new(2.5f64)); + let held = Rc::clone(&value); + let mut fixture = Fixture::new(move |ui| { + let mut now = held.get(); + SliderField::new("Angle", Bind::bound(&mut now), -45.0..=45.0).step(0.01).typed_decimals(2).explicit_plus().show(ui); + held.set(now); + }); + fixture.settle(); + assert!(fixture.texts().iter().any(|painted| painted.text == "+2.5"), "the number shows its sign: {:?}", fixture.texts()); +} + +#[trial] +fn a_length_slider_field_uses_its_sign_without_adding_the_starting_length() { + let value = Rc::new(Cell::new(144.0)); + let held = Rc::clone(&value); + let mut fixture = Fixture::new(move |ui| { + let mut now = held.get(); + SliderField::new("Depth", Bind::bound(&mut now), 0.0..=720.0) + .lengths(LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0)) + .step(18.0) + .explicit_plus() + .show(ui); + held.set(now); + }); + fixture.settle(); + assert!(fixture.texts().iter().any(|text| text.text == "+2"), "the positive length shows its sign in inches"); + let field = fixture.by_label("Depth").expect("the length field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("+1.25"); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!(value.get(), 90.0, "the typed length is 1.25 inches, not 2 + 1.25 inches"); +}