Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Expand arithmetic expressions across numeric inputs (#2252)

Sean Lavery478acf70cc45
diff --git a/crates/ui-egui/src/chrome_ui.rs b/crates/ui-egui/src/chrome_ui.rs
index e1d58801b..b69d71b98 100644
--- a/crates/ui-egui/src/chrome_ui.rs
+++ b/crates/ui-egui/src/chrome_ui.rs
@@ -216,7 +216,7 @@ pub fn crop_ratio(key: &str, doc_w: f64, doc_h: f64) -> Option<(f64, f64)> {
return Some((doc_w, doc_h));
}
let (a, b) = key.split_once(':')?;
- Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
+ Some((crate::numeric_expression::parse(a)?, crate::numeric_expression::parse(b)?))
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs
index d7166712f..2aff1608f 100644
--- a/crates/ui-egui/src/layer_style.rs
+++ b/crates/ui-egui/src/layer_style.rs
@@ -1316,7 +1316,7 @@ fn angle_row(ui: &mut egui::Ui, label: &str, angle: &mut f32) -> egui::Response
dial.mark_changed();
}
}
- let field = ui.add(egui::DragValue::new(angle).range(-180.0..=180.0).speed(1.0).suffix("°"));
+ let field = ui.add(egui::DragValue::new(angle).custom_parser(crate::widgets::parse_num).range(-180.0..=180.0).speed(1.0).suffix("°"));
if field.changed() {
dial.mark_changed();
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1bb38baeb..0f1f1b566 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -104,6 +104,7 @@ pub mod move_ui;
pub mod native_menu;
pub mod new_doc_ui;
pub mod notices;
+mod numeric_expression;
mod opacity_keys;
pub mod outline;
pub mod paint_mouse;
diff --git a/crates/ui-egui/src/new_doc_ui.rs b/crates/ui-egui/src/new_doc_ui.rs
index bb2597823..fb9631324 100644
--- a/crates/ui-egui/src/new_doc_ui.rs
+++ b/crates/ui-egui/src/new_doc_ui.rs
@@ -832,6 +832,15 @@ mod tests {
(d.size.width, d.size.height, d.resolution_dpi)
}
+ #[test]
+ fn arithmetic_dimensions_create_the_evaluated_size() {
+ let mut h = harness();
+ type_into(&mut h, 0, "1920/2");
+ type_into(&mut h, 1, "(100+50)*2");
+ enter(&mut h);
+ assert_eq!(created(&h), (960, 300, 72.0));
+ }
+
#[test]
fn typed_size_then_enter_creates_that_size() {
let mut h = harness();
diff --git a/crates/ui-egui/src/numeric_expression.rs b/crates/ui-egui/src/numeric_expression.rs
new file mode 100644
index 000000000..e6ffab28f
--- /dev/null
+++ b/crates/ui-egui/src/numeric_expression.rs
@@ -0,0 +1,170 @@
+//! Bounded arithmetic parser shared by every editable numeric widget.
+//! No scripting, allocations derived from results, or non-finite values.
+
+pub(crate) fn parse(text: &str) -> Option<f64> {
+ if text.len() > 1024 {
+ return None;
+ }
+ let normalized = text.replace('−', "-");
+ let mut parser = Parser { rest: &normalized };
+ let value = parser.expression(0, 0)?;
+ parser.space();
+ (parser.rest.is_empty() && value.is_finite()).then_some(value)
+}
+
+struct Parser<'a> {
+ rest: &'a str,
+}
+impl Parser<'_> {
+ fn space(&mut self) {
+ self.rest = self.rest.trim_start();
+ }
+ fn take(&mut self, token: &str) -> bool {
+ self.space();
+ if let Some(rest) = self.rest.strip_prefix(token) {
+ self.rest = rest;
+ true
+ } else {
+ false
+ }
+ }
+ fn expression(&mut self, minimum: u8, depth: u8) -> Option<f64> {
+ if depth >= 32 {
+ return None;
+ }
+ self.space();
+ let mut left = if self.take("+") {
+ self.expression(3, depth + 1)?
+ } else if self.take("-") {
+ -self.expression(3, depth + 1)?
+ } else if self.take("(") {
+ let value = self.expression(0, depth + 1)?;
+ if !self.take(")") {
+ return None;
+ }
+ value
+ } else if self.take("pi") {
+ std::f64::consts::PI
+ } else if self.take("tau") {
+ std::f64::consts::TAU
+ } else {
+ self.number()?
+ };
+ loop {
+ self.space();
+ let (token, precedence, right_minimum) = if self.rest.starts_with("**") {
+ ("**", 3, 3)
+ } else {
+ match self.rest.chars().next() {
+ Some('+') => ("+", 1, 2),
+ Some('-') => ("-", 1, 2),
+ Some('*') => ("*", 2, 3),
+ Some('/') => ("/", 2, 3),
+ Some('%') => ("%", 2, 3),
+ Some('^') => ("^", 3, 3),
+ _ => break,
+ }
+ };
+ if precedence < minimum {
+ break;
+ }
+ if !self.take(token) {
+ return None;
+ }
+ let right = self.expression(right_minimum, depth + 1)?;
+ left = match token {
+ "+" => left + right,
+ "-" => left - right,
+ "*" => left * right,
+ "/" if right != 0.0 => left / right,
+ "%" if right != 0.0 => left % right,
+ "^" | "**" => left.powf(right),
+ _ => return None,
+ };
+ if !left.is_finite() {
+ return None;
+ }
+ }
+ left.is_finite().then_some(left)
+ }
+ fn number(&mut self) -> Option<f64> {
+ let mut length = 0;
+ let mut exponent = false;
+ for (offset, ch) in self.rest.char_indices() {
+ let accepted = ch.is_ascii_digit()
+ || ch == '.'
+ || (!exponent && matches!(ch, 'e' | 'E'))
+ || (matches!(ch, '+' | '-') && self.rest.get(..offset).is_some_and(|s| s.ends_with(['e', 'E'])));
+ if !accepted {
+ break;
+ }
+ exponent |= matches!(ch, 'e' | 'E');
+ length = offset + ch.len_utf8();
+ }
+ let value = self.rest.get(..length)?.parse::<f64>().ok()?;
+ self.rest = self.rest.get(length..)?;
+ value.is_finite().then_some(value)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::parse;
+ #[test]
+ fn arithmetic() {
+ for (text, expected) in [
+ ("1920/2", 960.0),
+ ("30+15", 45.0),
+ ("2+3*4", 14.0),
+ ("(2+3)*4", 20.0),
+ ("-2^2", -4.0),
+ ("2**3**2", 512.0),
+ ("2^-2", 0.25),
+ ("10%3", 1.0),
+ ("1e-3 * 1000", 1.0),
+ ("−12 + .5", -11.5),
+ ("pi*2", std::f64::consts::TAU),
+ ("tau/2", std::f64::consts::PI),
+ ] {
+ assert_eq!(parse(text), Some(expected), "{text}");
+ }
+ }
+ #[test]
+ fn rejects_invalid_and_hostile_input() {
+ for text in ["", "1/0", "0/0", "1%0", "NaN", "inf", "1e999", "2+", "(2*3", "2 3", "pi junk", "sqrt(4)", "2^(1e300)", "你好"] {
+ assert_eq!(parse(text), None, "{text}");
+ }
+ assert_eq!(parse(&"(".repeat(1000)), None);
+ assert_eq!(parse(&"1".repeat(1025)), None);
+ }
+}
+
+#[cfg(test)]
+mod widget_tests {
+ use egui_kittest::{Harness, kittest::Queryable};
+ #[test]
+ fn typed_expression_commits_clamps_and_rejects_invalid() {
+ let mut h = Harness::builder().build_ui_state(
+ |ui, value| {
+ ui.add(egui::DragValue::new(value).range(0.0..=1000.0).custom_parser(super::parse));
+ },
+ 100.0_f64,
+ );
+ for (text, expected) in [("1920/2", 960.0), ("2000*2", 1000.0), ("1/0", 1000.0)] {
+ let center = h.get_by_role(egui::accesskit::Role::SpinButton).rect().center();
+ h.hover_at(center);
+ h.run_steps(1);
+ h.drag_at(center);
+ h.run_steps(1);
+ h.drop_at(center);
+ h.run();
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.run();
+ h.event(egui::Event::Text(text.to_owned()));
+ h.run();
+ h.key_press(egui::Key::Enter);
+ h.run();
+ assert_eq!(*h.state(), expected);
+ }
+ }
+}
diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs
index daf7a4902..27584a189 100644
--- a/crates/ui-egui/src/type_tool.rs
+++ b/crates/ui-egui/src/type_tool.rs
@@ -1121,7 +1121,7 @@ pub(crate) fn parse_kerning(s: &str) -> Option<serde_json::Value> {
match s.to_ascii_lowercase().as_str() {
"metrics" => Some(json!("metrics")),
"optical" => Some(json!("optical")),
- _ => s.parse::<f64>().ok().filter(|v| v.is_finite() && (-1000.0..=10000.0).contains(v)).map(|v| json!(v.round())),
+ _ => crate::numeric_expression::parse(s).filter(|v| v.is_finite() && (-1000.0..=10000.0).contains(v)).map(|v| json!(v.round())),
}
}
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 82ce33a82..5ab403447 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -1111,12 +1111,13 @@ pub fn fmt_num2(v: f64) -> String {
format!("{r:.2}").trim_end_matches('0').trim_end_matches('.').to_string()
}
-/// Parses a typed number or simple arithmetic such as `1280*2` or `20*2+5-2` (`+ - * /`,
-/// `*` and `/` first). Like egui's own parser it ignores whitespace and reads `−` as `-`.
-/// `None` for anything else, including a division by zero.
+/// Parses a typed number or bounded arithmetic, including parentheses and powers.
+/// Preserves egui-compatible whitespace and Unicode minus handling.
pub fn parse_num(text: &str) -> Option<f64> {
- let s = clean(text);
- s.parse().ok().or_else(|| sum(&s)).filter(|v: &f64| v.is_finite())
+ if text.len() > 1024 {
+ return None;
+ }
+ crate::numeric_expression::parse(&clean(text))
}
/// A plain typed number, no arithmetic.
@@ -1128,30 +1129,6 @@ fn clean(text: &str) -> String {
text.chars().filter(|c| !c.is_whitespace()).map(|c| if c == '−' { '-' } else { c }).collect()
}
-/// `a+b-c…`: a `+` or `-` right after an operand splits terms; anywhere else it is a sign.
-fn sum(s: &str) -> Option<f64> {
- let (mut total, mut sign, mut start, mut prev) = (0.0, 1.0, 0, ' ');
- for (i, c) in s.char_indices() {
- if matches!(c, '+' | '-') && i > start && !matches!(prev, '*' | '/' | 'e' | 'E') {
- total += sign * product(s.get(start..i)?)?;
- sign = if c == '-' { -1.0 } else { 1.0 };
- start = i + 1;
- }
- prev = c;
- }
- Some(total + sign * product(s.get(start..)?)?)
-}
-
-/// `a*b/c…`, left to right.
-fn product(s: &str) -> Option<f64> {
- let mut factors = s.split(['*', '/']).map(str::parse::<f64>);
- let mut acc = factors.next()?.ok()?;
- for (op, x) in s.matches(['*', '/']).zip(factors) {
- acc = if op == "*" { acc * x.ok()? } else { acc / x.ok()? };
- }
- Some(acc)
-}
-
#[cfg(test)]
mod tests {
use egui::{Key, Modifiers};
@@ -1308,10 +1285,13 @@ mod tests {
("−4", -4.0),
("1 234", 1234.0),
("1e3/2", 500.0),
+ ("(2+3)*4", 20.0),
+ ("2^3", 8.0),
+ ("10%3", 1.0),
] {
assert_eq!(parse_num(text), Some(want), "{text}");
}
- for text in ["", "abc", "5+", "*2", "4/0", "0/0", "1+*2", "(2+3)", "1e400"] {
+ for text in ["", "abc", "5+", "*2", "4/0", "0/0", "1+*2", "(2+3", "1e400"] {
assert_eq!(parse_num(text), None, "{text}");
}
}
diff --git a/crates/ui-egui/src/widgets/color_count.rs b/crates/ui-egui/src/widgets/color_count.rs
index f75f89a44..87d109b4d 100644
--- a/crates/ui-egui/src/widgets/color_count.rs
+++ b/crates/ui-egui/src/widgets/color_count.rs
@@ -5,7 +5,7 @@ use super::*;
const STOPS: [u32; 6] = [8, 16, 32, 64, 128, 256];
fn parse_count(text: &str) -> Option<f64> {
- text.trim().parse::<u32>().ok().map(f64::from)
+ super::parse_num(text).filter(|v| *v >= 0.0 && *v <= f64::from(u32::MAX) && v.fract() == 0.0)
}
fn position(track: Rect, count: u32) -> f32 {
@@ -106,7 +106,7 @@ mod tests {
#[test]
fn typed_color_counts_reject_fractions_and_allow_arbitrary_integers() {
- for (text, expected) in [("17", 17), ("256", 256), ("17.5", 64), ("17,5", 64), ("1e2", 64)] {
+ for (text, expected) in [("17", 17), ("256", 256), ("17.5", 64), ("17,5", 64), ("1e2", 100), ("(8+8)*2", 32), ("2^8", 256), ("5/2", 64)] {
let mut harness = Harness::builder().with_size(vec2(320.0, 100.0)).build_ui_state(
|ui, count: &mut u32| {
color_count_row(ui, "Colors", count);
@@ -150,3 +150,15 @@ mod tests {
assert!(((position(track, 128) - position(track, 64)) - (position(track, 96) - position(track, 32))).abs() < 0.001);
}
}
+
+#[cfg(test)]
+mod arithmetic_tests {
+ #[test]
+ fn count_expression_preserves_integer_validation() {
+ assert_eq!(super::parse_count("2^8"), Some(256.0));
+ assert_eq!(super::parse_count("(8+8)*2"), Some(32.0));
+ assert_eq!(super::parse_count("5/2"), None);
+ assert_eq!(super::parse_count("1/0"), None);
+ assert_eq!(super::parse_count("-2"), None);
+ }
+}
diff --git a/docs/ui-design.md b/docs/ui-design.md
index 10608369f..e405fcb78 100644
--- a/docs/ui-design.md
+++ b/docs/ui-design.md
@@ -187,3 +187,13 @@ panel width. Catalog coverage and actual shell language-switch tests enforce the
Native CJK font fallback follows the selected UI script and resets its cache when switching
languages; font delivery on the web remains separate work.
+
+## Arithmetic in numeric fields
+
+Click a numeric value and type an expression, then press Enter or move focus to finish.
+Numeric fields accept `+`, `-`, `*`, `/`, remainder `%`, powers `^` or `**`, parentheses,
+scientific notation, and `pi` / `tau`. For example, `1920/2` gives `960`, and `(30+15)*2`
+gives `90`. Shared value fields apply plain numbers live and arithmetic when editing
+finishes, preserving rounded/integer workflows. Field limits and integer rounding
+still apply; invalid expressions, division by zero, and non-finite results are rejected.
+Expressions are evaluated locally as arithmetic, never as scripts.