Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions crates/core/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ pub struct Parsed {
/// Interprets typed cell input (not formulas). Text that isn't a number, date, boolean or error
/// stays text. A leading apostrophe forces text.
pub fn parse_input(s: &str, sys: DateSystem) -> Parsed {
parse_value(s, sys, true)
}

/// Like [`parse_input`] for values read from a file such as CSV, which stays en-US: the euro
/// and hryvnia forms only typed entry reads (`€5`, `12,50 €`, `250 грн`) remain text.
pub fn parse_file_input(s: &str, sys: DateSystem) -> Parsed {
parse_value(s, sys, false)
}

fn parse_value(s: &str, sys: DateSystem, entry: bool) -> Parsed {
if s.is_empty() {
return Parsed { value: Value::Empty, format: None };
}
Expand All @@ -34,7 +44,7 @@ pub fn parse_input(s: &str, sys: DateSystem) -> Parsed {
if let Some(e) = CellError::parse(t) {
return Parsed { value: Value::Error(e), format: None };
}
if let Some((n, f)) = parse_numeric(t, sys, true) {
if let Some((n, f)) = parse_numeric(t, sys, entry) {
return Parsed { value: Value::number(n), format: f };
}
Parsed { value: Value::text(s), format: None }
Expand Down Expand Up @@ -487,7 +497,9 @@ fn delocalize_number(t: &str, region: Region) -> Option<String> {
let after = format!("{}{after}", body.get(trimmed.len()..).unwrap_or(""));
let body = trimmed;
let before = t.get(..start)?;
if body.is_empty() {
// A separator the region does not use right after the digits (`1 234.5` in Ukraine) makes
// the entry no number here, rather than a decimal read the en-US way.
if body.is_empty() || after.starts_with(['.', ',']) {
return None;
}
let (int, frac) = match body.split_once(d) {
Expand Down
4 changes: 4 additions & 0 deletions crates/core/tests/regional_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ fn ukrainian_numbers_group_with_spaces_and_take_the_hryvnia() {
assert_eq!(read("99,90 ₴", uk), (Value::Number(99.9), Some("#,##0.00 \"₴\"")));
assert_eq!(read("1 500 грн", uk), (Value::Number(1500.0), Some("#,##0 \"грн\"")));
assert_eq!(number("0,5", uk), Some(0.5));
// A dot decimal after grouped digits mixes two conventions: text, not 1234.5.
for text in ["1 234.5", "1\u{a0}234.50", "-1 234.5 ₴"] {
assert!(matches!(read(text, uk).0, Value::Text(_)), "{text}");
}
}

#[test]
Expand Down
31 changes: 26 additions & 5 deletions crates/formula/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,23 @@ fn translate_function(name: &str, display: bool, bound: &impl Fn(&str) -> bool)
Ok(name.to_string())
}

/// A function given by name as an argument, as in `MAP({1;4};RAIZ)`, is translated like a call.
/// Booleans, bound names and names that are no function's are left alone.
/// Whether argument `index` of `count` passed to the built-in `function` (English name) is a
/// function, which may be given by name: the LAMBDA of the helpers and the aggregation of
/// GROUPBY and PIVOTBY, as the evaluator reads them. Every other argument is a value, so a
/// name there stays a name (`SUMA(RAIZ;1)` keeps the name `RAIZ`).
fn takes_function(function: &str, index: usize, count: usize) -> bool {
let position = match function.to_ascii_uppercase().as_str() {
"MAP" => count.checked_sub(1),
"BYROW" | "BYCOL" => Some(1),
"REDUCE" | "SCAN" | "MAKEARRAY" | "GROUPBY" => Some(2),
"PIVOTBY" => Some(3),
_ => None,
};
position == Some(index)
}

/// A function given by name where a function is expected, as in `MAP({1;4};RAIZ)`, is
/// translated like a call. Booleans, bound names and names that are no function's are left alone.
fn function_argument(arg: &mut Expr, display: bool, bound: &impl Fn(&str) -> bool) -> Result<(), ParseError> {
let Expr::Name(name) = arg else { return Ok(()) };
if bound(name) || boolean_alias(name).is_some() {
Expand Down Expand Up @@ -214,18 +229,24 @@ fn normalize(expr: &mut Expr, known_name: &impl Fn(&str) -> bool, bindings: &mut
bindings.truncate(saved);
}
Expr::Call(name, args) => {
let mut canonical = name.clone();
if !bound(name, bindings) {
*name = translate_function(name, display, &|n| bound(n, bindings))?;
if !display {
canonical.clone_from(name);
}
}
for arg in args {
function_argument(arg, display, &|n| bound(n, bindings))?;
let count = args.len();
for (i, arg) in args.iter_mut().enumerate() {
if takes_function(&canonical, i, count) {
function_argument(arg, display, &|n| bound(n, bindings))?;
}
normalize(arg, known_name, bindings, depth + 1, display)?;
}
}
Expr::Invoke(callee, args) => {
normalize(callee, known_name, bindings, depth + 1, display)?;
for arg in args {
function_argument(arg, display, &|n| bound(n, bindings))?;
normalize(arg, known_name, bindings, depth + 1, display)?;
}
}
Expand Down
15 changes: 14 additions & 1 deletion crates/formula/tests/it/spanish_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,21 @@ fn a_function_given_by_name_as_an_argument_is_translated() {
let shown = print_input(&parse("LET(RAIZ,1,MAP(A1:A2,SQRT))").unwrap(), es, |_| false).unwrap();
assert_eq!(shown, "LET(RAIZ;1;MAP(A1:A2;SQRT))");
assert_eq!(print(&parse_input(&shown, es, |_| false).unwrap()), "LET(RAIZ,1,MAP(A1:A2,SQRT))");
// A bare name outside an argument list stays a name.
// Only where a function is expected: an ordinary argument or a bare name stays a name.
assert_eq!(input("RAIZ+1"), "RAIZ+1");
assert_eq!(input("SUMA(RAIZ;1)"), "SUM(RAIZ,1)");
assert_eq!(input("MAP(RAIZ;RAIZ)"), "MAP(RAIZ,SQRT)");
assert_eq!(input("LAMBDA(x;x)(RAIZ)"), "LAMBDA(x,x)(RAIZ)");
for (src, expected) in [
("REDUCE(0;A1:A3;SUMA)", "REDUCE(0,A1:A3,SUM)"),
("SCAN(0;A1:A3;SUMA)", "SCAN(0,A1:A3,SUM)"),
("BYCOL(A1:B2;MAX)", "BYCOL(A1:B2,MAX)"),
("MAKEARRAY(2;2;PRODUCTO)", "MAKEARRAY(2,2,PRODUCT)"),
("AGRUPARPOR(A1:A9;B1:B9;PROMEDIO)", "GROUPBY(A1:A9,B1:B9,AVERAGE)"),
] {
assert_eq!(input(src), expected, "{src}");
}
assert_eq!(print_input(&parse("SUM(SQRT,1)").unwrap(), es, |_| false).unwrap(), "SUMA(SQRT;1)");
}

#[test]
Expand Down
13 changes: 11 additions & 2 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,12 @@ impl SheetApp {
/// Per-frame logic (control channel, screenshots). Call before `ui`.
pub fn logic(&mut self, ctx: &egui::Context) {
// Values show in the interface language's region (`1.234,5` and `31/12/2026` in Spanish).
gridcraft_engine::display::set_region(self.ui.language.region());
// The region is per thread: each frame sets this app's and puts the previous one back,
// so apps sharing a thread never show values in each other's region.
gridcraft_engine::display::in_region(self.ui.language.region(), || self.logic_in_region(ctx));
}

fn logic_in_region(&mut self, ctx: &egui::Context) {
self.ensure_text_width(ctx);
// A keytip control request lives one frame: the ribbon consumes it during `ui`, and
// anything that never reached a control (collapsed ribbon, tab switch) is dropped.
Expand Down Expand Up @@ -1724,8 +1729,12 @@ impl SheetApp {
self.ui.autosave = !self.ui.autosave;
}

/// Lays out the whole window.
/// Lays out the whole window, with values in this app's region (see [`Self::logic`]).
pub fn ui(&mut self, ui: &mut egui::Ui) {
gridcraft_engine::display::in_region(self.ui.language.region(), || self.ui_in_region(ui));
}

fn ui_in_region(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
if !self.fonts_ready || self.fonts_rebind {
ctx.request_repaint();
Expand Down
36 changes: 36 additions & 0 deletions crates/ui-egui/tests/it/formula_locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,39 @@ fn ukrainian_entry_uses_english_names_with_semicolons_and_the_decimal_comma() {
app.begin_edit(None, true);
assert_eq!(app.editor.as_ref().unwrap().text, "=SUM(1.5,2)");
}

/// The display region is per thread. Two apps on one thread, in Spanish and in English, each
/// show values in their own region however their frames interleave, and a frame leaves the
/// thread's region as it found it.
#[test]
fn apps_sharing_a_thread_show_values_in_their_own_region() {
use egui_kittest::kittest::Queryable as _;
use gridcraft_engine::core::Region;
use gridcraft_engine::display::{region, set_region};
let harness = |language: &str| {
let mut a = app();
a.run("cell.set", json!({"cell":"A1","input":"1234.5"})).unwrap();
a.run("app.language.set", json!({"language": language})).unwrap();
set_region(Region::EnUs);
crate::common::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
a,
)
};
let mut spanish = harness("es");
let mut english = harness("en");
for _ in 0..2 {
spanish.run_steps(2);
assert!(spanish.query_by_label("1234,5").is_some(), "Spanish formula bar");
assert_eq!(region(), Region::EnUs, "a Spanish frame leaves the thread in en-US");
english.run_steps(2);
assert!(english.query_by_label("1234.5").is_some(), "English formula bar");
}
set_region(Region::UkUa);
english.run_steps(1);
assert_eq!(region(), Region::UkUa);
set_region(Region::EnUs);
}
4 changes: 2 additions & 2 deletions crates/xlsx/src/csv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::sync::Arc;

use gridcraft_core::parse::parse_input;
use gridcraft_core::parse::parse_file_input;
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, Value};
use gridcraft_model::{Cell, NumFmt, Sheet, StyleId, Workbook};

Expand Down Expand Up @@ -276,7 +276,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result<Workbook, IoError> {
}
let pos = CellRef::new(row, col as u32);
let cell = if opts.parse_values {
let p = parse_input(&f, opts.date_system);
let p = parse_file_input(&f, opts.date_system);
let style = match p.format {
Some(code) => match fmt_cache.iter().find(|(c, _)| *c == code) {
Some((_, id)) => *id,
Expand Down
11 changes: 11 additions & 0 deletions crates/xlsx/src/tests/csv_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,3 +326,14 @@ fn parser_stops_collecting_fields_at_max_cols() {
});
assert_eq!(lens, vec![MAX_COLS as usize]);
}

#[test]
fn csv_values_stay_en_us_without_the_typed_euro_and_hryvnia_forms() {
// Typed entry reads `12,50 €` and `250 грн` in a region; a CSV file is read as en-US text.
let src = "€5,12.50 €,250 грн,$5";
let wb = read_csv(src.as_bytes(), &CsvOptions::default()).unwrap();
assert_eq!(v(&wb, 0, 0), Value::text("€5"));
assert_eq!(v(&wb, 0, 1), Value::text("12.50 €"));
assert_eq!(v(&wb, 0, 2), Value::text("250 грн"));
assert_eq!(v(&wb, 0, 3), Value::Number(5.0));
}