mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-01 18:26:05 -06:00
Merge branch 'main' into PR #684
# Conflicts: # crates/xlsx/src/chart.rs # crates/xlsx/src/read.rs
This commit is contained in:
@@ -18,6 +18,7 @@ pub mod macros;
|
||||
pub mod pivot;
|
||||
pub mod print;
|
||||
pub mod python;
|
||||
pub mod quick_analysis;
|
||||
pub mod review;
|
||||
pub mod sheet;
|
||||
pub mod slicer;
|
||||
@@ -187,6 +188,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(forecast::specs());
|
||||
v.extend(analysis::specs());
|
||||
v.extend(print::specs());
|
||||
v.extend(quick_analysis::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -32,9 +32,12 @@ use sort::{quick_sort, sort};
|
||||
#[cfg(test)]
|
||||
use tools::split_delimited;
|
||||
use tools::{remove_duplicates, text_to_columns};
|
||||
pub use validation::{check_validation, list_items};
|
||||
use validation::{circle_invalid, validate_cmd, validation};
|
||||
pub(super) use validation::{move_rule_formula, remove_validation_cells};
|
||||
pub use validation::{
|
||||
LIST_MATCH_CAP, LIST_SOURCE_BUDGET, ListSource, check_validation, filter_list_items, list_items, list_search_source, search_fold, search_matches,
|
||||
search_term,
|
||||
};
|
||||
use validation::{circle_invalid, validate_cmd, validation, validation_list_cmd};
|
||||
pub(super) use validation::{move_rule_formula, moved_rule_parts, remove_rule_cells, remove_validation_cells};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -99,6 +102,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
validation
|
||||
),
|
||||
cmd!(query "data.validate", "Check Value Against Validation", [], None, "{cell?, input} → {ok, message?}", has_doc, validate_cmd),
|
||||
cmd!(
|
||||
query "data.validationList",
|
||||
"Validation List Items",
|
||||
[],
|
||||
None,
|
||||
"{cell?, search?} → {items: [..], truncated} (the cell's list validation entries; `search` keeps those with a word starting with it, ignoring case and the accents of Latin letters; at most 10,000 entries, read from at most 200,000 cells of the source; `truncated`: more may exist)",
|
||||
has_doc,
|
||||
validation_list_cmd
|
||||
),
|
||||
cmd!(noundo "data.circleInvalid", "Circle Invalid Data", ["Data", "Data Tools", "Data Validation"], None, "{} → {invalid: [cell], truncated: bool (true when the 100,000-cell scan allowance ended before every range was checked)}", has_doc, circle_invalid),
|
||||
CommandSpec {
|
||||
shortcut_mac: Some("Cmd+Shift+K"),
|
||||
|
||||
@@ -557,3 +557,144 @@ fn a_rule_with_an_unknown_type_operator_or_error_style_is_refused() {
|
||||
assert_eq!(sh.validations.len(), 3);
|
||||
assert!(check_validation(&s.doc().unwrap().wb, 0, CellRef::parse("A2").unwrap(), "0").is_some());
|
||||
}
|
||||
|
||||
fn finds(item: &str, typed: &str) -> bool {
|
||||
search_matches(&search_fold(item), &search_term(typed))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_search_matches_from_a_word_start() {
|
||||
let la = "Los Angeles - United States of America";
|
||||
for ok in ["Los an", " Los an", "Ange", "United St", "united st", "of America", "- United", "", "L"] {
|
||||
assert!(finds(la, ok), "{ok:?} should match");
|
||||
}
|
||||
for bad in ["United Amer", "geles", "os", "States America", "Los Angeles -"] {
|
||||
assert!(!finds(la, bad), "{bad:?} should not match");
|
||||
}
|
||||
// A word start can hide behind an earlier, overlapping occurrence.
|
||||
assert!(finds("xa-a-a", "a-a"));
|
||||
assert!(finds("(USA)", "usa"));
|
||||
assert!(finds("2024 report", "202"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_search_ignores_case_and_accents() {
|
||||
assert!(finds("États-Unis", "etats"));
|
||||
assert!(finds("États-Unis", "UNIS"));
|
||||
assert!(finds("Etats-Unis", "États"));
|
||||
assert!(finds("Straße", "strasse"));
|
||||
assert!(finds("Œuvre", "oe"));
|
||||
assert!(finds("Łódź", "lodz"));
|
||||
// Decomposed accents (e + combining acute) fold the same and don't start a word.
|
||||
assert!(finds("Cafe\u{301} noir", "café n"));
|
||||
assert!(!finds("Cafe\u{301}s", "s"));
|
||||
assert!(finds("東京", "東"));
|
||||
// Vietnamese (Latin Extended Additional, with ơ/ư from Latin Extended-B), any case.
|
||||
assert!(finds("Hà Nội - Vietnam", "ha noi"));
|
||||
assert!(finds("Đà Nẵng", "da nang"));
|
||||
assert!(finds("Thừa Thiên Huế", "thua thien hue"));
|
||||
assert!(finds("HỒ CHÍ MINH", "ho chi"));
|
||||
assert!(finds("Hồ Chí Minh", "HỒ CHÍ"));
|
||||
assert!(finds("Phường Bến Nghé", "phuong ben"));
|
||||
// Pinyin tone marks, transliterations with dots below.
|
||||
assert!(finds("Běijīng", "beijing"));
|
||||
assert!(finds("Lǜ", "lu"));
|
||||
assert!(finds("Ḥaifa", "haifa"));
|
||||
assert_eq!(search_fold("ỆỢỰẠẞ"), "eouass");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_list_items_keeps_order_and_cap() {
|
||||
let items: Vec<String> = ["Dubai - United Arab Emirates", "Paris - France", "London - United Kingdom", "Boston - United States"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
assert_eq!(filter_list_items(&items, "United", 100), [0, 2, 3]);
|
||||
assert_eq!(filter_list_items(&items, "United St", 100), [3]);
|
||||
assert_eq!(filter_list_items(&items, "United", 2), [0, 2]);
|
||||
assert!(filter_list_items(&items, "zzz", 100).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_list_command_returns_filtered_items() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "E1", "values": [["Paris - France"], ["Dubai - United Arab Emirates"], ["New York - United States"]]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.validation", json!({"range": "B2:B5", "type": "list", "formula1": "=$E$1:$E$3"})).unwrap();
|
||||
let all = s.execute("data.validationList", json!({"cell": "B3"})).unwrap();
|
||||
assert_eq!(all["items"].as_array().map(Vec::len), Some(3));
|
||||
assert_eq!(all["truncated"], json!(false));
|
||||
let some = s.execute("data.validationList", json!({"cell": "B3", "search": "united s"})).unwrap();
|
||||
assert_eq!(some["items"], json!(["New York - United States"]));
|
||||
assert!(s.execute("data.validationList", json!({"cell": "A1"})).is_err(), "no list validation on A1");
|
||||
s.execute("data.validation", json!({"range": "C1", "type": "list", "formula1": "\"Été,Hiver\""})).unwrap();
|
||||
let lit = s.execute("data.validationList", json!({"cell": "C1", "search": "ete"})).unwrap();
|
||||
assert_eq!(lit["items"], json!(["Été"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_list_search_reads_a_huge_source_within_its_budget() {
|
||||
// A list from a whole column used far past the source budget: a search with no match must
|
||||
// stop at the budget (and say so) rather than read and fold every cell first.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = LIST_SOURCE_BUDGET + 5_000;
|
||||
{
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
for r in 0..rows {
|
||||
sh.cells.set(CellRef::new(r as u32, 4), Cell::value(Value::Text(format!("Item {r}").into())));
|
||||
}
|
||||
}
|
||||
s.execute("data.validation", json!({"range": "B2", "type": "list", "formula1": "=$E:$E"})).unwrap();
|
||||
let none = s.execute("data.validationList", json!({"cell": "B2", "search": "zzz"})).unwrap();
|
||||
assert_eq!(none["items"], json!([]));
|
||||
assert_eq!(none["truncated"], json!(true), "the source was not read to its end");
|
||||
let first = s.execute("data.validationList", json!({"cell": "B2", "search": "item 1"})).unwrap();
|
||||
assert_eq!(first["items"][0], json!("Item 1"));
|
||||
|
||||
let wb = s.doc().unwrap().wb.clone();
|
||||
let dv = wb.active().unwrap().validations[0].clone();
|
||||
let src = list_search_source(&wb, 0, CellRef::new(1, 1), &dv, LIST_SOURCE_BUDGET);
|
||||
assert!(src.truncated);
|
||||
assert_eq!(src.items.len(), LIST_SOURCE_BUDGET, "exactly the budget's worth of cells read");
|
||||
// The membership check still sees the whole column.
|
||||
let last = format!("Item {}", rows - 1);
|
||||
assert!(check_validation(&wb, 0, CellRef::new(1, 1), &last).is_none(), "{last} is in the list");
|
||||
// A computed source (a name for a formula) over the same column runs out of formula work instead.
|
||||
s.execute("formulas.defineName", json!({"name": "Sorted", "refersTo": "=SORT(Sheet1!$E:$E)"})).unwrap();
|
||||
s.execute("data.validation", json!({"range": "C2", "type": "list", "formula1": "=Sorted"})).unwrap();
|
||||
let sorted = s.execute("data.validationList", json!({"cell": "C2", "search": "zzz"})).unwrap();
|
||||
assert_eq!(sorted["truncated"], json!(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_search_source_matches_list_items_within_budget() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B1:B5", "values": [["a"], [null], ["c"], ["d"], ["e"]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=SEQUENCE(4)"})).unwrap();
|
||||
s.execute("data.validation", json!({"range": "A1:A2", "type": "list", "formula1": "=$B1:$B4"})).unwrap();
|
||||
s.execute("data.validation", json!({"range": "C1", "type": "list", "formula1": "=$D$1:$D$9"})).unwrap();
|
||||
s.execute("data.validation", json!({"range": "F1", "type": "list", "formula1": "\"x,y,z\""})).unwrap();
|
||||
s.execute("formulas.defineName", json!({"name": "Upper", "refersTo": "=UPPER(Sheet1!$B$1:$B$5)"})).unwrap();
|
||||
s.execute("data.validation", json!({"range": "G1", "type": "list", "formula1": "=Upper"})).unwrap();
|
||||
let wb = s.doc().unwrap().wb.clone();
|
||||
let rules = wb.active().unwrap().validations.clone();
|
||||
for (dv, cell) in rules.iter().zip(["A2", "C1", "F1", "G1"]) {
|
||||
let at = CellRef::parse(cell).unwrap();
|
||||
let full = list_items(&wb, 0, at, dv);
|
||||
assert!(!full.is_empty(), "{cell}");
|
||||
let src = list_search_source(&wb, 0, at, dv, LIST_SOURCE_BUDGET);
|
||||
assert_eq!(src, ListSource { items: full.clone(), truncated: false }, "{cell}");
|
||||
// A tiny budget keeps the beginning and says the rest was not read.
|
||||
let cut = list_search_source(&wb, 0, at, dv, 1);
|
||||
assert!(cut.truncated, "{cell}: {cut:?}");
|
||||
assert!(full.starts_with(&cut.items), "{cell}: {cut:?}");
|
||||
}
|
||||
// The spilled SEQUENCE is read cell by cell like stored values.
|
||||
assert_eq!(list_search_source(&wb, 0, CellRef::new(0, 2), &rules[1], 100).items, ["1", "2", "3", "4"]);
|
||||
}
|
||||
|
||||
@@ -87,19 +87,67 @@ fn subtract_ranges(r: RangeRef, cuts: &[RangeRef]) -> Vec<RangeRef> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A conditional format or validation: ranges, and formulas written for their top-left cell.
|
||||
pub(in super::super) trait Rule: Clone {
|
||||
fn parts(&mut self) -> (&mut Vec<RangeRef>, Vec<&mut String>);
|
||||
}
|
||||
|
||||
impl Rule for Validation {
|
||||
fn parts(&mut self) -> (&mut Vec<RangeRef>, Vec<&mut String>) {
|
||||
let Validation { ranges, f1, f2, .. } = self;
|
||||
(ranges, std::iter::once(f1).chain(f2.as_mut()).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl Rule for gridcraft_model::CondFormat {
|
||||
fn parts(&mut self) -> (&mut Vec<RangeRef>, Vec<&mut String>) {
|
||||
(&mut self.ranges, self.rule.relative_formulas_mut())
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges.
|
||||
/// When the rule's top-left cell goes, its relative formulas are rewritten for the new top-left
|
||||
/// cell, so the cells left keep checking the same cells.
|
||||
pub(in super::super) fn remove_validation_cells(validations: &mut Vec<Validation>, cuts: &[RangeRef]) {
|
||||
for dv in validations.iter_mut() {
|
||||
let before = RangeRef::top_left(&dv.ranges);
|
||||
dv.ranges = dv.ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).collect();
|
||||
if let (Some(from), Some(to)) = (before, RangeRef::top_left(&dv.ranges)) {
|
||||
dv.f1 = move_rule_formula(&dv.f1, from, to);
|
||||
dv.f2 = dv.f2.take().map(|f| move_rule_formula(&f, from, to));
|
||||
remove_rule_cells(validations, cuts);
|
||||
}
|
||||
|
||||
/// [`remove_validation_cells`] for any kind of rule.
|
||||
pub(in super::super) fn remove_rule_cells<T: Rule>(rules: &mut Vec<T>, cuts: &[RangeRef]) {
|
||||
for rule in rules.iter_mut() {
|
||||
let (ranges, formulas) = rule.parts();
|
||||
let before = RangeRef::top_left(ranges);
|
||||
*ranges = ranges.iter().flat_map(|r| subtract_ranges(*r, cuts)).collect();
|
||||
if let (Some(from), Some(to)) = (before, RangeRef::top_left(ranges)) {
|
||||
for f in formulas {
|
||||
*f = move_rule_formula(f, from, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
validations.retain(|d| !d.ranges.is_empty());
|
||||
rules.retain_mut(|r| !r.parts().0.is_empty());
|
||||
}
|
||||
|
||||
/// The parts of `rules` inside `block`, moved to the block at `to`, as a cut takes them with
|
||||
/// its cells. Each part's formulas stay written for where its top-left cell was, as a cut
|
||||
/// cell's formula is copied: the reference rewrite for the move then shifts them.
|
||||
pub(in super::super) fn moved_rule_parts<T: Rule>(rules: &[T], block: RangeRef, to: CellRef) -> Vec<T> {
|
||||
let dr = i64::from(to.row) - i64::from(block.start.row);
|
||||
let dc = i64::from(to.col) - i64::from(block.start.col);
|
||||
let mut out = Vec::new();
|
||||
for rule in rules {
|
||||
let mut part = rule.clone();
|
||||
let (ranges, formulas) = part.parts();
|
||||
let Some(first) = RangeRef::top_left(ranges) else { continue };
|
||||
let inside: Vec<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&block)).collect();
|
||||
let Some(from) = RangeRef::top_left(&inside) else { continue };
|
||||
let moved: Vec<RangeRef> = inside.iter().filter_map(|r| Some(RangeRef::new(r.start.offset(dr, dc)?, r.end.offset(dr, dc)?))).collect();
|
||||
for f in formulas {
|
||||
*f = move_rule_formula(f, first, from);
|
||||
}
|
||||
*ranges = moved;
|
||||
out.push(part);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn validation(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
@@ -221,6 +269,226 @@ pub fn list_items(wb: &Workbook, sheet: usize, at: CellRef, dv: &Validation) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// Most entries a searched validation list returns (lists can come from huge ranges).
|
||||
pub const LIST_MATCH_CAP: usize = 10_000;
|
||||
|
||||
/// Source work a searched validation list may do: cells of its range read (or entries of a literal
|
||||
/// list, or units of formula work for a computed source). A list from a huge range (`$B:$B` on a
|
||||
/// sheet used to row 1,048,576) stops here instead of reading every cell, whatever is typed.
|
||||
pub const LIST_SOURCE_BUDGET: usize = 200_000;
|
||||
|
||||
/// The entries of a list validation read for search, within a source-work budget.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ListSource {
|
||||
/// Nonempty entries in list order, up to where the budget ran out.
|
||||
pub items: Vec<String>,
|
||||
/// The budget ran out before the whole source was read: `items` is only its beginning.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// The entries of a list validation for the cell `at`, as [`list_items`] gives them, but reading at
|
||||
/// most `budget` units of the source (see [`LIST_SOURCE_BUDGET`]). A range source is walked cell by
|
||||
/// cell, within the sheet's used range, rather than evaluated into an array first.
|
||||
pub fn list_search_source(wb: &Workbook, sheet: usize, at: CellRef, dv: &Validation, budget: usize) -> ListSource {
|
||||
let f = dv.f1.trim();
|
||||
if is_literal_list(f) {
|
||||
// A literal list is bounded by the rule's text; the budget still caps the entries kept.
|
||||
let mut items = list_items(wb, sheet, at, dv);
|
||||
let truncated = items.len() > budget;
|
||||
items.truncate(budget);
|
||||
return ListSource { items, truncated };
|
||||
}
|
||||
let first = RangeRef::top_left(&dv.ranges).unwrap_or(at);
|
||||
let work = u64::try_from(budget).unwrap_or(u64::MAX);
|
||||
match gridcraft_calc::evaluate_bounded(wb, sheet, at, &formula_at(f, first, at), work) {
|
||||
// One area is read as the evaluator would (several areas or sheets are `#VALUE!`: no list).
|
||||
gridcraft_calc::Bounded::Areas(areas) => match areas.as_slice() {
|
||||
[a] => walk_area(wb, a.sheet, a.range, budget),
|
||||
_ => ListSource::default(),
|
||||
},
|
||||
gridcraft_calc::Bounded::Value(Value::Array(a)) => {
|
||||
let mut out = ListSource::default();
|
||||
for (n, v) in a.data.iter().enumerate() {
|
||||
if n >= budget {
|
||||
out.truncated = true;
|
||||
break;
|
||||
}
|
||||
if !v.is_empty() {
|
||||
out.items.push(v.display());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
gridcraft_calc::Bounded::Value(v) if !v.is_empty() && !v.is_error() => ListSource { items: vec![v.display()], truncated: false },
|
||||
gridcraft_calc::Bounded::Value(_) => ListSource::default(),
|
||||
gridcraft_calc::Bounded::Exhausted => ListSource { items: vec![], truncated: true },
|
||||
}
|
||||
}
|
||||
|
||||
/// The nonempty values of `range` on `sheet`, row-major, reading at most `budget` cells. Without
|
||||
/// spilled values in the range only stored cells are visited; with them, every cell inside the
|
||||
/// sheet's used range (and the spills) is. Each visited cell counts against the budget.
|
||||
fn walk_area(wb: &Workbook, sheet: usize, range: RangeRef, budget: usize) -> ListSource {
|
||||
let mut out = ListSource::default();
|
||||
let Some(sh) = wb.sheet(sheet) else { return out };
|
||||
let spilled = sh.spill_ranges.values().filter_map(|r| r.intersection(&range)).collect::<Vec<_>>();
|
||||
let mut seen = 0usize;
|
||||
let mut take = |v: &Value, out: &mut ListSource| {
|
||||
if seen >= budget {
|
||||
out.truncated = true;
|
||||
return false;
|
||||
}
|
||||
seen += 1;
|
||||
if !v.is_empty() {
|
||||
out.items.push(v.display());
|
||||
}
|
||||
true
|
||||
};
|
||||
if spilled.is_empty() {
|
||||
for (_, cell) in sh.cells.iter_range(range) {
|
||||
if !take(&cell.value, &mut out) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let extent = spilled.iter().fold(sh.used_range(), |u, r| Some(u.map_or(*r, |u| u.union(r))));
|
||||
let Some(range) = extent.and_then(|u| u.intersection(&range)) else { return out };
|
||||
for c in range.iter() {
|
||||
if !take(&sh.value(c), &mut out) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Text folded for list search: lower case, with the accents of Latin letters removed
|
||||
/// (`É` → `e`, `ß` → `ss`, `Œ` → `oe`, `Ộ` → `o`) and combining marks dropped. Covers Latin-1,
|
||||
/// Latin Extended-A and -B and Latin Extended Additional; other scripts keep their marks.
|
||||
pub fn search_fold(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for ch in s.chars().flat_map(char::to_lowercase) {
|
||||
match fold_latin(ch) {
|
||||
Some(f) => out.push_str(f),
|
||||
None => out.push(ch),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The unaccented spelling of a lower-case Latin letter (`é` → `e`, `ß` → `ss`, `ộ` → `o`);
|
||||
/// combining marks fold to nothing. `None` leaves the character as it is.
|
||||
fn fold_latin(c: char) -> Option<&'static str> {
|
||||
Some(match c {
|
||||
'\u{300}'..='\u{36f}' => "",
|
||||
'à'..='å' | 'ā' | 'ă' | 'ą' => "a",
|
||||
'æ' => "ae",
|
||||
'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => "c",
|
||||
'ð' | 'ď' | 'đ' => "d",
|
||||
'è'..='ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e",
|
||||
'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g",
|
||||
'ĥ' | 'ħ' => "h",
|
||||
'ì'..='ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => "i",
|
||||
'ĵ' => "j",
|
||||
'ķ' => "k",
|
||||
'ĺ' | 'ļ' | 'ľ' | 'ŀ' | 'ł' => "l",
|
||||
'ñ' | 'ń' | 'ņ' | 'ň' => "n",
|
||||
'ò'..='ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o",
|
||||
'œ' => "oe",
|
||||
'ŕ' | 'ŗ' | 'ř' => "r",
|
||||
'ś' | 'ŝ' | 'ş' | 'š' | 'ș' => "s",
|
||||
'ß' => "ss",
|
||||
'ţ' | 'ť' | 'ŧ' | 'ț' => "t",
|
||||
'þ' => "th",
|
||||
'ù'..='ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u",
|
||||
'ŵ' => "w",
|
||||
'ý' | 'ÿ' | 'ŷ' => "y",
|
||||
'ź' | 'ż' | 'ž' => "z",
|
||||
// Latin Extended-B and Latin Extended Additional (Vietnamese, pinyin tones, …): the base
|
||||
// letter of each canonical decomposition (Unicode 15).
|
||||
'ǎ' | 'ǟ' | 'ǡ' | 'ǻ' | 'ȁ' | 'ȃ' | 'ȧ' | 'ḁ' | 'ạ' | 'ả' | 'ấ' | 'ầ' | 'ẩ' | 'ẫ' | 'ậ' | 'ắ' | 'ằ' | 'ẳ' | 'ẵ' | 'ặ' => {
|
||||
"a"
|
||||
}
|
||||
'ḃ' | 'ḅ' | 'ḇ' => "b",
|
||||
'ḉ' => "c",
|
||||
'ḋ' | 'ḍ' | 'ḏ' | 'ḑ' | 'ḓ' => "d",
|
||||
'ȅ' | 'ȇ' | 'ȩ' | 'ḕ' | 'ḗ' | 'ḙ' | 'ḛ' | 'ḝ' | 'ẹ' | 'ẻ' | 'ẽ' | 'ế' | 'ề' | 'ể' | 'ễ' | 'ệ' => "e",
|
||||
'ḟ' => "f",
|
||||
'ǧ' | 'ǵ' | 'ḡ' => "g",
|
||||
'ȟ' | 'ḣ' | 'ḥ' | 'ḧ' | 'ḩ' | 'ḫ' | 'ẖ' => "h",
|
||||
'ǐ' | 'ȉ' | 'ȋ' | 'ḭ' | 'ḯ' | 'ỉ' | 'ị' => "i",
|
||||
'ǰ' => "j",
|
||||
'ǩ' | 'ḱ' | 'ḳ' | 'ḵ' => "k",
|
||||
'ḷ' | 'ḹ' | 'ḻ' | 'ḽ' => "l",
|
||||
'ḿ' | 'ṁ' | 'ṃ' => "m",
|
||||
'ǹ' | 'ṅ' | 'ṇ' | 'ṉ' | 'ṋ' => "n",
|
||||
'ơ' | 'ǒ' | 'ǫ' | 'ǭ' | 'ȍ' | 'ȏ' | 'ȫ' | 'ȭ' | 'ȯ' | 'ȱ' | 'ṍ' | 'ṏ' | 'ṑ' | 'ṓ' | 'ọ' | 'ỏ' | 'ố' | 'ồ' | 'ổ' | 'ỗ' | 'ộ' | 'ớ' | 'ờ'
|
||||
| 'ở' | 'ỡ' | 'ợ' => "o",
|
||||
'ṕ' | 'ṗ' => "p",
|
||||
'ȑ' | 'ȓ' | 'ṙ' | 'ṛ' | 'ṝ' | 'ṟ' => "r",
|
||||
'ṡ' | 'ṣ' | 'ṥ' | 'ṧ' | 'ṩ' => "s",
|
||||
'ṫ' | 'ṭ' | 'ṯ' | 'ṱ' | 'ẗ' => "t",
|
||||
'ư' | 'ǔ' | 'ǖ' | 'ǘ' | 'ǚ' | 'ǜ' | 'ȕ' | 'ȗ' | 'ṳ' | 'ṵ' | 'ṷ' | 'ṹ' | 'ṻ' | 'ụ' | 'ủ' | 'ứ' | 'ừ' | 'ử' | 'ữ' | 'ự' => {
|
||||
"u"
|
||||
}
|
||||
'ṽ' | 'ṿ' => "v",
|
||||
'ẁ' | 'ẃ' | 'ẅ' | 'ẇ' | 'ẉ' | 'ẘ' => "w",
|
||||
'ẋ' | 'ẍ' => "x",
|
||||
'ȳ' | 'ẏ' | 'ẙ' | 'ỳ' | 'ỵ' | 'ỷ' | 'ỹ' => "y",
|
||||
'ẑ' | 'ẓ' | 'ẕ' => "z",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The search term as typed, folded for [`search_matches`]. Leading spaces are ignored.
|
||||
pub fn search_term(typed: &str) -> String {
|
||||
search_fold(typed.trim_start())
|
||||
}
|
||||
|
||||
/// Whether a folded list entry matches a folded search term, as Excel's in-cell list search:
|
||||
/// the term appears as one piece that starts at the beginning of a word ("United St" finds
|
||||
/// "Los Angeles - United States", "geles" and "United Amer" don't).
|
||||
pub fn search_matches(folded_item: &str, folded_term: &str) -> bool {
|
||||
if folded_term.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let mut prev: Option<char> = None;
|
||||
for (i, ch) in folded_item.char_indices() {
|
||||
if prev.is_none_or(|p| !p.is_alphanumeric()) && folded_item.get(i..).is_some_and(|rest| rest.starts_with(folded_term)) {
|
||||
return true;
|
||||
}
|
||||
prev = Some(ch);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Indices of the list entries matching `typed`, in list order, at most `cap` of them.
|
||||
pub fn filter_list_items(items: &[String], typed: &str, cap: usize) -> Vec<usize> {
|
||||
let term = search_term(typed);
|
||||
items.iter().enumerate().filter(|(_, it)| search_matches(&search_fold(it), &term)).map(|(i, _)| i).take(cap).collect()
|
||||
}
|
||||
|
||||
/// `data.validationList`: a cell's list validation entries, searched like the in-cell dropdown,
|
||||
/// at most [`LIST_MATCH_CAP`] of them, from at most [`LIST_SOURCE_BUDGET`] of source work.
|
||||
/// `truncated` says that more entries may exist (past the match cap, or past the source budget).
|
||||
pub(super) fn validation_list_cmd(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let sheet = d.wb.active_sheet();
|
||||
let dv =
|
||||
d.wb.sheet(sheet)
|
||||
.and_then(|sh| sh.validations.iter().find(|v| v.kind == ValidationKind::List && v.ranges.iter().any(|r| r.contains(at))))
|
||||
.ok_or_else(|| EngineError::Other(format!("{} has no list validation", at.a1())))?;
|
||||
let ListSource { items, truncated: source_truncated } = list_search_source(&d.wb, sheet, at, dv, LIST_SOURCE_BUDGET);
|
||||
let picked: Vec<usize> = match str_param(p, "search") {
|
||||
Some(term) => filter_list_items(&items, term, LIST_MATCH_CAP.saturating_add(1)),
|
||||
None => (0..items.len().min(LIST_MATCH_CAP.saturating_add(1))).collect(),
|
||||
};
|
||||
let truncated = source_truncated || picked.len() > LIST_MATCH_CAP;
|
||||
let out: Vec<&String> = picked.iter().take(LIST_MATCH_CAP).filter_map(|&i| items.get(i)).collect();
|
||||
Ok(json!({"items": out, "truncated": truncated}))
|
||||
}
|
||||
|
||||
/// Checks typed input against the validation of a cell. `Ok(None)` = valid.
|
||||
pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -> Option<(Validation, String)> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
|
||||
@@ -35,7 +35,7 @@ use go_to::go_to_special;
|
||||
#[cfg(test)]
|
||||
use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts};
|
||||
use paste_special::paste_special;
|
||||
pub(crate) use paste_special::{rewrite_all_formulas_many, rewrite_cell_links, rewrite_python_refs};
|
||||
pub(crate) use paste_special::{place_moved_rules, rewrite_all_formulas_many, rewrite_python_refs};
|
||||
use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"AutoFill",
|
||||
[],
|
||||
None,
|
||||
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday)",
|
||||
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years|linearTrend|growthTrend}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday; linearTrend, growthTrend = Linear Trend, Growth Trend: the targets continue the least-squares line or the exponential curve fitted to each row or column of source numbers, and the source keeps its values; an error when a source cell is not a number or holds a formula, or for growthTrend when a row or column mixes signs or holds zero)",
|
||||
has_doc,
|
||||
auto_fill
|
||||
),
|
||||
@@ -206,6 +206,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.selection = e.selection;
|
||||
// Step by step: a rename and a new sheet undone together match up only one step apart.
|
||||
super::extra::keep_view_modes(d, &cur_wb);
|
||||
super::view::keep_zoom(d, &cur_wb);
|
||||
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
@@ -227,6 +228,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.wb = e.wb;
|
||||
d.selection = e.selection;
|
||||
super::extra::keep_view_modes(d, &cur_wb);
|
||||
super::view::keep_zoom(d, &cur_wb);
|
||||
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
|
||||
@@ -8,14 +8,12 @@ use super::{
|
||||
/// Typing `=PY(` doesn't make a Python cell; this says what does.
|
||||
pub(crate) const PY_FORMULA: &str = "Python cells are made with the python.set command (the code as `code`), not by typing =PY(…).";
|
||||
|
||||
/// Whether typing `input` into a cell enters a formula: `=…`, or `+…`/`-…` followed by a name or
|
||||
/// a parenthesis (not a number), as Excel takes `+SUM(1)`.
|
||||
/// Whether typing `input` into a cell is meant as a formula: `=…`, or `+…`/`-…` when the entry
|
||||
/// isn't a number on its own, as Excel takes `+5+4` and `+SUM(1)` (see
|
||||
/// [`gridcraft_core::parse::starts_formula`]). A `+…`/`-…` entry that doesn't parse as a formula
|
||||
/// still enters as text (`--`), see [`input_to_cell`].
|
||||
pub(crate) fn is_formula_input(input: &str) -> bool {
|
||||
input.starts_with('=')
|
||||
|| (input.len() > 1
|
||||
&& (input.starts_with('+') || input.starts_with('-'))
|
||||
&& gridcraft_core::parse::parse_number_text(input).is_none()
|
||||
&& input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '('))
|
||||
gridcraft_core::parse::starts_formula(input)
|
||||
}
|
||||
|
||||
/// What typing `input` into a cell produces (constant or formula, plus an automatic number
|
||||
@@ -35,7 +33,15 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
if is_formula && gridcraft_model::python::is_py_formula(input) {
|
||||
return Err(EngineError::Other(PY_FORMULA.into()));
|
||||
}
|
||||
if is_formula {
|
||||
// As in Excel, a `+` or `-` entry is a formula when it reads as one (`+5+4` enters `=+5+4`)
|
||||
// and text when it doesn't (`--`, `+49 170 1234567`); only `=` entries are refused.
|
||||
if is_formula
|
||||
&& !input.starts_with('=')
|
||||
&& let Ok(cell) = input_to_cell(&format!("={input}"), sheet, at, wb)
|
||||
{
|
||||
return Ok(cell);
|
||||
}
|
||||
if input.starts_with('=') {
|
||||
let body = input.strip_prefix('=').unwrap_or(input);
|
||||
let expr = wb.name_call_case(parse_typed_formula(body)?);
|
||||
check_arg_counts(&expr)?;
|
||||
@@ -143,24 +149,66 @@ pub(super) fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// the cell; a cell elsewhere (or on another sheet) gets a one-cell array.
|
||||
let selected = cx.sel.current();
|
||||
let range = if sheet == active_sheet && selected.contains(at) { selected } else { RangeRef::cell(at) };
|
||||
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
|
||||
// Excel forms no array from a constant: every cell of the selection takes the value.
|
||||
if cell.formula.is_none() && !range.is_single() {
|
||||
if range.count() > crate::fill::MAX_FILL_CELLS {
|
||||
return Err(EngineError::Other("That selection is too large to fill.".into()));
|
||||
}
|
||||
let mut by_style: std::collections::HashMap<StyleId, Option<Cell>> = std::collections::HashMap::new();
|
||||
for c in range.iter() {
|
||||
let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(c)).unwrap_or_default();
|
||||
let filled = match by_style.get(&style) {
|
||||
Some(filled) => filled.clone(),
|
||||
None => {
|
||||
let filled = input_to_cell(&input, sheet, c, &mut cx.wb)?;
|
||||
by_style.insert(style, filled.clone());
|
||||
filled
|
||||
}
|
||||
};
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
match filled {
|
||||
Some(f) => {
|
||||
sh.set_cell(c, f);
|
||||
crate::cmd::data::grow_autofilter(sh, c);
|
||||
}
|
||||
None => {
|
||||
sh.remove_cell(c);
|
||||
}
|
||||
}
|
||||
cx.touch(sheet, c);
|
||||
}
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
// A table header can't hold an array's value, and a table resizes under it.
|
||||
if !range.is_single() && cx.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&range))) {
|
||||
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
|
||||
}
|
||||
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
|
||||
if let Some(f) = cell.formula.as_mut() {
|
||||
std::sync::Arc::make_mut(f).array = Some(range);
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// The array takes the whole range: other cells in it lose their contents.
|
||||
for c in range.iter().skip(1).take(1_000_000) {
|
||||
if let Some(old) = sh.cells.get(c).filter(|x| x.has_content()) {
|
||||
let style = old.style;
|
||||
sh.set_cell(c, Cell { style, ..Cell::default() });
|
||||
}
|
||||
// The array takes the whole range: other cells in it lose their contents. Walk the
|
||||
// cells the sheet holds rather than every address, so a whole-column array clears
|
||||
// all of its area, and mark each cleared cell so formulas reading it recalculate.
|
||||
let cleared: Vec<(CellRef, StyleId)> =
|
||||
sh.cells.iter_range(range).filter(|(c, x)| *c != range.start && x.has_content()).map(|(c, x)| (c, x.style)).collect();
|
||||
for &(c, style) in &cleared {
|
||||
sh.set_cell(c, Cell { style, ..Cell::default() });
|
||||
}
|
||||
sh.set_cell(range.start, cell);
|
||||
cx.touch(sheet, range.start);
|
||||
// The array's results land in every cell of the range, stored or not, so readers of
|
||||
// an empty result cell need the touch too. A huge range marks only the cells it held.
|
||||
if range.count() <= 1_000_000 {
|
||||
for c in range.iter() {
|
||||
cx.touch(sheet, c);
|
||||
}
|
||||
} else {
|
||||
for (c, _) in cleared {
|
||||
cx.touch(sheet, c);
|
||||
}
|
||||
}
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?;
|
||||
|
||||
@@ -52,6 +52,8 @@ pub(super) fn auto_fill(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"weekdays" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Weekday),
|
||||
"months" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Month),
|
||||
"years" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Year),
|
||||
"linearTrend" => crate::fill::FillMode::LinearTrend,
|
||||
"growthTrend" => crate::fill::FillMode::GrowthTrend,
|
||||
_ => crate::fill::FillMode::Series,
|
||||
};
|
||||
if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS {
|
||||
|
||||
@@ -76,10 +76,48 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(EngineError::Other("Too many cells to paste as links at once.".into()));
|
||||
}
|
||||
let same_doc = s.doc()?.uid == clip.doc_uid;
|
||||
let cut_move = clip.cut && same_doc && what == What::All;
|
||||
// A cut in this workbook moves its cells: the source is emptied before the destination is
|
||||
// written. As in Excel, it moves only as a plain Paste onto one cell or an area of its own size
|
||||
// and shape. Every other way (a Paste Special option, tiling over a larger or differently shaped
|
||||
// area, a row the filter hides) would write the cut cells somewhere other than one place, or not
|
||||
// at all, after their source was gone, so it is refused here, before anything changes, and the
|
||||
// cut stays pending.
|
||||
let cut_move = clip.cut && same_doc;
|
||||
if cut_move {
|
||||
let plain = what == What::All && !link && !skip_blanks && !transpose && op == "none";
|
||||
if !plain {
|
||||
return Err(EngineError::Other("Cut cells can only be pasted with Paste. To use Paste Special, copy them instead.".into()));
|
||||
}
|
||||
let anchored = cell_param_on(s, p, "at", dest_sheet)?.is_some() || sel.is_single();
|
||||
if !anchored && (sel.height() != h || sel.width() != w) {
|
||||
return Err(EngineError::Other(
|
||||
"The cut cells and the paste area aren't the same size and shape: select one cell, or an area the size of the cut cells.".into(),
|
||||
));
|
||||
}
|
||||
// The rows the cut itself would land on, whatever the paste would skip: an anchored or
|
||||
// taller block is pasted straight down, so `skip_rows` (which only a tiled single row uses)
|
||||
// can't tell whether it would write into a hidden row.
|
||||
if let Some(end) = at.offset(i64::from(h) - 1, i64::from(w) - 1) {
|
||||
let dest = RangeRef::new(at, end);
|
||||
if s.doc()?.wb.sheet(dest_sheet).is_some_and(|sh| !super::filtered_rows(sh, dest).is_empty()) {
|
||||
return Err(EngineError::Other("The cut area can't be pasted into rows the filter hides.".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let src_wb = clip.wb.clone();
|
||||
let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) };
|
||||
let src_sheet_name = src_sheet.name.clone();
|
||||
// The source sheet's name now: a cut whose sheet was renamed after it moves its cells,
|
||||
// rules and the references to them on the sheet as it is named, not as the clipboard saw it.
|
||||
let src_sheet_name = match s.doc()?.wb.sheet(clip.sheet) {
|
||||
Some(live) if clip.cut && same_doc => live.name.clone(),
|
||||
_ => src_sheet.name.clone(),
|
||||
};
|
||||
// A cut moves its block as it is, as Excel's does: it can't be transposed, tiled over a
|
||||
// larger selection or pasted skipping blanks (the move's references, rules and arrays follow
|
||||
// the whole block unturned, and its rules replace the destination's under every cell).
|
||||
if cut_move && (transpose || skip_blanks || tiles_r > 1 || tiles_c > 1) {
|
||||
return Err(EngineError::Other("The cut area can only be pasted as it is: paste it without Transpose or Skip Blanks, into one cell.".into()));
|
||||
}
|
||||
edit(s, |cx| {
|
||||
// Styles from another workbook must be re-interned.
|
||||
let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default();
|
||||
@@ -92,6 +130,9 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let mut moved_formulas = std::collections::BTreeMap::new();
|
||||
let mut moved_pictures = std::collections::BTreeMap::new();
|
||||
// A cut moves the rules its cells hold now, not the clipboard's: rules cleared or added
|
||||
// since the cut would otherwise come back or be lost.
|
||||
let live_source = if cut_move { cx.wb.sheet(clip.sheet).cloned() } else { None };
|
||||
if cut_move {
|
||||
// Remove the source first (contents and formats), and fix references to it.
|
||||
let source = cx.sheet_mut(clip.sheet)?;
|
||||
@@ -194,7 +235,12 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
moved.dynamic = f.dynamic;
|
||||
return Some(std::sync::Arc::new(moved));
|
||||
}
|
||||
let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
|
||||
let moved = if transpose {
|
||||
// A transposed paste turns the references instead of shifting them (#2450).
|
||||
gridcraft_formula::adjust::transpose_relative(e, sc, dest)
|
||||
} else {
|
||||
gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64)
|
||||
};
|
||||
Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) }))
|
||||
};
|
||||
let moved_py = |cell: &Cell| -> Result<Option<std::sync::Arc<gridcraft_model::PyCode>>> {
|
||||
@@ -347,7 +393,8 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
let pasted = RangeRef::new(at, at.offset_clamped(i64::from(tiles_r * h) - 1, i64::from(tiles_c * w) - 1));
|
||||
if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) {
|
||||
// A cut takes its rules along itself (`move_cut_rules`, below).
|
||||
if !link && !cut_move && matches!(what, What::All | What::AllExceptBorders | What::Validation) {
|
||||
paste_validations(cx, src_sheet, src, dest_sheet, pasted, PasteMode { transpose, skip_blanks, skip_rows: &skip_rows })?;
|
||||
}
|
||||
if what == What::ColumnWidths {
|
||||
@@ -379,7 +426,8 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if cut_move {
|
||||
if let Some(live) = &live_source {
|
||||
move_cut_rules(cx, live, (clip.sheet, dest_sheet), src, at)?;
|
||||
// References elsewhere to the moved block now point to its new place.
|
||||
let e = if dest_sheet == clip.sheet {
|
||||
gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col }
|
||||
@@ -564,7 +612,67 @@ fn paste_validations(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
|
||||
/// A cut, or Move Columns, takes its cells' conditional formats and validation with it, from
|
||||
/// sheet `from` to the block at `at` on sheet `to`, replacing the rules there. The moved parts'
|
||||
/// formulas are handled as the moved cells' are: kept written for where their cells were (on
|
||||
/// another sheet, with their references to it named), so the reference rewrite for the move
|
||||
/// shifts those into the block once. `snapshot` is the source sheet before the block moved.
|
||||
pub(crate) fn move_cut_rules(
|
||||
cx: &mut crate::cmd::Ctx,
|
||||
snapshot: &gridcraft_model::Sheet,
|
||||
(from, to): (usize, usize),
|
||||
src: RangeRef,
|
||||
at: CellRef,
|
||||
) -> Result<()> {
|
||||
let mut cfs: Vec<gridcraft_model::CondFormat> = crate::cmd::data::moved_rule_parts(&snapshot.cond_formats, src, at);
|
||||
let mut dvs: Vec<gridcraft_model::Validation> = crate::cmd::data::moved_rule_parts(&snapshot.validations, src, at);
|
||||
if from != to {
|
||||
let name = |t: &mut String| {
|
||||
if let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) {
|
||||
let e = e.map(&mut |x| match x {
|
||||
gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => {
|
||||
r.sheet = gridcraft_formula::SheetSel::Named(snapshot.name.clone());
|
||||
gridcraft_formula::Expr::Ref(r)
|
||||
}
|
||||
other => other,
|
||||
});
|
||||
*t = format!("{}{}", if t.starts_with('=') { "=" } else { "" }, gridcraft_formula::print(&e));
|
||||
}
|
||||
};
|
||||
// Every formula, thresholds included: an unnamed reference would read the destination sheet.
|
||||
cfs.iter_mut().flat_map(|r| r.rule.formulas_mut()).for_each(name);
|
||||
dvs.iter_mut().flat_map(|r| r.formulas_mut()).for_each(name);
|
||||
}
|
||||
place_moved_rules(cx, (from, to), src, at, (cfs, dvs))
|
||||
}
|
||||
|
||||
/// Takes the rules off the cells of `src` on sheet `from` and puts `parts` (the moved parts of
|
||||
/// them, as [`move_cut_rules`] builds them) on the block at `at` on sheet `to`, in place of the
|
||||
/// rules there.
|
||||
pub(crate) fn place_moved_rules(
|
||||
cx: &mut crate::cmd::Ctx,
|
||||
(from, to): (usize, usize),
|
||||
src: RangeRef,
|
||||
at: CellRef,
|
||||
(cfs, dvs): (Vec<gridcraft_model::CondFormat>, Vec<gridcraft_model::Validation>),
|
||||
) -> Result<()> {
|
||||
let source = cx.sheet_mut(from)?;
|
||||
crate::cmd::data::remove_rule_cells(&mut source.cond_formats, &[src]);
|
||||
crate::cmd::data::remove_rule_cells(&mut source.validations, &[src]);
|
||||
let block = RangeRef::new(at, at.offset_clamped(i64::from(src.height()) - 1, i64::from(src.width()) - 1));
|
||||
let dest = cx.sheet_mut(to)?;
|
||||
crate::cmd::data::remove_rule_cells(&mut dest.cond_formats, &[block]);
|
||||
crate::cmd::data::remove_rule_cells(&mut dest.validations, &[block]);
|
||||
dest.cond_formats.extend(cfs);
|
||||
dest.validations.extend(dvs);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies a reference adjustment to every reference the workbook holds
|
||||
/// ([`Workbook::rewrite_references`]) and its Python cells, and moves the legacy array ranges
|
||||
/// on `target`.
|
||||
///
|
||||
/// [`Workbook::rewrite_references`]: gridcraft_model::Workbook::rewrite_references
|
||||
pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> {
|
||||
rewrite_all_formulas_many(wb, target, std::slice::from_ref(e))
|
||||
}
|
||||
@@ -572,90 +680,28 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
/// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once.
|
||||
pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> {
|
||||
use gridcraft_formula::adjust::Edit;
|
||||
let adjust_all =
|
||||
|host: &str, expr: gridcraft_formula::Expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e));
|
||||
wb.rewrite_references(&|host, expr| adjust_all(host.name, expr));
|
||||
// Rows and columns inserted or deleted on the target sheet move its legacy array ranges too
|
||||
// (a cut moves its arrays itself).
|
||||
let moves_arrays = |e: &Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, cell)| cell.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default();
|
||||
if keys.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let on_target = host.eq_ignore_ascii_case(target);
|
||||
let Some(sheet) = wb.sheet_mut(si) else { continue };
|
||||
for (c, f) in keys {
|
||||
// Borrows the tree and copies and prints only the formulas the edits change. A formula
|
||||
// the edits leave alone keeps its stored text, even if that text is not canonical.
|
||||
let Some(new) = f.with_expr(|x| {
|
||||
let mut cur: Option<gridcraft_formula::Expr> = None;
|
||||
for e in edits {
|
||||
if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) {
|
||||
cur = Some(n);
|
||||
}
|
||||
}
|
||||
cur
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let mut array = f.array;
|
||||
for e in edits {
|
||||
array = match array {
|
||||
Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e),
|
||||
a => a,
|
||||
};
|
||||
}
|
||||
let nf = match new {
|
||||
Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) },
|
||||
None if array != f.array => Formula { array, ..(*f).clone() },
|
||||
None => continue,
|
||||
};
|
||||
if let Some(cell) = sheet.cells.get_mut(c) {
|
||||
cell.formula = Some(std::sync::Arc::new(nf));
|
||||
let moves_arrays = |e: &&Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
if edits.iter().any(|e| moves_arrays(&e))
|
||||
&& let Some(si) = wb.sheet_index(target)
|
||||
&& let Some(sheet) = wb.sheet_mut(si)
|
||||
{
|
||||
let arrays: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
sheet.cells.iter().filter_map(|(c, cell)| cell.formula.clone().filter(|f| f.array.is_some()).map(|f| (c, f))).collect();
|
||||
for (c, f) in arrays {
|
||||
let array = edits.iter().filter(moves_arrays).fold(f.array, |a, e| a.and_then(|a| crate::cmd::sheet::map_range(a, e)));
|
||||
if array != f.array
|
||||
&& let Some(cell) = sheet.cells.get_mut(c)
|
||||
{
|
||||
cell.formula = Some(std::sync::Arc::new(Formula { array, ..(*f).clone() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
for n in wb.names.iter_mut() {
|
||||
if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) {
|
||||
// Names are workbook-level: unqualified refs don't occur; qualified ones adjust.
|
||||
let new = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e));
|
||||
n.formula = gridcraft_formula::print(&new);
|
||||
}
|
||||
}
|
||||
rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)));
|
||||
rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)))
|
||||
}
|
||||
|
||||
/// Runs `f` over every reference a floating object holds (a chart's series values, categories,
|
||||
/// name and bubble sizes, and the source block it was made from, and a form control's linked
|
||||
/// cell). Every edit that moves
|
||||
/// references calls it: inserting and deleting lines and cells and cut-moves (through
|
||||
/// [`rewrite_all_formulas`]), and renaming and deleting sheets. `f` maps a reference held by an
|
||||
/// object on the sheet named `host` to its new form; text that does not parse is kept. A source
|
||||
/// block that no longer exists is dropped.
|
||||
pub(crate) fn rewrite_cell_links(wb: &mut gridcraft_model::Workbook, f: impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr) {
|
||||
for si in 0..wb.sheets.len() {
|
||||
let Some(host) = wb.sheets.get(si).filter(|s| !s.charts.is_empty() || !s.controls.is_empty()).map(|s| s.name.clone()) else { continue };
|
||||
let Some(sh) = wb.sheet_mut(si) else { continue };
|
||||
let fix = |text: &str| -> String {
|
||||
match gridcraft_formula::parse(text) {
|
||||
Ok(expr) => gridcraft_formula::print(&f(&host, expr)),
|
||||
Err(_) => text.to_string(),
|
||||
}
|
||||
};
|
||||
for ch in sh.charts.iter_mut() {
|
||||
ch.source = ch.source.as_deref().map(fix).filter(|s| !s.contains("#REF!"));
|
||||
for se in ch.series.iter_mut() {
|
||||
se.values = fix(&se.values);
|
||||
se.categories = se.categories.as_deref().map(fix);
|
||||
se.name = se.name.as_deref().map(fix);
|
||||
se.bubble_sizes = se.bubble_sizes.as_deref().map(fix);
|
||||
}
|
||||
}
|
||||
for c in sh.controls.iter_mut() {
|
||||
c.link = c.link.as_deref().map(fix);
|
||||
}
|
||||
}
|
||||
rewrite_python_refs(wb, &adjust_all)
|
||||
}
|
||||
|
||||
/// Rewrites the `xl("…")` literals in every Python cell with `f`, which maps a reference held on
|
||||
|
||||
@@ -52,6 +52,13 @@ impl crate::DocState {
|
||||
// View state: set in place, so the workbook is neither copied nor made dirty.
|
||||
self.wb.set_active_sheet(i);
|
||||
self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default();
|
||||
// A sheet's first visit starts at A1, which may be part of a merged cell: take it whole,
|
||||
// as a click would (#1348). A selection the sheet remembers comes back as it was.
|
||||
if self.selection == crate::Selection::default()
|
||||
&& let Some(sh) = self.wb.sheet(i)
|
||||
{
|
||||
self.selection.expand_merges(sh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -314,6 +314,137 @@ fn an_array_entered_outside_the_selection_covers_only_its_cell() {
|
||||
assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep"));
|
||||
}
|
||||
|
||||
/// The value a full recalculation from scratch gives `a1` on the active sheet.
|
||||
fn fully_recalculated(s: &Session, a1: &str) -> Value {
|
||||
let mut fresh = (*s.doc().unwrap().wb).clone();
|
||||
gridcraft_calc::Calc::new().recalc_all(&mut fresh);
|
||||
fresh.active().unwrap().value(CellRef::parse(a1).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_entering_a_constant_recalculates_readers_of_the_cells_it_fills() {
|
||||
// Found by the command-sequence fuzzer (seeds 4, 1213): only the array's first cell was
|
||||
// marked changed, so formulas reading the cells it cleared kept their old values.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[5, 6, "=B1+1"]]})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "7", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
// Excel fills both cells with the constant and forms no array.
|
||||
for a in ["A1", "B1"] {
|
||||
let c = sh.cell(CellRef::parse(a).unwrap()).unwrap();
|
||||
assert_eq!(c.value, Value::number(7.0));
|
||||
assert!(c.formula.is_none());
|
||||
}
|
||||
assert_eq!(sh.value(CellRef::parse("C1").unwrap()), Value::number(8.0));
|
||||
|
||||
// The fuzzer's minimal repro on the budget sample.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "budget"})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "C5", "range": "C5:D5"})).unwrap();
|
||||
s.execute("cell.set", json!({"array": true, "cell": "C5", "input": "7"})).unwrap();
|
||||
let in_memory = s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D15").unwrap());
|
||||
assert_eq!(in_memory, fully_recalculated(&s, "D15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_entering_a_constant_grows_an_autofilter_below_it() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B3"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A4:A5"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "new", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.autofilter.as_ref().map(|f| f.range.a1()), Some("A1:B5".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_entering_a_formula_fills_every_cell_as_an_array() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "5"})).unwrap();
|
||||
for (input, want) in [("=1", 1.0), ("=A2", 5.0)] {
|
||||
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": input, "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
for a in ["A1", "B1"] {
|
||||
assert_eq!(sh.value(CellRef::parse(a).unwrap()), Value::number(want), "{input} {a}");
|
||||
}
|
||||
let f = sh.cell(CellRef::parse("A1").unwrap()).and_then(|c| c.formula.clone()).unwrap();
|
||||
assert_eq!(f.array, Some(RangeRef::parse("A1:B1").unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readers_of_an_empty_array_result_cell_see_its_result() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=B1+1"})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "=5", "array": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D1").unwrap()), Value::number(6.0));
|
||||
assert_eq!(fully_recalculated(&s, "D1"), Value::number(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_column_constant_fills_its_whole_area() {
|
||||
// The loop stopped after a million addresses, so cells further down the column kept
|
||||
// their old content (and their readers weren't recalculated).
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "D1", "range": "D:D"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "1", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::number(1.0));
|
||||
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(2.0));
|
||||
assert_eq!(fully_recalculated(&s, "F1"), Value::number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_more_than_a_million_cells_recalculates_readers_of_all_of_them() {
|
||||
// Clear marked only the first million addresses of the range as changed, so formulas
|
||||
// reading a cleared cell further down kept its old value.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
|
||||
s.execute("edit.clearContents", json!({"range": "D:D"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::Empty);
|
||||
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_spill_recalculates_readers_of_its_spilled_cells() {
|
||||
// Clear marks only the cells the sheet holds; a spill's other cells go with its anchor.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(5)"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": "=A3+1"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(4.0));
|
||||
s.execute("edit.clearContents", json!({"range": "A1:A5"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(1.0));
|
||||
assert_eq!(fully_recalculated(&s, "C1"), Value::number(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readers_of_an_array_formulas_cells_see_its_results() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B2", "values": [[1], [2]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C3", "input": "100"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E1", "input": "=C3+C4+1"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "C2:C4"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C2", "input": "=B2:B3*2", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("E1").unwrap()), fully_recalculated(&s, "E1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcards() {
|
||||
assert!(wildcard("hello", "h*o"));
|
||||
@@ -475,6 +606,39 @@ fn cut_paste_that_overflows_the_grid_moves_nothing() {
|
||||
assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transposed_paste_turns_the_formula_with_the_cell_that_carries_it() {
|
||||
// #2450: the values moved but the formula kept the offset it had in the source column,
|
||||
// so it read the cell above instead of the cell to its left.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A3", "input": "2025-10-31"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "=A3+1"})).unwrap();
|
||||
s.execute("edit.copy", json!({"range": "A3:A4"})).unwrap();
|
||||
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C3"})).unwrap();
|
||||
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
|
||||
let date = get(&mut s, "C3")["value"].as_f64().expect("the date pastes as its serial");
|
||||
assert_eq!(date, get(&mut s, "A3")["value"].as_f64().unwrap());
|
||||
assert_eq!(get(&mut s, "D3")["formula"], "=C3+1", "the formula reads the cell to its left, as Excel's does");
|
||||
assert_eq!(get(&mut s, "D3")["value"].as_f64().unwrap(), date + 1.0, "and shows the day after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transposed_paste_turns_every_kind_of_reference_the_way_excel_does() {
|
||||
// Observed from Excel 16: relative parts turn a quarter turn, a reference pinned with $
|
||||
// is left standing, and a whole column comes back as a range open to the sheet's edge.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["=B1+1"], ["=$B$1"], ["=SUM(B1:C3)"], ["=SUM(B:D)"]]})).unwrap();
|
||||
s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap();
|
||||
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C10"})).unwrap();
|
||||
let formula = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["formula"].clone();
|
||||
assert_eq!(formula(&mut s, "C10"), "=C11+1");
|
||||
assert_eq!(formula(&mut s, "D10"), "=$B$1");
|
||||
assert_eq!(formula(&mut s, "E10"), "=SUM(C11:E12)");
|
||||
assert_eq!(formula(&mut s, "F10"), "=SUM($C11:$XFD13)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_and_drop_asks_before_replacing_data() {
|
||||
// #3136: dragging column B's border onto column A replaced A without asking.
|
||||
|
||||
@@ -69,8 +69,11 @@ pub(super) fn add_element(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Ok(());
|
||||
}
|
||||
let t = trendline_param(p)?;
|
||||
// Every series' kind in one pass: a combo series' kind looks back for its group's
|
||||
// first series, so asking per series is quadratic in a chart with many.
|
||||
let kinds = c.series_kinds();
|
||||
let eligible: Vec<usize> =
|
||||
targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect();
|
||||
targets.into_iter().filter(|i| kinds.get(*i).is_some_and(|k| gridcraft_chart::supports_trendline(*k))).collect();
|
||||
if eligible.is_empty() {
|
||||
return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series"));
|
||||
}
|
||||
|
||||
@@ -130,6 +130,13 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
None => crate::io::save_bytes(wb, &path)?,
|
||||
};
|
||||
crate::io::write_file(&path, &bytes)?;
|
||||
// Only a field the user was not told about yet raises the notice: a known path is no proof,
|
||||
// since a Distinct Count added after an earlier save is still unreported.
|
||||
let distinct = distinct_count_fields(wb);
|
||||
let distinct_notice = kind == Some(crate::io::FileKind::Xlsx) && distinct.iter().any(|f| !d.distinct_disclosed.contains(f));
|
||||
if kind == Some(crate::io::FileKind::Xlsx) {
|
||||
d.distinct_disclosed = distinct;
|
||||
}
|
||||
// Only a full-fidelity format clears the dirty flag and becomes the document's file.
|
||||
if matches!(kind, Some(crate::io::FileKind::Xlsx | crate::io::FileKind::Json)) {
|
||||
// The new file is the workbook's own now, so `CELL("filename")` reports it (#1489). Set
|
||||
@@ -142,9 +149,31 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.saved = d.wb.clone();
|
||||
d.path = Some(path.clone());
|
||||
}
|
||||
if distinct_notice {
|
||||
s.ui_requests.push(crate::UiRequest::Message(DISTINCT_COUNT_NOTICE.into()));
|
||||
}
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
/// Shown when a workbook with a Distinct Count PivotTable value field is saved as .xlsx for the first time (#3336): the
|
||||
/// file stores a plain Count that only GridCraft's private marker turns back into Distinct Count.
|
||||
const DISTINCT_COUNT_NOTICE: &str = "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count.";
|
||||
|
||||
/// Every Distinct Count value field of the workbook, as (sheet, pivot, value) positions.
|
||||
fn distinct_count_fields(wb: &gridcraft_model::Workbook) -> Vec<(usize, usize, usize)> {
|
||||
let mut fields = Vec::new();
|
||||
for (si, sheet) in wb.sheets.iter().enumerate() {
|
||||
for (pi, pt) in sheet.pivots.iter().enumerate() {
|
||||
for (vi, v) in pt.values.iter().enumerate() {
|
||||
if v.func == gridcraft_model::PivotFunc::DistinctCount {
|
||||
fields.push((si, pi, vi));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
fn save_as(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if str_param(p, "path").is_none() {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("saveAs".into(), json!({})));
|
||||
@@ -159,6 +188,9 @@ fn save_bytes(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = format!("{}.{fmt}", std::path::Path::new(&d.display_title()).file_stem().and_then(|x| x.to_str()).unwrap_or("Book"));
|
||||
// The file name goes into a PivotChart's link to its PivotTable.
|
||||
let bytes = crate::io::save_bytes(&d.wb, &name)?;
|
||||
if fmt == "xlsx" && !distinct_count_fields(&d.wb).is_empty() {
|
||||
s.ui_requests.push(crate::UiRequest::Message(DISTINCT_COUNT_NOTICE.into()));
|
||||
}
|
||||
Ok(json!({"name": name, "base64": crate::io::base64_encode(&bytes), "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
|
||||
@@ -870,6 +870,33 @@ mod tests {
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00");
|
||||
}
|
||||
|
||||
/// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them.
|
||||
#[test]
|
||||
fn format_cells_sets_outlined_letters() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": true}}})).unwrap();
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], true);
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": false}}})).unwrap();
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], false);
|
||||
}
|
||||
|
||||
/// The Format Cells dialog sends the active cell's whole style to every selected cell, so a
|
||||
/// non-outlined active cell must clear outline on the others, as it does bold.
|
||||
#[test]
|
||||
fn format_cells_whole_style_clears_outline_on_the_selection() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "plain"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": "hollow"})).unwrap();
|
||||
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"outline": true, "bold": true}}})).unwrap();
|
||||
let style = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"].clone();
|
||||
s.execute("home.formatCells", json!({"range": "A1:B1", "style": style})).unwrap();
|
||||
let font = s.execute("cell.get", json!({"cell": "B1"})).unwrap()["style"]["font"].clone();
|
||||
assert_eq!((font["bold"].clone(), font["outline"].clone()), (json!(false), json!(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_vowel_and_direction_marks_add_no_width() {
|
||||
let plain = approx_text_width("محمد يدرس في المدرسة", 11.0, false);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Formulas tab: AutoSum, Insert Function, names, auditing, calculation.
|
||||
|
||||
use gridcraft_core::{CellError, CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{CalcMode, Cell, DefinedName, Formula, Workbook};
|
||||
use gridcraft_model::{CalcMode, Cell, DefinedName, Workbook};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{
|
||||
@@ -408,10 +408,12 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
edit(s, |cx| {
|
||||
if let Some((old_name, old_scope)) = &old {
|
||||
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope));
|
||||
// Formulas are renamed while the old name is still defined, so a chart series named
|
||||
// by it is still read as a reference.
|
||||
if !old_name.eq_ignore_ascii_case(&name) {
|
||||
rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name);
|
||||
rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name)?;
|
||||
}
|
||||
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope));
|
||||
}
|
||||
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && n.scope == scope));
|
||||
cx.wb.names.push(DefinedName { name: name.clone(), scope, formula: refers.clone(), comment: comment.clone(), hidden: false });
|
||||
@@ -420,49 +422,124 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Formulas that use a renamed name follow it: cell formulas and other names' definitions, on
|
||||
/// References to a renamed name follow it: every one the workbook holds
|
||||
/// ([`gridcraft_model::Workbook::rewrite_references`]) and Python cells' `xl()` references, on
|
||||
/// the sheets where `old` resolves to the renamed name (its own sheet for a sheet-scoped name;
|
||||
/// every sheet without a same-named sheet-level name for a workbook-level one).
|
||||
fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option<usize>, new: &str) {
|
||||
fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option<usize>, new: &str) -> Result<()> {
|
||||
let shadowed: Vec<usize> = wb.names.iter().filter(|n| n.name.eq_ignore_ascii_case(old)).filter_map(|n| n.scope).collect();
|
||||
let applies = |sheet: usize| match old_scope {
|
||||
Some(s) => s == sheet,
|
||||
None => !shadowed.contains(&sheet),
|
||||
};
|
||||
// The renamed expression, or `None` when the name doesn't occur in it.
|
||||
// Set when an occurrence would be captured by a LET or LAMBDA local of the new name.
|
||||
let captured = std::cell::Cell::new(false);
|
||||
let rename = |e: gridcraft_formula::Expr| {
|
||||
let mut hit = false;
|
||||
let out = e.map(&mut |x| match x {
|
||||
gridcraft_formula::Expr::Name(n) if n.eq_ignore_ascii_case(old) => {
|
||||
hit = true;
|
||||
gridcraft_formula::Expr::Name(new.to_string())
|
||||
}
|
||||
o => o,
|
||||
});
|
||||
hit.then_some(out)
|
||||
let mut bound = Vec::new();
|
||||
rename_free_name(e, old, new, &mut bound, &captured, 0)
|
||||
};
|
||||
for i in 0..wb.sheets.len() {
|
||||
if !applies(i) {
|
||||
continue;
|
||||
}
|
||||
let Some(sh) = wb.sheet_mut(i) else { continue };
|
||||
let formulas: Vec<(CellRef, std::sync::Arc<Formula>)> = sh.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect();
|
||||
for (c, f) in formulas {
|
||||
let Some(e) = f.expr().and_then(rename) else { continue };
|
||||
let mut nf = Formula::from_expr(e);
|
||||
nf.array = f.array;
|
||||
nf.dynamic = f.dynamic;
|
||||
if let Some(cell) = sh.cells.get_mut(c) {
|
||||
cell.formula = Some(std::sync::Arc::new(nf));
|
||||
}
|
||||
}
|
||||
// Every reference held where the renamed name is the one meant: on its sheet (or, for a
|
||||
// workbook name, every sheet without one of its own), and in workbook names.
|
||||
wb.rewrite_references(&|host, e| if host.sheet.is_none_or(applies) { rename(e) } else { e });
|
||||
// Python cells' `xl("…")` references too.
|
||||
let sheet_of: std::collections::HashMap<String, usize> = wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
crate::cmd::edit::rewrite_python_refs(wb, &|host, e| {
|
||||
if sheet_of.get(&host.to_ascii_lowercase()).copied().is_none_or(applies) { rename(e) } else { e }
|
||||
})?;
|
||||
if captured.get() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"The name can't be changed to {new}: a LET or LAMBDA in a formula that uses it already has a local name {new}."
|
||||
)));
|
||||
}
|
||||
for n in wb.names.iter_mut() {
|
||||
if n.scope.is_none_or(applies)
|
||||
&& let Some(e) = gridcraft_formula::parse_name(&n.formula).ok().and_then(rename)
|
||||
{
|
||||
n.formula = gridcraft_formula::print(&e);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `e` with every free occurrence of the name `old` renamed to `new`. A LET or LAMBDA local is not
|
||||
/// the defined name, so its own occurrences (of `old`) are left alone, and a free occurrence
|
||||
/// inside the scope of a local named `new` would be captured by it: that sets `captured`. `bound`
|
||||
/// holds the locals in scope. Nesting deeper than any formula the parser accepts is left as it is.
|
||||
fn rename_free_name(
|
||||
e: gridcraft_formula::Expr,
|
||||
old: &str,
|
||||
new: &str,
|
||||
bound: &mut Vec<String>,
|
||||
captured: &std::cell::Cell<bool>,
|
||||
depth: usize,
|
||||
) -> gridcraft_formula::Expr {
|
||||
use gridcraft_formula::Expr;
|
||||
const MAX_DEPTH: usize = 512;
|
||||
if depth > MAX_DEPTH {
|
||||
return e;
|
||||
}
|
||||
let is_bound = |bound: &[String], n: &str| bound.iter().any(|b| b.eq_ignore_ascii_case(n));
|
||||
let walk = |e: Expr, bound: &mut Vec<String>| rename_free_name(e, old, new, bound, captured, depth + 1);
|
||||
match e {
|
||||
Expr::Name(n) if n.eq_ignore_ascii_case(old) && !is_bound(bound, &n) => {
|
||||
if is_bound(bound, new) {
|
||||
captured.set(true);
|
||||
}
|
||||
Expr::Name(new.to_string())
|
||||
}
|
||||
Expr::Call(name, args) if name == "LET" && args.len() >= 3 && !args.len().is_multiple_of(2) => {
|
||||
let saved = bound.len();
|
||||
let mut args = args;
|
||||
// The arguments are odd in number: pairs of a declaration and its value, then the body.
|
||||
let body = args.pop();
|
||||
let mut out = Vec::with_capacity(args.len() + 1);
|
||||
let mut pairs = args.into_iter();
|
||||
while let (Some(declaration), Some(value)) = (pairs.next(), pairs.next()) {
|
||||
// A value comes before its own local is in scope; the declaration is the local's
|
||||
// own name, never the defined name.
|
||||
let value = walk(value, bound);
|
||||
if let Expr::Name(n) = &declaration {
|
||||
bound.push(n.clone());
|
||||
}
|
||||
out.push(declaration);
|
||||
out.push(value);
|
||||
}
|
||||
out.extend(body.map(|b| walk(b, bound)));
|
||||
bound.truncate(saved);
|
||||
Expr::Call(name, out)
|
||||
}
|
||||
Expr::Call(name, args) if name == "LAMBDA" => {
|
||||
let saved = bound.len();
|
||||
let last = args.len().saturating_sub(1);
|
||||
let mut out = Vec::with_capacity(args.len());
|
||||
for (i, arg) in args.into_iter().enumerate() {
|
||||
if i == last {
|
||||
out.push(walk(arg, bound));
|
||||
} else {
|
||||
if let Expr::Name(n) = &arg {
|
||||
bound.push(n.clone());
|
||||
}
|
||||
out.push(arg);
|
||||
}
|
||||
}
|
||||
bound.truncate(saved);
|
||||
Expr::Call(name, out)
|
||||
}
|
||||
Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| walk(a, bound)).collect()),
|
||||
Expr::Invoke(callee, args) => Expr::Invoke(Box::new(walk(*callee, bound)), args.into_iter().map(|a| walk(a, bound)).collect()),
|
||||
Expr::Array(rows) => Expr::Array(rows.into_iter().map(|r| r.into_iter().map(|x| walk(x, bound)).collect()).collect()),
|
||||
Expr::Unary(op, x) => Expr::Unary(op, Box::new(walk(*x, bound))),
|
||||
Expr::Binary(op, a, b) => {
|
||||
// A long operator chain is unwound, not recursed into once per operand (as
|
||||
// `Expr::map` does), so its length doesn't count toward the nesting limit.
|
||||
let mut spine = vec![(op, b)];
|
||||
let mut node = *a;
|
||||
while let Expr::Binary(op, a, b) = node {
|
||||
spine.push((op, b));
|
||||
node = *a;
|
||||
}
|
||||
let mut acc = walk(node, bound);
|
||||
while let Some((op, b)) = spine.pop() {
|
||||
let b = walk(*b, bound);
|
||||
acc = Expr::Binary(op, Box::new(acc), Box::new(b));
|
||||
}
|
||||
acc
|
||||
}
|
||||
Expr::Paren(x) => Expr::Paren(Box::new(walk(*x, bound))),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -337,6 +337,74 @@ mod tests {
|
||||
assert_eq!(serde_json::from_value::<Chart>(json).unwrap().data_table, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_type_change_drops_series_kinds_it_does_not_draw() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "A", "B"], ["Q1", 10, 1], ["Q2", 20, 2]]})).unwrap();
|
||||
s.execute("insert.chart", json!({"range": "A1:C3", "type": "combo"})).unwrap();
|
||||
let chart = |s: &Session| s.active().unwrap().wb.active().unwrap().charts[0].clone();
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
let active = wb.active_sheet();
|
||||
if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) {
|
||||
c.series[0].kind = Some(ChartKind::Area);
|
||||
c.series[1].kind = Some(ChartKind::LineMarkers);
|
||||
}
|
||||
// A new type applies to every series: neither the area nor the markers stay.
|
||||
s.execute("chart.set", json!({"type": "line"})).unwrap();
|
||||
let c = chart(&s);
|
||||
assert_eq!(c.series.iter().map(|x| x.kind).collect::<Vec<_>>(), vec![None, None]);
|
||||
assert_eq!((c.series_kind(0), c.series_kind(1)), (ChartKind::Line, ChartKind::Line));
|
||||
// Setting the type a chart already has keeps a series' own markers (a file's).
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) {
|
||||
c.series[1].kind = Some(ChartKind::LineMarkers);
|
||||
}
|
||||
s.execute("chart.set", json!({"type": "line", "subtype": ""})).unwrap();
|
||||
assert_eq!(chart(&s).series_kinds(), vec![ChartKind::Line, ChartKind::LineMarkers]);
|
||||
// Trendlines go by the kind each series is drawn as.
|
||||
s.execute("chart.set", json!({"type": "pie"})).unwrap();
|
||||
assert!(s.execute("chart.addElement", json!({"element": "trendline"})).is_err());
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(chart(&s).series[1].kind, Some(ChartKind::LineMarkers));
|
||||
}
|
||||
|
||||
/// Adding a trendline to every series of a combo chart works out the series' kinds in one
|
||||
/// pass, however many series it holds (a stored chart isn't held to the renderer's limit):
|
||||
/// eight times the series is about eight times the work, not sixty-four.
|
||||
#[test]
|
||||
fn trendlines_for_every_series_are_checked_in_linear_time() {
|
||||
let visits = |n: usize| {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "A"], ["Q1", 10], ["Q2", 20]]})).unwrap();
|
||||
s.execute("insert.chart", json!({"range": "A1:B3", "type": "combo"})).unwrap();
|
||||
// Line series, then as many column series: asked one at a time, each column series
|
||||
// looks back past every line series for the first column series of its group.
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
let active = wb.active_sheet();
|
||||
if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) {
|
||||
let one = c.series[0].clone();
|
||||
c.series = (0..2 * n)
|
||||
.map(|i| {
|
||||
let mut se = one.clone();
|
||||
se.kind = Some(if i < n { ChartKind::Line } else { ChartKind::ColumnClustered });
|
||||
se
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
gridcraft_model::features::work::take_series_visits();
|
||||
s.execute("chart.addElement", json!({"element": "trendline"})).unwrap();
|
||||
let visits = gridcraft_model::features::work::take_series_visits();
|
||||
let c = s.active().unwrap().wb.active().unwrap().charts[0].clone();
|
||||
assert!(c.series.iter().all(|se| se.trendlines.len() == 1));
|
||||
visits
|
||||
};
|
||||
let (small, large) = (visits(200), visits(1_600));
|
||||
assert!(small >= 400, "every series' kind is worked out: {small}");
|
||||
assert!(large < 16 * small, "eight times the series took {large} visits against {small}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_data_table_refuses_unsupported_types_without_changing_history() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -334,7 +334,15 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) };
|
||||
if let Some(t) = str_param(p, "type") {
|
||||
c.kind = chart_kind(t, str_param(p, "subtype").unwrap_or(""));
|
||||
let kind = chart_kind(t, str_param(p, "subtype").unwrap_or(""));
|
||||
// A new type (other than a combo) applies to every series, as choosing it did before
|
||||
// series kept their own: their markers or lines from a file go with the old type.
|
||||
if kind != c.kind && kind != ChartKind::Combo {
|
||||
for series in &mut c.series {
|
||||
series.kind = None;
|
||||
}
|
||||
}
|
||||
c.kind = kind;
|
||||
if !c.supports_data_table() {
|
||||
c.data_table = None;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Anchor, BorderLine, BorderStyle, Borders, CellRef, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result,
|
||||
Session, Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges,
|
||||
target_sheet, u32_param,
|
||||
Anchor, BorderLine, BorderStyle, Borders, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result, Session,
|
||||
Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges, target_sheet,
|
||||
u32_param,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -282,7 +282,9 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// The relative formulas are written for the top-left cell: when it goes, they're
|
||||
// rewritten for the new one, so the areas left keep reading the same cells.
|
||||
if let (Some(from), Some(to)) = (before, RangeRef::top_left(&cf.ranges)) {
|
||||
rebase_cf_formulas(&mut cf.rule, from, to);
|
||||
for f in cf.rule.relative_formulas_mut() {
|
||||
*f = crate::cmd::data::move_rule_formula(f, from, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
sh.cond_formats.retain(|c| !c.ranges.is_empty());
|
||||
@@ -291,19 +293,6 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the relative references of a rule's per-cell formulas written for `from` to `to`.
|
||||
fn rebase_cf_formulas(rule: &mut CfRule, from: CellRef, to: CellRef) {
|
||||
let mv = |f: &str| crate::cmd::data::move_rule_formula(f, from, to);
|
||||
match rule {
|
||||
CfRule::CellIs { a, b, .. } => {
|
||||
*a = mv(a);
|
||||
*b = b.as_deref().map(mv);
|
||||
}
|
||||
CfRule::Expression { formula, .. } => *formula = mv(formula),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
|
||||
|
||||
@@ -293,28 +293,39 @@ pub(super) fn table_rename(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let Some(t) = cx.sheet_mut(si)?.tables.get_mut(ti) {
|
||||
t.name = name.clone();
|
||||
}
|
||||
// Structured references follow the rename.
|
||||
// Every reference to the table follows the rename. A bare name that is also a defined
|
||||
// name where it is held resolves to the defined name, so it is not the table; in a
|
||||
// workbook name, that is a workbook-level defined name.
|
||||
let shadowed: Vec<bool> = (0..cx.wb.sheets.len()).map(|i| cx.wb.name(&old, i).is_some()).collect();
|
||||
let shadowed_in_book = cx.wb.names.iter().any(|n| n.scope.is_none() && n.name.eq_ignore_ascii_case(&old));
|
||||
let sheet_of: std::collections::HashMap<String, usize> =
|
||||
cx.wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
let rename = |sheet: Option<usize>, e: gridcraft_formula::Expr| {
|
||||
let shadow = sheet.map_or(shadowed_in_book, |i| shadowed.get(i).copied().unwrap_or(false));
|
||||
e.map(&mut |x| match x {
|
||||
gridcraft_formula::Expr::Struct(mut st) if st.table.eq_ignore_ascii_case(&old) => {
|
||||
st.table = name.clone();
|
||||
gridcraft_formula::Expr::Struct(st)
|
||||
}
|
||||
gridcraft_formula::Expr::Name(n) if !shadow && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()),
|
||||
o => o,
|
||||
})
|
||||
};
|
||||
cx.wb.rewrite_references(&|host, e| rename(host.sheet, e));
|
||||
// A bare PivotTable source binds to a table before a defined name (`pivot::resolve_source`),
|
||||
// so a defined name with the old name doesn't shadow it: it follows the rename regardless.
|
||||
for i in 0..cx.wb.sheets.len() {
|
||||
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
cx.wb.sheets.get(i).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default();
|
||||
// A bare name that is also a defined name resolves to the defined name, so it is not the table.
|
||||
let shadowed = cx.wb.name(&old, i).is_some();
|
||||
let Some(sh) = cx.wb.sheet_mut(i) else { continue };
|
||||
for (c, f) in keys {
|
||||
let Some(e) = f.expr() else { continue };
|
||||
let ne = e.map(&mut |x| match x {
|
||||
gridcraft_formula::Expr::Struct(mut st) if st.table.eq_ignore_ascii_case(&old) => {
|
||||
st.table = name.clone();
|
||||
gridcraft_formula::Expr::Struct(st)
|
||||
}
|
||||
gridcraft_formula::Expr::Name(n) if !shadowed && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()),
|
||||
o => o,
|
||||
});
|
||||
if let Some(cell) = sh.cells.get_mut(c) {
|
||||
cell.formula = Some(std::sync::Arc::new(Formula::from_expr(ne)));
|
||||
let names_old = |src: &str| src.trim().trim_start_matches('=').trim().eq_ignore_ascii_case(&old);
|
||||
if !cx.wb.sheet(i).is_some_and(|sh| sh.pivots.iter().any(|pt| names_old(&pt.source))) {
|
||||
continue;
|
||||
}
|
||||
for pt in &mut cx.sheet_mut(i)?.pivots {
|
||||
if names_old(&pt.source) {
|
||||
pt.source = name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|host, e| rename(sheet_of.get(&host.to_ascii_lowercase()).copied(), e))?;
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})
|
||||
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Field",
|
||||
[],
|
||||
None,
|
||||
"{pivot?, field, area: rows|columns|values|filters, func?: sum|count|average|max|min|product|countNumbers|stdDev|stdDevP|var|varP, name?, position?: index, replace?}",
|
||||
"{pivot?, field, area: rows|columns|values|filters, func?: sum|count|average|max|min|product|countNumbers|distinctCount|stdDev|stdDevP|var|varP, name?, position?: index, replace?}",
|
||||
has_doc,
|
||||
add_field
|
||||
),
|
||||
|
||||
@@ -106,6 +106,10 @@ fn auto_name(f: PivotFunc, field: &str) -> String {
|
||||
format!("{} of {field}", pv::func_caption(f))
|
||||
}
|
||||
|
||||
/// A calculated field is evaluated on the report's totals, not per source record, so there is
|
||||
/// no set of values to count the distinct members of.
|
||||
const NO_CALC_DISTINCT: &str = "A calculated field can't use Distinct Count.";
|
||||
|
||||
/// Adds `field` to an area (moving it out of the other axis areas).
|
||||
pub(super) struct AreaPlacement<'a> {
|
||||
pub cmd: &'a str,
|
||||
@@ -140,6 +144,9 @@ pub(super) fn add_to_area(pt: &mut PivotTable, src: &pv::Source, placement: Area
|
||||
}
|
||||
let numeric = is_calc || src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false);
|
||||
let f = func.unwrap_or(if numeric { PivotFunc::Sum } else { PivotFunc::Count });
|
||||
if is_calc && f == PivotFunc::DistinctCount {
|
||||
return Err(other(NO_CALC_DISTINCT));
|
||||
}
|
||||
let base = match name {
|
||||
Some(n) if !n.trim().is_empty() => {
|
||||
if src.col(n).is_some() {
|
||||
@@ -506,6 +513,9 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let cur = pt.values.get(i).cloned().ok_or_else(|| bad(C, "no value field at that index"))?;
|
||||
let mut v = cur.clone();
|
||||
if let Some(f) = func {
|
||||
if f == PivotFunc::DistinctCount && src.col(&cur.source_col).is_none() && calc_field(pt, &cur.source_col).is_some() {
|
||||
return Err(other(NO_CALC_DISTINCT));
|
||||
}
|
||||
v.func = f;
|
||||
// An automatic caption follows the function. Count Numbers was captioned "Count
|
||||
// Numbers of …" before it took Excel's "Count of …", and saved workbooks still carry it.
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(super) fn func_param(v: Option<&str>) -> Option<PivotFunc> {
|
||||
"min" => PivotFunc::Min,
|
||||
"product" => PivotFunc::Product,
|
||||
"countnumbers" | "countnums" | "count numbers" => PivotFunc::CountNumbers,
|
||||
"distinctcount" | "distinct count" | "distinct" => PivotFunc::DistinctCount,
|
||||
"stddev" => PivotFunc::StdDev,
|
||||
"stddevp" => PivotFunc::StdDevP,
|
||||
"var" => PivotFunc::Var,
|
||||
@@ -37,6 +38,7 @@ pub(super) fn func_name(f: PivotFunc) -> &'static str {
|
||||
PivotFunc::Min => "min",
|
||||
PivotFunc::Product => "product",
|
||||
PivotFunc::CountNumbers => "countNumbers",
|
||||
PivotFunc::DistinctCount => "distinctCount",
|
||||
PivotFunc::StdDev => "stdDev",
|
||||
PivotFunc::StdDevP => "stdDevP",
|
||||
PivotFunc::Var => "var",
|
||||
|
||||
@@ -571,6 +571,25 @@ fn pivot_chart_errors() {
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().charts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calculated_field_cannot_use_distinct_count() {
|
||||
// It is computed from the report's totals, so there are no per-record values to count.
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.calculatedField", json!({"name": "Price", "formula": "Sales / Units"})).unwrap();
|
||||
assert_eq!(text(&s, "C3"), "Sum of Price");
|
||||
let before = s.doc().unwrap().wb.clone();
|
||||
let set = s.execute("pivot.valueSettings", json!({"field": "Price", "func": "distinctCount"}));
|
||||
assert!(set.unwrap_err().to_string().contains("Distinct Count"));
|
||||
assert_eq!(s.doc().unwrap().wb, before, "a rejected change leaves the workbook as it was");
|
||||
s.execute("pivot.removeField", json!({"field": "Price", "area": "values"})).unwrap();
|
||||
let add = s.execute("pivot.addField", json!({"field": "Price", "area": "values", "func": "distinctCount"}));
|
||||
assert!(add.unwrap_err().to_string().contains("Distinct Count"));
|
||||
// A source field still takes it, and a calculated field keeps its other functions.
|
||||
s.execute("pivot.addField", json!({"field": "Product", "area": "values", "func": "distinctCount"})).unwrap();
|
||||
s.execute("pivot.addField", json!({"field": "Price", "area": "values", "func": "sum"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculated_field_on_sums() {
|
||||
let mut s = sales();
|
||||
@@ -1428,3 +1447,139 @@ fn legacy_count_numbers_caption_follows_the_function() {
|
||||
assert_eq!(text(&s, "E3"), after, "{legacy}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_count_counts_each_different_value_once_per_cell_and_in_the_totals() {
|
||||
// #3336: Alice, Bob, Alice, Charlie is 3 distinct customers, where Count says 4. Case does not
|
||||
// make a name different, and an empty cell is not a value.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = json!([
|
||||
["Region", "Customer"],
|
||||
["East", "Alice"],
|
||||
["East", "Bob"],
|
||||
["East", "alice"],
|
||||
["East", null],
|
||||
["West", "Alice"],
|
||||
["West", "Charlie"]
|
||||
]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let make = json!({"source": "Sheet1!$A$1:$B$7", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]});
|
||||
s.execute("insert.pivotTable", make).unwrap();
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "count"})).unwrap();
|
||||
let counts: Vec<Value> = ["E4", "E5", "E6"].iter().map(|a| val(&s, a)).collect();
|
||||
assert_eq!(counts, [3.0, 2.0, 5.0].map(Value::Number), "Count counts every non-empty cell");
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
assert_eq!(text(&s, "E3"), "Distinct Count of Customer");
|
||||
let distinct: Vec<Value> = ["E4", "E5", "E6"].iter().map(|a| val(&s, a)).collect();
|
||||
assert_eq!(distinct, [2.0, 2.0, 3.0].map(Value::Number), "East has Alice and Bob, West Alice and Charlie, 3 in all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_count_survives_an_xlsx_round_trip_and_a_refresh() {
|
||||
// #3385: saving wrote Distinct Count as Count, so Alice, Bob, Alice became 3 after reopening
|
||||
// and refreshing. The sheet keeps the computed distinct counts for other readers too.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = json!([["Region", "Customer"], ["East", "Alice"], ["East", "Bob"], ["East", "alice"], ["West", "Alice"], ["West", "Charlie"]]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let make = json!({"source": "Sheet1!$A$1:$B$6", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]});
|
||||
s.execute("insert.pivotTable", make).unwrap();
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
let cells = ["E4", "E5", "E6"];
|
||||
let expected = [2.0, 2.0, 3.0].map(Value::Number);
|
||||
assert_eq!(cells.map(|a| val(&s, a)), expected);
|
||||
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap();
|
||||
|
||||
// The written sheet holds the distinct counts, and the cache doesn't ask for a refresh on open.
|
||||
let (written, _) = gridcraft_xlsx::read_xlsx(&bytes).unwrap();
|
||||
let sheet = written.sheet(0).unwrap();
|
||||
assert_eq!(cells.map(|a| sheet.value(CellRef::parse(a).unwrap())), expected);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut cache = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("xl/pivotCache/pivotCacheDefinition1.xml").unwrap(), &mut cache).unwrap();
|
||||
assert!(!cache.contains("refreshOnLoad"), "{cache}");
|
||||
|
||||
let mut back = Session::new();
|
||||
back.execute("file.open", json!({"name": "book.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
|
||||
assert_eq!(pt(&back).values[0].func, gridcraft_model::PivotFunc::DistinctCount);
|
||||
back.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
|
||||
assert_eq!(text(&back, "E3"), "Distinct Count of Customer");
|
||||
assert_eq!(cells.map(|a| val(&back, a)), expected, "a refresh after reopening still counts distinct customers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_distinct_count_pivot_as_xlsx_says_only_gridcraft_reads_it() {
|
||||
// #3385: the file stores a plain Count; Excel's Refresh turns it into a count, so the user is told.
|
||||
let notices =
|
||||
|s: &mut Session| s.take_ui_requests().iter().filter(|r| matches!(r, crate::UiRequest::Message(m) if m.contains("Distinct Count"))).count();
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-distinct-notice-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = json!([["Region", "Customer"], ["East", "Alice"], ["East", "Bob"], ["West", "Alice"]]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let make = json!({"source": "Sheet1!$A$1:$B$4", "destination": "Sheet1!D3", "rows": ["Region"], "values": ["Customer"]});
|
||||
s.execute("insert.pivotTable", make).unwrap();
|
||||
s.take_ui_requests();
|
||||
|
||||
s.execute("file.saveAs", json!({"path": dir.join("plain.xlsx")})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "a plain Count is saved as it is");
|
||||
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
s.execute("file.saveBytes", json!({"format": "csv"})).unwrap();
|
||||
s.execute("file.saveAs", json!({"path": dir.join("book.csv")})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "only an .xlsx file stores the marker");
|
||||
s.execute("file.saveAs", json!({"path": dir.join("book.xlsx")})).unwrap();
|
||||
assert_eq!(notices(&mut s), 1);
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "saving the same file again does not repeat it");
|
||||
// The path is known now, but a Distinct Count added later was never disclosed.
|
||||
s.execute("insert.pivotTable", json!({"source": "Sheet1!$A$1:$B$4", "destination": "Sheet1!H3", "rows": ["Region"], "values": ["Customer"]}))
|
||||
.unwrap();
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "a plain Count adds nothing to disclose");
|
||||
s.execute("pivot.valueSettings", json!({"index": 0, "func": "distinctCount"})).unwrap();
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 1, "a new Distinct Count field is disclosed on an ordinary Save to the same path");
|
||||
s.execute("file.save", json!({})).unwrap();
|
||||
assert_eq!(notices(&mut s), 0, "and only once");
|
||||
s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
assert_eq!(notices(&mut s), 1, "a download is an export too");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A defined name with a table's name doesn't stop a PivotTable's table source following a rename
|
||||
/// of the table: a bare source binds to the table first.
|
||||
#[test]
|
||||
fn a_table_rename_moves_a_pivot_source_a_defined_name_shadows() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.table", json!({"range": "A1:E13"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap();
|
||||
assert_eq!(pt(&s).source, "Table1");
|
||||
s.execute("formulas.defineName", json!({"name": "Table1", "refersTo": "=Sheet1!$A$1:$B$3"})).unwrap();
|
||||
s.execute("table.rename", json!({"table": "Table1", "name": "Data"})).unwrap();
|
||||
assert_eq!(pt(&s).source, "Data");
|
||||
s.execute("pivot.refresh", json!({})).unwrap();
|
||||
let gt = find_row(&s, "Grand Total").unwrap();
|
||||
assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0));
|
||||
}
|
||||
|
||||
/// A PivotTable source that is a table's name reads the table before a defined name of that name,
|
||||
/// so renaming the defined name leaves it on the table; a source that is the defined name's own
|
||||
/// follows the rename.
|
||||
#[test]
|
||||
fn renaming_a_defined_name_leaves_a_table_source_on_its_table() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.table", json!({"range": "A1:E13", "name": "Data"})).unwrap();
|
||||
s.execute("formulas.defineName", json!({"name": "Data", "refersTo": "=Sheet1!$A$1:$E$3"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap();
|
||||
assert_eq!(pt(&s).source, "Data");
|
||||
s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Data", "refersTo": "=Sheet1!$A$1:$E$3"})).unwrap();
|
||||
assert_eq!(pt(&s).source, "Data");
|
||||
s.execute("pivot.refresh", json!({})).unwrap();
|
||||
let gt = find_row(&s, "Grand Total").unwrap();
|
||||
assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! Quick Analysis › Totals: appends totals (or per-cell percentages / running totals) next to a
|
||||
//! block of numbers as ordinary formulas, in one undoable edit. The popup in the UI
|
||||
//! (`ui.quickAnalysis`) is a thin front end for this command; the control channel, CLI and MCP
|
||||
//! call it directly. The layout is GridCraft's own: aggregates go in the row below the block (or
|
||||
//! the column to its right), per-cell results in a block of the same shape next to it.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
|
||||
use gridcraft_model::{Color, NumFmt, Sparkline, SparklineKind};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, PROTECTED, Result, Session, bad, bool_param, cmd, edit, has_doc, str_param, target_range, target_sheet};
|
||||
|
||||
const CMD: &str = "analysis.addTotal";
|
||||
const SPARK: &str = "analysis.addSparklines";
|
||||
/// Most sparklines one call may add.
|
||||
const MAX_SPARKLINES: u64 = 10_000;
|
||||
/// Most cells one call may write (a per-cell block on a huge selection is refused).
|
||||
const MAX_OUTPUT_CELLS: u64 = 200_000;
|
||||
/// Largest block (after clipping to the used range) the command scans for numbers.
|
||||
const MAX_SCAN_CELLS: u64 = 5_000_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"analysis.addTotal",
|
||||
"Add Totals",
|
||||
[],
|
||||
None,
|
||||
"{function?: sum|average|count|min|max|percentTotal|runningTotal (default sum), direction?: columns|rows (default columns: one result per column, below the block; rows: one per row, right of it; percentTotal and runningTotal write a block of the same shape to the right (columns) or below (rows)), range?: \"A1:C9\" (default: the selection; limited to the used range), overwrite?: bool (else non-empty output cells are refused)} → {function, direction, output, cells}. Quick Analysis › Totals. A header row (columns) or label column (rows) is skipped; columns without numbers get no total. One undo step.",
|
||||
has_doc,
|
||||
add_total
|
||||
),
|
||||
cmd!(
|
||||
"analysis.addSparklines",
|
||||
"Add Sparklines",
|
||||
[],
|
||||
None,
|
||||
"{type?: line|column|winLoss (default line), direction?: rows|columns (default rows: one sparkline per row, in the column right of the block; columns: one per column, in the row below), markers?: bool, range?: \"A1:F9\" (default: the selection; limited to the used range), overwrite?: bool} → {output, sparklines}. Quick Analysis › Sparklines. A header row (columns) or label column (rows) is skipped; lines without numbers get none. One undo step.",
|
||||
has_doc,
|
||||
add_sparklines
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Func {
|
||||
Aggregate(&'static str),
|
||||
Percent,
|
||||
Running,
|
||||
}
|
||||
|
||||
fn parse_func(name: &str) -> Result<Func> {
|
||||
Ok(match name.to_ascii_lowercase().replace(['_', '-', ' ', '%'], "").as_str() {
|
||||
"sum" => Func::Aggregate("SUM"),
|
||||
"average" | "avg" => Func::Aggregate("AVERAGE"),
|
||||
"count" => Func::Aggregate("COUNT"),
|
||||
"min" => Func::Aggregate("MIN"),
|
||||
"max" => Func::Aggregate("MAX"),
|
||||
"percenttotal" | "percent" => Func::Percent,
|
||||
"runningtotal" | "running" => Func::Running,
|
||||
_ => return Err(bad(CMD, format!("unknown function `{name}` (use sum, average, count, min, max, percentTotal or runningTotal)"))),
|
||||
})
|
||||
}
|
||||
|
||||
/// The block a Quick Analysis result is computed from.
|
||||
struct Block {
|
||||
sheet: usize,
|
||||
/// The selection clipped to the used range.
|
||||
range: RangeRef,
|
||||
/// `range` without its header row (columns) or label column (rows).
|
||||
data: RangeRef,
|
||||
/// The columns (or, `by_rows`, the rows) of `data` that hold numbers.
|
||||
lines: BTreeSet<u32>,
|
||||
by_rows: bool,
|
||||
/// Last row / column the results must stay clear of: the selection's own far edge, so a
|
||||
/// selection reaching past the data still gets its results outside it. Whole rows or columns
|
||||
/// (reaching the sheet limit) fall back to the clipped range.
|
||||
edge: CellRef,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn cell_at(&self, line: u32, i: u32) -> CellRef {
|
||||
if self.by_rows { CellRef::new(line, i) } else { CellRef::new(i, line) }
|
||||
}
|
||||
/// First and last position along a line of `data`.
|
||||
fn span_of_line(&self) -> (u32, u32) {
|
||||
if self.by_rows { (self.data.start.col, self.data.end.col) } else { (self.data.start.row, self.data.end.row) }
|
||||
}
|
||||
fn line_range(&self, line: u32, from: u32, to: u32) -> RangeRef {
|
||||
RangeRef::new(self.cell_at(line, from), self.cell_at(line, to))
|
||||
}
|
||||
}
|
||||
|
||||
fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result<Block> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let sel = match str_param(p, "range") {
|
||||
Some(_) => target_range(s, p)?,
|
||||
None => {
|
||||
// Never guess from the current area of a multi-area selection.
|
||||
if s.doc()?.selection.ranges.len() > 1 {
|
||||
return Err(bad(cmd, "select a single contiguous range"));
|
||||
}
|
||||
s.doc()?.selection.current()
|
||||
}
|
||||
};
|
||||
if sel.is_single() {
|
||||
return Err(bad(cmd, "select at least two cells"));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
// Whole rows / columns are limited to what holds data.
|
||||
let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?;
|
||||
let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?;
|
||||
if r.count() > MAX_SCAN_CELLS {
|
||||
return Err(bad(cmd, "selection too large to analyse"));
|
||||
}
|
||||
let is_num = |c: CellRef| sh.value(c).is_number();
|
||||
let is_text = |c: CellRef| sh.value(c).is_text();
|
||||
// Header row (columns) / label column (rows): text only, with at least one entry.
|
||||
let lead: Vec<CellRef> = if by_rows {
|
||||
(r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect()
|
||||
} else {
|
||||
(r.start.col..=r.end.col).map(|c| CellRef::new(r.start.row, c)).collect()
|
||||
};
|
||||
let longer_than_one = if by_rows { r.width() > 1 } else { r.height() > 1 };
|
||||
let has_label = longer_than_one && lead.iter().any(|c| is_text(*c)) && !lead.iter().any(|c| is_num(*c));
|
||||
let data = if by_rows {
|
||||
RangeRef::new(CellRef::new(r.start.row, r.start.col + u32::from(has_label)), r.end)
|
||||
} else {
|
||||
RangeRef::new(CellRef::new(r.start.row + u32::from(has_label), r.start.col), r.end)
|
||||
};
|
||||
let mut lines: BTreeSet<u32> = BTreeSet::new();
|
||||
for (c, _) in sh.cells.iter_range(data) {
|
||||
if is_num(c) {
|
||||
lines.insert(if by_rows { c.row } else { c.col });
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other("The selection holds no numbers.".into()));
|
||||
}
|
||||
let edge = CellRef::new(
|
||||
if sel.end.row >= MAX_ROWS - 1 { r.end.row } else { sel.end.row.max(r.end.row) },
|
||||
if sel.end.col >= MAX_COLS - 1 { r.end.col } else { sel.end.col.max(r.end.col) },
|
||||
);
|
||||
Ok(Block { sheet, range: r, data, lines, by_rows, edge })
|
||||
}
|
||||
|
||||
fn add_total(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let func = parse_func(str_param(p, "function").unwrap_or("sum"))?;
|
||||
let by_rows = match str_param(p, "direction") {
|
||||
None | Some("columns") => false,
|
||||
Some("rows") => true,
|
||||
Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))),
|
||||
};
|
||||
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
|
||||
let b = block(s, p, by_rows, CMD)?;
|
||||
let (r, sheet) = (b.range, b.sheet);
|
||||
let (lo, hi) = b.span_of_line();
|
||||
let out_cells = match func {
|
||||
Func::Aggregate(_) => b.lines.len() as u64,
|
||||
_ => b.lines.len() as u64 * (u64::from(hi - lo) + 1),
|
||||
};
|
||||
if out_cells > MAX_OUTPUT_CELLS {
|
||||
return Err(bad(CMD, "selection too large for this result"));
|
||||
}
|
||||
// `$` pins a part of a reference like a hand-written formula would.
|
||||
let abs = |c: CellRef, row: bool, col: bool| {
|
||||
let a = c.a1();
|
||||
let letters: String = a.chars().take_while(|ch| ch.is_ascii_alphabetic()).collect();
|
||||
let digits = &a[letters.len()..];
|
||||
format!("{}{letters}{}{digits}", if col { "$" } else { "" }, if row { "$" } else { "" })
|
||||
};
|
||||
// (target, formula) pairs.
|
||||
let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize);
|
||||
let (height, width) = (b.edge.row - r.start.row + 1, b.edge.col - r.start.col + 1);
|
||||
for &line in &b.lines {
|
||||
match func {
|
||||
Func::Aggregate(name) => {
|
||||
let target =
|
||||
if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
|
||||
writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1())));
|
||||
}
|
||||
Func::Percent | Func::Running => {
|
||||
for i in lo..=hi {
|
||||
let src = b.cell_at(line, i);
|
||||
let target = if by_rows {
|
||||
CellRef::new(src.row.saturating_add(height), src.col)
|
||||
} else {
|
||||
CellRef::new(src.row, src.col.saturating_add(width))
|
||||
};
|
||||
let formula = if func == Func::Percent {
|
||||
// The summed block is locked on the axis the formula is filled along.
|
||||
let (a, z) = (b.cell_at(line, lo), b.cell_at(line, hi));
|
||||
format!("={}/SUM({}:{})", src.a1(), abs(a, !by_rows, by_rows), abs(z, !by_rows, by_rows))
|
||||
} else {
|
||||
format!("=SUM({}:{})", abs(b.cell_at(line, lo), !by_rows, by_rows), src.a1())
|
||||
};
|
||||
writes.push((target, formula));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Everything has to fit on the sheet and may not overwrite data.
|
||||
if writes.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
|
||||
return Err(EngineError::Other("There's no room next to the selection for the result.".into()));
|
||||
}
|
||||
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
if !overwrite && writes.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.cells.get(*t).is_some_and(|c| c.formula.is_some())) {
|
||||
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
|
||||
}
|
||||
let out = writes.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
|
||||
let percent = func == Func::Percent;
|
||||
let count = writes.len();
|
||||
edit(s, |cx| {
|
||||
for (t, f) in &writes {
|
||||
let cell = super::edit::input_to_cell(f, sheet, *t, &mut cx.wb)?.unwrap_or_default();
|
||||
cx.sheet_mut(sheet)?.set_cell(*t, cell);
|
||||
if percent {
|
||||
let cur = cx.wb.sheet(sheet).map(|sh| sh.style_id(*t)).unwrap_or_default();
|
||||
let new = cx.wb.styles.derive(cur, |st| st.num_fmt = NumFmt::new("0.0%"));
|
||||
cx.sheet_mut(sheet)?.set_style(*t, new);
|
||||
}
|
||||
cx.touch(sheet, *t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let name = match func {
|
||||
Func::Aggregate(n) => n.to_ascii_lowercase(),
|
||||
Func::Percent => "percentTotal".into(),
|
||||
Func::Running => "runningTotal".into(),
|
||||
};
|
||||
Ok(json!({"function": name, "direction": if by_rows { "rows" } else { "columns" }, "output": out.map(|o| o.a1()), "cells": count}))
|
||||
}
|
||||
|
||||
fn add_sparklines(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let by_rows = match str_param(p, "direction") {
|
||||
None | Some("rows") => true,
|
||||
Some("columns") => false,
|
||||
Some(other) => return Err(bad(SPARK, format!("direction must be rows or columns, not `{other}`"))),
|
||||
};
|
||||
let kind = match str_param(p, "type") {
|
||||
None | Some("line") => SparklineKind::Line,
|
||||
Some("column") => SparklineKind::Column,
|
||||
Some("winLoss") => SparklineKind::WinLoss,
|
||||
Some(other) => return Err(bad(SPARK, format!("type must be line, column or winLoss, not `{other}`"))),
|
||||
};
|
||||
let markers = bool_param(p, "markers").unwrap_or(false);
|
||||
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
|
||||
let b = block(s, p, by_rows, SPARK)?;
|
||||
if b.lines.len() as u64 > MAX_SPARKLINES {
|
||||
return Err(bad(SPARK, "selection too large for this result"));
|
||||
}
|
||||
let (lo, hi) = b.span_of_line();
|
||||
let sparks: Vec<(CellRef, String)> = b
|
||||
.lines
|
||||
.iter()
|
||||
.map(|&line| {
|
||||
let at = if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
|
||||
(at, b.line_range(line, lo, hi).a1())
|
||||
})
|
||||
.collect();
|
||||
if sparks.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
|
||||
return Err(EngineError::Other("There's no room next to the selection for the sparklines.".into()));
|
||||
}
|
||||
let sheet = b.sheet;
|
||||
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
// Sparklines are not cell content, so the commit-time protection check does not see them.
|
||||
if sh.is_protected() {
|
||||
return Err(EngineError::Other(PROTECTED.into()));
|
||||
}
|
||||
if !overwrite && sparks.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.sparklines.iter().any(|x| x.cell == *t)) {
|
||||
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
|
||||
}
|
||||
let out = sparks.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
|
||||
let count = sparks.len();
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
for (cell, source) in sparks {
|
||||
sh.sparklines.retain(|x| x.cell != cell);
|
||||
sh.sparklines.push(Sparkline { cell, source, kind, color: Color::Theme(4, 0), markers });
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"output": out.map(|o| o.a1()), "sparklines": count}))
|
||||
}
|
||||
@@ -161,7 +161,7 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let d = s.doc()?;
|
||||
let what = d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
|
||||
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_password_hash(d, &what, pw)), ..prot };
|
||||
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_protection_hash(d, &what, pw)), ..prot };
|
||||
edit(s, |cx| {
|
||||
// FORMULATEXT reads a sheet's protection: its results are recalculated.
|
||||
cx.recalc_all = true;
|
||||
@@ -192,13 +192,25 @@ fn unprotect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A new Excel-compatible (SHA-512, salted) hash of `pw`. The salt mixes `what` is protected
|
||||
/// with the document, a counter and the clock, so equal passwords get different hashes.
|
||||
/// A new hash of a sheet's or the workbook's protection password, in every form a file keeps
|
||||
/// (Excel's salted SHA-512 and OpenDocument's SHA-256 digest), so it survives saving in either
|
||||
/// format.
|
||||
fn new_protection_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
|
||||
PasswordHash::new_for_files(pw, &new_salt(d, what))
|
||||
}
|
||||
|
||||
/// A new Excel-compatible (SHA-512, salted) hash of `pw`: edit ranges only have this form.
|
||||
fn new_password_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
|
||||
PasswordHash::new_sha512(pw, &new_salt(d, what))
|
||||
}
|
||||
|
||||
/// A salt mixing `what` is protected with the document, a counter and the clock, so equal
|
||||
/// passwords get different hashes.
|
||||
fn new_salt(d: &DocState, what: &str) -> [u8; 16] {
|
||||
static SALT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = SALT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let seed = format!("{what}\u{0}{n}\u{0}{}\u{0}{}", d.uid, gridcraft_calc::now_serial().to_bits());
|
||||
PasswordHash::new_sha512(pw, &gridcraft_model::password::salt_from(seed.as_bytes()))
|
||||
gridcraft_model::password::salt_from(seed.as_bytes())
|
||||
}
|
||||
|
||||
fn range_text(r: &EditRange) -> String {
|
||||
@@ -317,7 +329,7 @@ fn protect_workbook(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Ok(json!({"on": on}));
|
||||
}
|
||||
let password = if on {
|
||||
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_password_hash(d, "workbook", pw))
|
||||
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_protection_hash(d, "workbook", pw))
|
||||
} else {
|
||||
if let Some(h) = &d.wb.structure_password
|
||||
&& !h.verify(str_param(p, "password").unwrap_or("")).map_err(EngineError::Other)?
|
||||
@@ -449,7 +461,10 @@ mod tests {
|
||||
let mut s = book();
|
||||
s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap();
|
||||
let prot = s.doc().unwrap().wb.active().unwrap().protection.clone().unwrap();
|
||||
assert!(matches!(&prot.password, Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
|
||||
// Kept in both forms: Excel's salted SHA-512 and OpenDocument's SHA-256 digest.
|
||||
let password = prot.password.as_ref().unwrap();
|
||||
assert!(matches!(password.excel(), Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
|
||||
assert_eq!(password.odf_key(), PasswordHash::new_sha256_digest("pa55").odf_key());
|
||||
assert!(s.execute("review.unprotectSheet", json!({})).is_err());
|
||||
assert!(s.execute("review.unprotectSheet", json!({"password": "pass"})).is_err());
|
||||
// Protecting again can't swap the password out from under it.
|
||||
|
||||
+109
-35
@@ -154,7 +154,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
}
|
||||
sh.merges = sh.merges.iter().filter_map(|m| map_range(*m)).filter(|m| !m.is_single()).collect();
|
||||
for cf in sh.cond_formats.iter_mut() {
|
||||
cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r)).collect();
|
||||
let before = std::mem::take(&mut cf.ranges);
|
||||
let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r).map(|m| (*r, m))).collect();
|
||||
cf.ranges = moves.iter().map(|(_, m)| *m).collect();
|
||||
rehost_rule(cf.rule.relative_formulas_mut(), &before, &moves, &e);
|
||||
}
|
||||
for er in sh.edit_ranges.iter_mut() {
|
||||
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r)).collect();
|
||||
@@ -162,7 +165,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
sh.edit_ranges.retain(|er| !er.ranges.is_empty());
|
||||
sh.cond_formats.retain(|cf| !cf.ranges.is_empty());
|
||||
for dv in sh.validations.iter_mut() {
|
||||
dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r)).collect();
|
||||
let before = std::mem::take(&mut dv.ranges);
|
||||
let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r).map(|m| (*r, m))).collect();
|
||||
dv.ranges = moves.iter().map(|(_, m)| *m).collect();
|
||||
rehost_rule(dv.formulas_mut(), &before, &moves, &e);
|
||||
}
|
||||
sh.validations.retain(|dv| !dv.ranges.is_empty());
|
||||
for t in sh.tables.iter_mut() {
|
||||
@@ -239,8 +245,7 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites every formula reference (chart series included), sparkline source and PivotTable
|
||||
/// source for a structural edit on `target`.
|
||||
/// Rewrites every reference the workbook holds for a structural edit on `target`.
|
||||
pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
|
||||
rewrite_many(cx, target, std::slice::from_ref(e))
|
||||
}
|
||||
@@ -248,34 +253,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
|
||||
/// [`rewrite`] for several edits applied in order, parsing each reference once.
|
||||
fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> {
|
||||
cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone())));
|
||||
let wb = &mut cx.wb;
|
||||
super::edit::rewrite_all_formulas_many(wb, target, edits)?;
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let Some(sh) = wb.sheet_mut(si) else { continue };
|
||||
let fix = |text: &str| -> String {
|
||||
match gridcraft_formula::parse(text) {
|
||||
Ok(expr) => gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))),
|
||||
Err(_) => text.to_string(),
|
||||
}
|
||||
};
|
||||
for sp in sh.sparklines.iter_mut() {
|
||||
sp.source = fix(&sp.source);
|
||||
}
|
||||
// PivotTable sources (a range, table or defined name) are only rewritten when the edit
|
||||
// moves them, so table and name sources keep their text.
|
||||
for pt in sh.pivots.iter_mut() {
|
||||
let body = pt.source.trim().trim_start_matches('=');
|
||||
if let Ok(expr) = gridcraft_formula::parse(body) {
|
||||
let before = gridcraft_formula::print(&expr);
|
||||
let after = gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e)));
|
||||
if after != before {
|
||||
pt.source = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
super::edit::rewrite_all_formulas_many(&mut cx.wb, target, edits)
|
||||
}
|
||||
|
||||
/// Inserting or deleting cells moves the copied block away from the stored source range, so, like
|
||||
@@ -442,15 +420,37 @@ fn move_columns(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let out = edit(s, |cx| {
|
||||
let name = cx.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
|
||||
cx.protection_checked = true;
|
||||
// The moved columns' rules go with them as a cut's do, so a rule wider than them stays on
|
||||
// its other cells and checks what it did. Their parts are taken from the sheet before the
|
||||
// columns are made room for: a rule's formulas are written for its top-left cell, and
|
||||
// after the insert they no longer say what the moved cells read (a reference between the
|
||||
// rule's top-left and the moved columns has moved, the top-left has not).
|
||||
let insert = Edit::Insert { axis: Axis::Cols, at: before, count };
|
||||
let original = cx.wb.sheets.get(sheet).cloned().ok_or_else(|| bad("sheet.moveColumns", "no such sheet"))?;
|
||||
let at = CellRef::new(0, destination);
|
||||
let block = RangeRef::cols(from, end - 1);
|
||||
let mut cfs: Vec<gridcraft_model::CondFormat> = crate::cmd::data::moved_rule_parts(&original.cond_formats, block, at);
|
||||
let mut dvs: Vec<gridcraft_model::Validation> = crate::cmd::data::moved_rule_parts(&original.validations, block, at);
|
||||
// Each part's formulas, written for the moved cells where they stood, follow the insert
|
||||
// as those cells' formulas do; the move and delete below then rewrite them in place.
|
||||
let follow_insert = |t: &mut String| {
|
||||
if let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) {
|
||||
let e = gridcraft_formula::adjust::adjust(e, &name, &name, &insert);
|
||||
*t = format!("{}{}", if t.starts_with('=') { "=" } else { "" }, gridcraft_formula::print(&e));
|
||||
}
|
||||
};
|
||||
cfs.iter_mut().flat_map(|r| r.rule.formulas_mut()).for_each(follow_insert);
|
||||
dvs.iter_mut().flat_map(|r| r.formulas_mut()).for_each(follow_insert);
|
||||
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
sh.cells.shift_cols(before, count as i64);
|
||||
shift_sheet_features(sh, Axis::Cols, before, count, true);
|
||||
}
|
||||
rewrite(cx, &name, &Edit::Insert { axis: Axis::Cols, at: before, count })?;
|
||||
rewrite(cx, &name, &insert)?;
|
||||
|
||||
let mut touched = Vec::new();
|
||||
crate::cmd::edit::place_moved_rules(cx, (sheet, sheet), source, at, (cfs, dvs))?;
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let pictures: Vec<_> =
|
||||
@@ -458,6 +458,7 @@ fn move_columns(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let cells = sh.take_cells(source);
|
||||
let moved_lines: Vec<_> = (0..count).filter_map(|offset| sh.cols.remove(&(moved_from + offset)).map(|info| (offset, info))).collect();
|
||||
let movement = Edit::Move { from: source, to_row: 0, to_col: destination };
|
||||
// (Its conditional formats and validation no longer touch the moved columns.)
|
||||
shift_cell_features(sh, &movement);
|
||||
for object in sh
|
||||
.charts
|
||||
@@ -752,13 +753,83 @@ pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A conditional format's or validation's formulas are written for its ranges' top-left cell.
|
||||
/// When an edit moves its ranges (`moves`: each range before and after) so the top-left is
|
||||
/// another cell, they are re-hosted at that cell where it stood before the edit; rewriting the
|
||||
/// workbook's references for the edit then moves them as it moves a formula there. A range
|
||||
/// moved whole keeps its cells in step, so its top-left stood where the range's offset says;
|
||||
/// one cut short (its first cells deleted), or one whose own cells an insert or delete of cells
|
||||
/// shifted only in part into its top-left, takes the cell that moved into its place.
|
||||
/// `before` is every range the rule had before the edit (the formulas are written for their
|
||||
/// top-left cell, which may lie in a range the edit removed).
|
||||
fn rehost_rule(formulas: Vec<&mut String>, before: &[RangeRef], moves: &[(RangeRef, RangeRef)], e: &Edit) {
|
||||
let (Some(from), Some(to)) = (RangeRef::top_left(before), RangeRef::top_left(&moves.iter().map(|(_, m)| *m).collect::<Vec<_>>())) else {
|
||||
return;
|
||||
};
|
||||
let whole = |(r, m): &(RangeRef, RangeRef)| r.width() == m.width() && r.height() == m.height();
|
||||
let back = |c: CellRef, (r, m): &(RangeRef, RangeRef)| {
|
||||
CellRef::new(
|
||||
(i64::from(c.row) - i64::from(m.start.row) + i64::from(r.start.row)).max(0) as u32,
|
||||
(i64::from(c.col) - i64::from(m.start.col) + i64::from(r.start.col)).max(0) as u32,
|
||||
)
|
||||
};
|
||||
let holder = moves.iter().find(|(_, m)| m.contains(to));
|
||||
let same_shift = moves.iter().all(whole)
|
||||
&& moves.windows(2).all(|w| match w {
|
||||
[a, b] => back(to, a) == back(to, b),
|
||||
_ => true,
|
||||
});
|
||||
// Inserting or deleting cells can shift part of a range and keep its size (cells deleted in
|
||||
// its first column only, say): when the cell the shift put at its top-left was one of the
|
||||
// rule's own cells, the formulas follow that cell.
|
||||
let shifted_in = matches!(e, Edit::InsertCells { .. } | Edit::DeleteCells { .. })
|
||||
.then(|| pre_image(e, to))
|
||||
.filter(|p| *p != to && before.iter().any(|r| r.contains(*p)));
|
||||
let at = match holder {
|
||||
Some(_) if shifted_in.is_some() => shifted_in.unwrap_or(to),
|
||||
Some(p) if whole(p) => back(to, p),
|
||||
Some(_) => pre_image(e, to),
|
||||
None if same_shift => moves.first().map_or(to, |p| back(to, p)),
|
||||
None => pre_image(e, to),
|
||||
};
|
||||
if at != from {
|
||||
for f in formulas {
|
||||
*f = crate::cmd::data::move_rule_formula(f, from, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the cell that `e` puts at `c` stood before it (`c` itself when nothing moved it).
|
||||
fn pre_image(e: &Edit, c: CellRef) -> CellRef {
|
||||
let (axis, count) = match *e {
|
||||
Edit::Insert { axis, count, .. } | Edit::Delete { axis, count, .. } => (axis, count),
|
||||
Edit::InsertCells { axis, range } | Edit::DeleteCells { axis, range } => {
|
||||
(axis, if axis == Axis::Rows { range.height() } else { range.width() })
|
||||
}
|
||||
// A move takes ranges whole, which `rehost_rule` handles by their offset.
|
||||
Edit::Move { .. } | Edit::MoveToSheet { .. } => return c,
|
||||
};
|
||||
let along = |d: i64| match axis {
|
||||
Axis::Rows => c.offset(d, 0),
|
||||
Axis::Cols => c.offset(0, d),
|
||||
};
|
||||
[Some(c), along(i64::from(count)), along(-i64::from(count))]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|p| map_range(RangeRef::cell(*p), e).map(|r| r.start) == Some(c))
|
||||
.unwrap_or(c)
|
||||
}
|
||||
|
||||
/// Shifts what Insert/Delete Cells moves along with the cells: merged areas, conditional
|
||||
/// format, validation, table, filter and print-area ranges, notes, links and sparklines.
|
||||
pub(super) fn shift_cell_features(sh: &mut Sheet, e: &Edit) {
|
||||
let map_cell = |c: CellRef| map_range(RangeRef::cell(c), e).map(|r| r.start);
|
||||
sh.merges = sh.merges.iter().filter_map(|m| map_range(*m, e)).filter(|m| !m.is_single()).collect();
|
||||
for cf in sh.cond_formats.iter_mut() {
|
||||
cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
|
||||
let before = std::mem::take(&mut cf.ranges);
|
||||
let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r, e).map(|m| (*r, m))).collect();
|
||||
cf.ranges = moves.iter().map(|(_, m)| *m).collect();
|
||||
rehost_rule(cf.rule.relative_formulas_mut(), &before, &moves, e);
|
||||
}
|
||||
for er in sh.edit_ranges.iter_mut() {
|
||||
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
|
||||
@@ -766,7 +837,10 @@ pub(super) fn shift_cell_features(sh: &mut Sheet, e: &Edit) {
|
||||
sh.edit_ranges.retain(|er| !er.ranges.is_empty());
|
||||
sh.cond_formats.retain(|cf| !cf.ranges.is_empty());
|
||||
for dv in sh.validations.iter_mut() {
|
||||
dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
|
||||
let before = std::mem::take(&mut dv.ranges);
|
||||
let moves: Vec<(RangeRef, RangeRef)> = before.iter().filter_map(|r| map_range(*r, e).map(|m| (*r, m))).collect();
|
||||
dv.ranges = moves.iter().map(|(_, m)| *m).collect();
|
||||
rehost_rule(dv.formulas_mut(), &before, &moves, e);
|
||||
}
|
||||
sh.validations.retain(|dv| !dv.ranges.is_empty());
|
||||
for t in sh.tables.iter_mut() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{Arc, CellRef, Ctx, EngineError, Json, Result, Session, Sheet, Visibility, bad, bool_param, edit, json, ok, str_param, target_sheet};
|
||||
use super::{Arc, Ctx, EngineError, Json, Result, Session, Sheet, Visibility, bad, bool_param, edit, json, ok, str_param, target_sheet};
|
||||
|
||||
pub(super) fn insert_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if s.doc()?.wb.protected_structure {
|
||||
@@ -50,37 +50,16 @@ pub(super) fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc_mut()?;
|
||||
edit_doc(d, |cx| {
|
||||
cx.wb.sheets.remove(i);
|
||||
for si in 0..cx.wb.sheets.len() {
|
||||
let keys: Vec<(CellRef, Arc<gridcraft_model::Formula>)> =
|
||||
cx.wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default();
|
||||
let Some(sh) = cx.wb.sheet_mut(si) else { continue };
|
||||
for (c, f) in keys {
|
||||
// Only formulas whose tree changes are rewritten; the others keep their text.
|
||||
let changed = f.with_expr(|e| Some(gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order)).filter(|ne| ne != e));
|
||||
if let Some(Some(ne)) = changed
|
||||
&& let Some(cell) = sh.cells.get_mut(c)
|
||||
{
|
||||
cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne)));
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?;
|
||||
// Chart series into the deleted sheet become #REF!, like formulas.
|
||||
crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order));
|
||||
cx.wb.names.retain(|n| n.scope != Some(i));
|
||||
// Every reference into the deleted sheet becomes #REF!.
|
||||
cx.wb.rewrite_references(&|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order));
|
||||
crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?;
|
||||
for n in cx.wb.names.iter_mut() {
|
||||
if let Some(sc) = n.scope.as_mut()
|
||||
&& *sc > i
|
||||
{
|
||||
*sc -= 1;
|
||||
}
|
||||
// Names referring to the sheet become #REF!.
|
||||
if let Ok(e) = gridcraft_formula::parse_name(&n.formula) {
|
||||
let ne = gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order);
|
||||
if ne != e {
|
||||
n.formula = gridcraft_formula::print(&ne);
|
||||
}
|
||||
}
|
||||
}
|
||||
if cx.wb.active_sheet() >= cx.wb.sheets.len() || cx.wb.active_sheet() > i {
|
||||
cx.wb.set_active_sheet(cx.wb.active_sheet().saturating_sub(1).min(cx.wb.sheets.len().saturating_sub(1)));
|
||||
@@ -105,21 +84,17 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
edit(s, |cx| {
|
||||
let old = cx.wb.sheet(i).map(|s| s.name.clone()).unwrap_or_default();
|
||||
cx.sheet_mut(i)?.name = name.clone();
|
||||
// Every reference the workbook holds follows the sheet.
|
||||
cx.wb.rewrite_references(&|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name));
|
||||
// A PivotChart follows its PivotTable's sheet. Only a sheet holding such a chart is
|
||||
// copied, so the others stay shared with undo snapshots.
|
||||
let on_old = |link: Option<&str>| link.and_then(crate::pivot::parse_chart_link).is_some_and(|(sheet, _)| sheet.eq_ignore_ascii_case(&old));
|
||||
for si in 0..cx.wb.sheets.len() {
|
||||
let keys: Vec<(CellRef, Arc<gridcraft_model::Formula>)> =
|
||||
cx.wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default();
|
||||
let Some(sh) = cx.wb.sheet_mut(si) else { continue };
|
||||
for (c, f) in keys {
|
||||
// Compares trees, so unchanged formulas are not printed; they keep their text.
|
||||
let changed = f.with_expr(|e| Some(gridcraft_formula::adjust::rename_sheet(e.clone(), &old, &name)).filter(|ne| ne != e));
|
||||
if let Some(Some(ne)) = changed
|
||||
&& let Some(cell) = sh.cells.get_mut(c)
|
||||
{
|
||||
cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne)));
|
||||
}
|
||||
if !cx.wb.sheets.get(si).is_some_and(|sh| sh.charts.iter().any(|ch| on_old(ch.pivot.as_deref()))) {
|
||||
continue;
|
||||
}
|
||||
let Some(sh) = cx.wb.sheet_mut(si) else { continue };
|
||||
for ch in sh.charts.iter_mut() {
|
||||
// A PivotChart follows its PivotTable's sheet.
|
||||
if let Some((sheet, pivot)) = ch.pivot.as_deref().and_then(crate::pivot::parse_chart_link)
|
||||
&& sheet.eq_ignore_ascii_case(&old)
|
||||
{
|
||||
@@ -127,12 +102,6 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name));
|
||||
for n in cx.wb.names.iter_mut() {
|
||||
if let Ok(e) = gridcraft_formula::parse_name(&n.formula) {
|
||||
n.formula = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &old, &name));
|
||||
}
|
||||
}
|
||||
crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name))?;
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
@@ -164,6 +133,29 @@ pub(super) fn move_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
.find(|nm| cx.wb.sheet_index(nm).is_none())
|
||||
.unwrap_or(base.clone());
|
||||
sh.name = name;
|
||||
// A copied sheet's charts plot the copy's own data, as Excel's do (its formulas keep
|
||||
// what they name).
|
||||
// Text that names no other sheet is kept as written (a leading `=` included).
|
||||
let copy = sh.name.clone();
|
||||
let fix = |t: &mut String| {
|
||||
let Ok(e) = gridcraft_formula::parse(t.trim_start_matches('=')) else { return };
|
||||
let before = gridcraft_formula::print(&e);
|
||||
let after = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &base, ©));
|
||||
if after != before {
|
||||
*t = if t.starts_with('=') { format!("={after}") } else { after };
|
||||
}
|
||||
};
|
||||
for ch in &mut sh.charts {
|
||||
for se in &mut ch.series {
|
||||
fix(&mut se.values);
|
||||
for t in [&mut se.categories, &mut se.name, &mut se.bubble_sizes].into_iter().flatten() {
|
||||
fix(t);
|
||||
}
|
||||
}
|
||||
if let Some(t) = ch.source.as_mut() {
|
||||
fix(t);
|
||||
}
|
||||
}
|
||||
sh.tables.clear(); // table names must be unique
|
||||
sh.preserved = None; // kept file content (form controls, OLE objects…) stays with the original
|
||||
// Object ids are unique across the workbook (selection and the `{kind, id}` commands
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! View tab (sheet view state that's saved with the file) and Page Layout settings.
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_model::Orientation;
|
||||
use gridcraft_model::{Orientation, Workbook};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{
|
||||
@@ -62,8 +62,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
workbook_view_flag(s, p, "vertical")
|
||||
}),
|
||||
cmd!("view.rightToLeft", "Sheet Right-to-Left", ["Page Layout", "Sheet Options"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "rtl")),
|
||||
cmd!("view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
|
||||
cmd!("view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))),
|
||||
cmd!(noundo "view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
|
||||
cmd!(noundo "view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))),
|
||||
cmd!(query "view.formulaBar", "Formula Bar", ["View", "Show"], None, "{on?: bool}", always, |s, p| {
|
||||
s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar);
|
||||
Ok(json!({"on": s.prefs.formula_bar}))
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
status_bar
|
||||
),
|
||||
cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
|
||||
cmd!(noundo "view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
|
||||
cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation),
|
||||
cmd!(
|
||||
"pageLayout.size",
|
||||
@@ -274,6 +274,34 @@ fn zoom(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(json!({"zoom": z}))
|
||||
}
|
||||
|
||||
/// Zoom belongs to the window, not to the edits (Excel doesn't undo it, #2313): undo and redo keep
|
||||
/// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved
|
||||
/// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`.
|
||||
pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) {
|
||||
// Sheets have no stable id. A name missing from `now` is a rename being undone or redone, which
|
||||
// keeps the sheet count and position: the sheet is the one at the same index, under a name the
|
||||
// restored snapshot doesn't have.
|
||||
let renamed = |i: usize| {
|
||||
(now.sheets.len() == d.wb.sheets.len()).then(|| now.sheets.get(i)).flatten().filter(|sh| !d.wb.sheets.iter().any(|s| s.name == sh.name))
|
||||
};
|
||||
let current = |i: usize, name: &str| now.sheets.iter().find(|sh| sh.name == name).or_else(|| renamed(i)).map(|sh| sh.zoom);
|
||||
let changed: Vec<(usize, u16)> =
|
||||
d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect();
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let saved = std::sync::Arc::ptr_eq(&d.wb, &d.saved);
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
for (i, z) in changed {
|
||||
if let Some(sh) = wb.sheet_mut(i) {
|
||||
sh.zoom = z;
|
||||
}
|
||||
}
|
||||
if saved {
|
||||
d.saved = d.wb.clone();
|
||||
}
|
||||
}
|
||||
|
||||
fn zoom_selection(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
@@ -535,6 +563,7 @@ fn theme(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gridcraft_core::CellRef;
|
||||
|
||||
#[test]
|
||||
fn zoom_100_resets_the_active_sheet_zoom() {
|
||||
@@ -545,6 +574,94 @@ mod tests {
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zooming_is_not_an_undo_step() {
|
||||
// Excel keeps zoom on the window, not in the edit history (#2313): wheel, slider, dialog,
|
||||
// 100% and Zoom to Selection leave Undo and Redo alone.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "y"})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let (undo, redo) = s.doc().map(|d| (d.undo.len(), d.redo.len())).unwrap();
|
||||
for (id, params, zoom) in [
|
||||
("view.zoom", json!({"percent": 150}), 150),
|
||||
("view.zoomToSelection", json!({"viewWidth": 1200, "viewHeight": 700}), 400),
|
||||
("view.zoom100", json!({}), 100),
|
||||
] {
|
||||
s.execute(id, params).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.wb.active().unwrap().zoom, zoom, "{id}");
|
||||
assert_eq!((d.undo.len(), d.redo.len()), (undo, redo), "{id} touched the history");
|
||||
}
|
||||
let a1 = CellRef::parse("A1").unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().value(a1).is_empty(), "Ctrl+Z after zooming undoes the last edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_redo_keep_the_current_zoom() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let zoom = |s: &Session| s.doc().unwrap().wb.active().unwrap().zoom;
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 200})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty());
|
||||
assert_eq!(zoom(&s), 200, "undo keeps the zoom");
|
||||
// Back at the state on disk: the zoom alone doesn't make the workbook dirty, as in `zoom`.
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("view.zoom", json!({"percent": 50})).unwrap();
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty());
|
||||
assert_eq!(zoom(&s), 50, "redo keeps the zoom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_a_rename_keeps_the_current_zoom() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let active = |s: &Session| {
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
(sh.name.clone(), sh.zoom)
|
||||
};
|
||||
let before = active(&s).0;
|
||||
s.execute("sheet.rename", json!({"name": "Data"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 150})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(active(&s), (before, 150), "undoing the rename keeps the zoom");
|
||||
s.execute("view.zoom", json!({"percent": 75})).unwrap();
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_several_steps_keeps_each_sheet_its_own_zoom() {
|
||||
// Adding C then deleting B leaves as many sheets as before under other names: across both
|
||||
// steps at once, that looks like B renamed to C, and C's zoom used to land on B.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let zoom = |s: &Session, name: &str| {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
wb.sheet(wb.sheet_index(name).unwrap()).unwrap().zoom
|
||||
};
|
||||
let names = |s: &Session| s.doc().unwrap().wb.sheets.iter().map(|sh| sh.name.clone()).collect::<Vec<_>>();
|
||||
let first = names(&s)[0].clone();
|
||||
s.execute("home.insertSheet", json!({"name": "B", "before": 1})).unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "C", "before": 2})).unwrap();
|
||||
s.execute("home.deleteSheet", json!({"sheet": "B"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": "C"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 150})).unwrap();
|
||||
s.execute("edit.undo", json!({"steps": 2})).unwrap();
|
||||
assert_eq!(names(&s), [first.clone(), "B".to_string()]);
|
||||
assert_eq!(zoom(&s, "B"), 100, "B never had C's zoom");
|
||||
s.execute("sheet.activate", json!({"sheet": "B"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 80})).unwrap();
|
||||
s.execute("edit.redo", json!({"steps": 2})).unwrap();
|
||||
assert_eq!(names(&s), [first, "C".to_string()]);
|
||||
assert_eq!(zoom(&s, "C"), 150, "C gets its own zoom back, not B's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -51,12 +51,16 @@ fn text_needs_quote_prefix(t: &str, sys: gridcraft_core::date::DateSystem) -> bo
|
||||
if t.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut chars = t.chars();
|
||||
let (first, second) = (chars.next(), chars.next());
|
||||
let first = t.chars().next();
|
||||
if matches!(first, Some('=' | '\'')) {
|
||||
return true;
|
||||
}
|
||||
if matches!(first, Some('+' | '-')) && second.is_some_and(|c| c.is_ascii_alphabetic() || c == '(') {
|
||||
// A `+` or `-` entry that reads as a formula becomes one (`+5+4`, `-abc`); one that doesn't
|
||||
// stays text (`--`, `+49 170 1234567`), as `input_to_cell` decides it.
|
||||
if matches!(first, Some('+' | '-'))
|
||||
&& gridcraft_core::parse::starts_formula(t)
|
||||
&& crate::cmd::edit::parse_typed_formula(t).is_ok_and(|e| crate::cmd::edit::check_arg_counts(&e).is_ok())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
!matches!(gridcraft_core::parse::parse_input(t, sys).value, Value::Text(ref x) if x.as_ref() == t)
|
||||
|
||||
+216
-21
@@ -28,6 +28,12 @@ pub enum FillMode {
|
||||
/// counted in that unit (one unit when they fall in the same one). A source that isn't dates
|
||||
/// extends like a plain drag.
|
||||
Dates(DateUnit),
|
||||
/// Linear Trend: the targets continue the least-squares line (y = mx + b) through the source's
|
||||
/// numbers. The source keeps its values.
|
||||
LinearTrend,
|
||||
/// Growth Trend: the targets continue the exponential curve (y = b·m^x) fitted to the source's
|
||||
/// numbers. The source keeps its values.
|
||||
GrowthTrend,
|
||||
}
|
||||
|
||||
/// The step of a [`FillMode::Dates`] fill.
|
||||
@@ -47,6 +53,87 @@ impl FillMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fill from `src` to `target` runs down or up the sheet rather than across it.
|
||||
fn fills_vertically(src: RangeRef, target: RangeRef) -> bool {
|
||||
target.height() != src.height() || target.width() == src.width()
|
||||
}
|
||||
|
||||
/// The numbers in each lane of `src` that a fill to `target` continues, or `None` when a source
|
||||
/// cell is empty or holds text, a logical value, an error, a formula or Python code.
|
||||
fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option<Vec<Vec<f64>>> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
lane_cells(src, target).map(|lane| lane.map(|c| trend_number(sh, c)).collect()).collect()
|
||||
}
|
||||
|
||||
/// The cells of each lane of `src` that a fill to `target` continues: each column when the fill
|
||||
/// runs down or up the sheet, each row when it runs across.
|
||||
fn lane_cells(src: RangeRef, target: RangeRef) -> impl Iterator<Item = impl Iterator<Item = CellRef>> {
|
||||
let vertical = fills_vertically(src, target);
|
||||
let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) };
|
||||
lanes.map(move |lane| (0..len).map(move |i| if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }))
|
||||
}
|
||||
|
||||
/// The sign Growth Trend fits a lane's numbers by: 1 when they are all above zero, -1 when they
|
||||
/// are all below zero, and `None` otherwise.
|
||||
fn growth_sign(nums: impl IntoIterator<Item = f64>) -> Option<f64> {
|
||||
let (mut above, mut below) = (true, true);
|
||||
for y in nums {
|
||||
above &= y > 0.0;
|
||||
below &= y < 0.0;
|
||||
}
|
||||
if above {
|
||||
Some(1.0)
|
||||
} else if below {
|
||||
Some(-1.0)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The number a trend fill reads from source cell `c`, or `None` when it is empty or holds text, a
|
||||
/// logical value, an error, a formula or Python code.
|
||||
fn trend_number(sh: &gridcraft_model::Sheet, c: CellRef) -> Option<f64> {
|
||||
let cell = sh.cell(c)?;
|
||||
if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() {
|
||||
return None;
|
||||
}
|
||||
cell.value.as_f64()
|
||||
}
|
||||
|
||||
/// Whether the fill menu offers Linear Trend (`growth` false) or Growth Trend (`growth` true) for a
|
||||
/// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers
|
||||
/// of each lane are all above zero or all below zero. A source or target larger than
|
||||
/// [`MAX_FILL_CELLS`], or a target that doesn't hold the source in a corner, is refused by
|
||||
/// `edit.autoFill`, so neither trend applies to it and no source cell is read.
|
||||
pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool {
|
||||
let (linear, growth_fits) = trends_that_apply(wb, sheet, src, target);
|
||||
if growth { growth_fits } else { linear }
|
||||
}
|
||||
|
||||
/// [`trend_applies`] for both trends from one read of the source: (Linear Trend, Growth Trend). It
|
||||
/// checks each cell's number and sign and fits nothing, so the menu does not wait on a fit.
|
||||
pub fn trends_that_apply(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> (bool, bool) {
|
||||
if src.count() > MAX_FILL_CELLS || target.count() > MAX_FILL_CELLS || !holds_source_in_corner(src, target) {
|
||||
return (false, false);
|
||||
}
|
||||
let Some(sh) = wb.sheet(sheet) else { return (false, false) };
|
||||
let mut growth = true;
|
||||
// The lanes and the sign rule are the ones the fill uses (`numeric_lanes`, `Pattern::growth`).
|
||||
for lane in lane_cells(src, target) {
|
||||
let mut missing = false;
|
||||
let sign = growth_sign(lane.map_while(|c| {
|
||||
let y = trend_number(sh, c);
|
||||
missing |= y.is_none();
|
||||
y
|
||||
}));
|
||||
if missing {
|
||||
return (false, false);
|
||||
}
|
||||
growth &= sign.is_some();
|
||||
}
|
||||
(true, growth)
|
||||
}
|
||||
|
||||
/// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"`
|
||||
/// and `h:mm` don't).
|
||||
fn is_date_format(fmt: &str) -> bool {
|
||||
@@ -102,7 +189,7 @@ pub fn fill_except(
|
||||
let custom = cx.wb.custom_lists.clone();
|
||||
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
|
||||
// Direction: down/up if target extends rows, else right/left.
|
||||
let vertical = target.height() != src.height() || target.width() == src.width();
|
||||
let vertical = fills_vertically(src, target);
|
||||
let forward = if vertical {
|
||||
target.end.row > src.end.row || target.start.row == src.start.row
|
||||
} else {
|
||||
@@ -120,11 +207,25 @@ pub fn fill_except(
|
||||
if u64::from(lane_count).saturating_mul(u64::from(steps)) > MAX_FILL_CELLS {
|
||||
return Err(crate::EngineError::Other("The fill is too large.".into()));
|
||||
}
|
||||
// Linear Trend and Growth Trend fit each lane's numbers.
|
||||
let trends: Vec<Pattern> = match mode {
|
||||
FillMode::LinearTrend | FillMode::GrowthTrend => {
|
||||
let Some(lanes) = numeric_lanes(&cx.wb, sheet, src, target) else {
|
||||
return Err(crate::EngineError::Other("Linear Trend and Growth Trend need a number in every source cell.".into()));
|
||||
};
|
||||
let fit = |nums: &Vec<f64>| if mode == FillMode::GrowthTrend { Pattern::growth(nums) } else { Some(Pattern::linear(nums)) };
|
||||
let Some(trends) = lanes.iter().map(fit).collect() else {
|
||||
return Err(crate::EngineError::Other("Growth Trend needs numbers that are all above zero or all below zero.".into()));
|
||||
};
|
||||
trends
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let lanes: Vec<u32> = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() };
|
||||
let src_len = if vertical { src.height() } else { src.width() };
|
||||
let mut writes: Vec<(CellRef, Option<Cell>)> = Vec::new();
|
||||
let mut pictures = Vec::new();
|
||||
for lane in lanes {
|
||||
for (lane_i, lane) in lanes.into_iter().enumerate() {
|
||||
let src_cells: Vec<(CellRef, Option<Cell>)> = (0..src_len)
|
||||
.map(|i| {
|
||||
let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) };
|
||||
@@ -142,7 +243,9 @@ pub fn fill_except(
|
||||
};
|
||||
targets.retain(|t| !skip_rows.contains(&t.row));
|
||||
let fmt = |c: &(CellRef, Option<Cell>)| cx.wb.styles.get(c.1.as_ref().map(|c| c.style).unwrap_or_default()).num_fmt.as_str();
|
||||
let pattern = if mode.extends_series() || mode == FillMode::Alternate {
|
||||
let pattern = if let Some(trend) = trends.get(lane_i) {
|
||||
trend.clone()
|
||||
} else if mode.extends_series() || mode == FillMode::Alternate {
|
||||
let first_fmt = src_cells.first().map(fmt).unwrap_or_default();
|
||||
let dates = match mode {
|
||||
FillMode::Dates(unit) => Pattern::dates(&src_cells, unit, cx.wb.date_system, first_fmt),
|
||||
@@ -176,7 +279,14 @@ pub fn fill_except(
|
||||
writes.push((*t, Some(existing)));
|
||||
continue;
|
||||
}
|
||||
FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy | FillMode::Extend | FillMode::Dates(_) => {
|
||||
FillMode::ValuesOnly
|
||||
| FillMode::Series
|
||||
| FillMode::Alternate
|
||||
| FillMode::Copy
|
||||
| FillMode::Extend
|
||||
| FillMode::Dates(_)
|
||||
| FillMode::LinearTrend
|
||||
| FillMode::GrowthTrend => {
|
||||
let style = if mode == FillMode::ValuesOnly { sh.cell(*t).map(|c| c.style).unwrap_or_default() } else { cell.style };
|
||||
if let Some(f) = &cell.formula {
|
||||
if let Some(e) = f.expr() {
|
||||
@@ -259,9 +369,42 @@ enum Pattern {
|
||||
step: i64,
|
||||
sys: gridcraft_core::DateSystem,
|
||||
},
|
||||
/// Growth Trend, kept as logarithms so that a value the curve reaches is not lost to an
|
||||
/// overflow or underflow on the way: the logarithms of the fitted magnitudes at the source's
|
||||
/// last and first cells, the logarithm of the factor between neighboring cells, and the sign
|
||||
/// of every value (1 or -1).
|
||||
Growth {
|
||||
last: f64,
|
||||
first: f64,
|
||||
step: f64,
|
||||
sign: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
/// Linear Trend: the least-squares line through `nums`. A lone number is copied unchanged.
|
||||
fn linear(nums: &[f64]) -> Pattern {
|
||||
if nums.len() == 1 {
|
||||
return Pattern::Copy;
|
||||
}
|
||||
let (first, last, step) = least_squares(nums);
|
||||
Pattern::Linear { last, first, step }
|
||||
}
|
||||
|
||||
/// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on
|
||||
/// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted
|
||||
/// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or
|
||||
/// all below zero. A lone number, or the same number repeated, is copied unchanged.
|
||||
fn growth(nums: &[f64]) -> Option<Pattern> {
|
||||
let sign = growth_sign(nums.iter().copied())?;
|
||||
if nums.windows(2).all(|w| w.first() == w.last()) {
|
||||
return Some(Pattern::Copy);
|
||||
}
|
||||
let logs: Vec<f64> = nums.iter().map(|y| (y * sign).ln()).collect();
|
||||
let (first, last, step) = least_squares(&logs);
|
||||
Some(Pattern::Growth { last, first, step, sign })
|
||||
}
|
||||
|
||||
/// The pattern of Fill Days, Fill Weekdays, Fill Months or Fill Years, or `None` when the
|
||||
/// source isn't all dates (numbers, not formulas, under a date format in its first cell).
|
||||
fn dates(cells: &[(CellRef, Option<Cell>)], unit: DateUnit, sys: gridcraft_core::DateSystem, fmt: &str) -> Option<Pattern> {
|
||||
@@ -344,19 +487,7 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
// Least-squares step for 2+ values (Excel uses a linear trend).
|
||||
let n = nums.len() as f64;
|
||||
let mean_x = (n - 1.0) / 2.0;
|
||||
let mean_y = nums.iter().sum::<f64>() / n;
|
||||
let mut num = 0.0;
|
||||
let mut den = 0.0;
|
||||
for (i, y) in nums.iter().enumerate() {
|
||||
num += (i as f64 - mean_x) * (y - mean_y);
|
||||
den += (i as f64 - mean_x).powi(2);
|
||||
}
|
||||
let step = if den == 0.0 { 0.0 } else { num / den };
|
||||
let fitted_last = mean_y + step * (n - 1.0 - mean_x);
|
||||
let fitted_first = mean_y - step * mean_x;
|
||||
return Pattern::Linear { last: fitted_last, first: fitted_first, step };
|
||||
return Pattern::linear(&nums);
|
||||
}
|
||||
// Text.
|
||||
if !vals.is_empty() && vals.iter().all(|v| v.is_text()) {
|
||||
@@ -450,10 +581,45 @@ impl Pattern {
|
||||
let base = if forward { *last } else { *first };
|
||||
Some(Value::number(add_weekdays(*sys, base, step.checked_mul(k)?.checked_mul(sign)?)?))
|
||||
}
|
||||
Pattern::Growth { last, first, step, sign: growth_sign } => {
|
||||
let base = if forward { *last } else { *first };
|
||||
Some(Value::number(round15(growth_sign * (base + step * (k * sign) as f64).exp())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 2^600 and 2^-600, both exact.
|
||||
const TWO_POW_600: f64 = f64::from_bits((1023 + 600) << 52);
|
||||
const TWO_POW_MINUS_600: f64 = f64::from_bits((1023 - 600) << 52);
|
||||
|
||||
/// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last
|
||||
/// positions, and its step. A lone number gives a step of zero. When a number is larger than 2^600,
|
||||
/// the fit runs on the numbers multiplied by 2^-600 and its results are multiplied by 2^600, so the
|
||||
/// sums stay finite for numbers up to the largest double. When every number is smaller than 2^-600,
|
||||
/// the fit runs on the numbers multiplied by 2^600 and its results are multiplied by 2^-600, so
|
||||
/// subnormal numbers keep their step instead of rounding it to zero.
|
||||
fn least_squares(nums: &[f64]) -> (f64, f64, f64) {
|
||||
let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) {
|
||||
(TWO_POW_MINUS_600, TWO_POW_600)
|
||||
} else if nums.iter().all(|y| y.abs() < TWO_POW_MINUS_600) {
|
||||
(TWO_POW_600, TWO_POW_MINUS_600)
|
||||
} else {
|
||||
(1.0, 1.0)
|
||||
};
|
||||
let n = nums.len() as f64;
|
||||
let mean_x = (n - 1.0) / 2.0;
|
||||
let mean_y = nums.iter().map(|y| y * down).sum::<f64>() / n;
|
||||
let mut num = 0.0;
|
||||
let mut den = 0.0;
|
||||
for (i, y) in nums.iter().enumerate() {
|
||||
num += (i as f64 - mean_x) * (y * down - mean_y);
|
||||
den += (i as f64 - mean_x).powi(2);
|
||||
}
|
||||
let step = if den == 0.0 { 0.0 } else { num / den };
|
||||
((mean_y - step * mean_x) * up, (mean_y + step * (n - 1.0 - mean_x)) * up, step * up)
|
||||
}
|
||||
|
||||
/// Whether `serial` falls on Monday to Friday; `None` outside the supported date range.
|
||||
fn is_weekday(sys: gridcraft_core::DateSystem, serial: f64) -> Option<bool> {
|
||||
datetime_from_serial(sys, serial).map(|d| d.weekday != 0 && d.weekday != 6)
|
||||
@@ -514,13 +680,27 @@ fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64)
|
||||
serial_from_ymd(sys, year, month, (d.day as i64).min(last as i64)).map(|day| day + serial - serial.floor())
|
||||
}
|
||||
|
||||
/// `x` rounded to 15 significant digits through its exact decimal expansion, so a number that
|
||||
/// already has 15 or fewer digits comes back unchanged at any size. A number near the largest
|
||||
/// double whose rounding would pass it keeps its value. A whole number below 10^15 is returned
|
||||
/// as it is, and other numbers are written to a buffer on the stack, so a fill does not allocate
|
||||
/// for each cell.
|
||||
fn round15(x: f64) -> f64 {
|
||||
if x == 0.0 || !x.is_finite() {
|
||||
use std::io::Write;
|
||||
if x == 0.0 || !x.is_finite() || (x.fract() == 0.0 && x.abs() < 1e15) {
|
||||
return x;
|
||||
}
|
||||
let mag = x.abs().log10().floor() as i32;
|
||||
let p = 10f64.powi(14 - mag);
|
||||
if !p.is_finite() || p == 0.0 { x } else { (x * p).round() / p }
|
||||
// "-1.23456789012345e-308" is the longest expansion: 22 bytes.
|
||||
let mut buf = [0u8; 32];
|
||||
let mut out = &mut buf[..];
|
||||
if write!(out, "{x:.14e}").is_err() {
|
||||
return x;
|
||||
}
|
||||
let len = 32 - out.len();
|
||||
match buf.get(..len).and_then(|b| std::str::from_utf8(b).ok()).and_then(|s| s.parse::<f64>().ok()) {
|
||||
Some(r) if r.is_finite() => r,
|
||||
_ => x,
|
||||
}
|
||||
}
|
||||
|
||||
/// `1st Period` → `2nd Period`: an English ordinal ending is rewritten to suit the new number.
|
||||
@@ -811,6 +991,21 @@ mod tests {
|
||||
assert_eq!(sh.value(CellRef::new(1, 1)), Value::from("03/12/2023"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round15_matches_the_decimal_expansion_without_allocating() {
|
||||
let by_string = |x: f64| match format!("{x:.14e}").parse::<f64>() {
|
||||
Ok(r) if r.is_finite() => r,
|
||||
_ => x,
|
||||
};
|
||||
let tiny = f64::from_bits(1);
|
||||
let whole = [1.0, -7.0, 999_999_999_999_999.0, 1e15, 1e15 + 1.0, 123_456_789_012_345_680.0];
|
||||
let other = [0.1 + 0.2, -1.0 / 3.0, tiny, -tiny, 1e-308, f64::MAX, -f64::MAX, 1.7976931348623e308];
|
||||
for x in whole.into_iter().chain(other) {
|
||||
assert_eq!(round15(x).to_bits(), by_string(x).to_bits(), "{x:e}");
|
||||
}
|
||||
assert_eq!(round15(-0.0).to_bits(), (-0.0f64).to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn series_keeps_value_equal_to_stop_after_float_drift() {
|
||||
let mut s = crate::Session::new();
|
||||
|
||||
+3
-32
@@ -1143,43 +1143,14 @@ pub fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
|
||||
Err(EngineError::Other(format!("{path}: no file system in the browser")))
|
||||
}
|
||||
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
||||
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
|
||||
for i in 0..4 {
|
||||
if i <= chunk.len() {
|
||||
out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char);
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
gridcraft_model::b64::encode(data)
|
||||
}
|
||||
|
||||
/// Base64, or a `data:` URL's base64 payload.
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let s = s.split_once(',').filter(|(h, _)| h.starts_with("data:")).map(|(_, b)| b).unwrap_or(s);
|
||||
let mut out = Vec::with_capacity(s.len() / 4 * 3);
|
||||
let mut buf = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes() {
|
||||
if c == b'=' || c.is_ascii_whitespace() {
|
||||
continue;
|
||||
}
|
||||
let v = B64.iter().position(|&x| x == c)? as u32;
|
||||
buf = (buf << 6) | v;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push((buf >> bits) as u8);
|
||||
buf &= (1 << bits) - 1;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
gridcraft_model::b64::decode(s)
|
||||
}
|
||||
|
||||
/// Pixel size of a PNG or JPEG from its header.
|
||||
|
||||
@@ -409,16 +409,19 @@ fn full_sync_tolerates_only_unsupported_errors() {
|
||||
}
|
||||
|
||||
/// Apple's ENOTSUP is 45 (EOPNOTSUPP is 102), and std maps only the latter to
|
||||
/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. Elsewhere 45 is
|
||||
/// another error (EL2NSYNC on Linux) and stays a failed save.
|
||||
/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. On Linux, 45 is
|
||||
/// EL2NSYNC and stays a failed save. On FreeBSD and other BSDs, 45 is ENOTSUP (the same value as
|
||||
/// EOPNOTSUPP), so this host's std reports `ErrorKind::Unsupported` and the flush is tolerated
|
||||
/// even when the `apple` flag is false — which is the real helper's behaviour on those systems.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn full_sync_tolerates_apple_enotsup() {
|
||||
use std::io::Error;
|
||||
use std::io::{Error, ErrorKind};
|
||||
let enotsup = Error::from_raw_os_error(45);
|
||||
assert!(flush_unsupported_on(&enotsup, true, true), "ENOTSUP on Apple");
|
||||
assert!(!flush_unsupported_on(&enotsup, true, false), "45 on other Unix");
|
||||
assert!(!flush_unsupported_on(&enotsup, false, false), "45 on Windows");
|
||||
let host_maps_45_unsupported = enotsup.kind() == ErrorKind::Unsupported;
|
||||
assert_eq!(flush_unsupported_on(&enotsup, true, false), host_maps_45_unsupported, "45 on other Unix");
|
||||
assert_eq!(flush_unsupported_on(&enotsup, false, false), host_maps_45_unsupported, "45 on Windows");
|
||||
assert!(flush_unsupported_on(&Error::from_raw_os_error(25), true, true), "ENOTTY on Apple");
|
||||
assert!(!flush_unsupported_on(&Error::from_raw_os_error(5), true, true), "EIO on Apple");
|
||||
assert!(!flush_unsupported_on(&Error::from_raw_os_error(28), true, true), "ENOSPC on Apple");
|
||||
|
||||
@@ -225,6 +225,9 @@ pub struct DocState {
|
||||
/// The references `edit.goTo` with `record: true` went to in this document, newest first,
|
||||
/// without names, each area written with its sheet (`Sheet1!B14:C22,Sheet1!F19:G30`).
|
||||
pub go_to_recent: Vec<String>,
|
||||
/// The Distinct Count PivotTable value fields (sheet, pivot, value) an .xlsx save has already
|
||||
/// told the user about (#3336), so only a field not yet disclosed raises the notice again.
|
||||
pub distinct_disclosed: Vec<(usize, usize, usize)>,
|
||||
}
|
||||
|
||||
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -342,7 +345,11 @@ impl DocState {
|
||||
wb.refresh_equations();
|
||||
let scripts_trusted = !cmd::extra::has_scripts(&wb);
|
||||
let wb = Arc::new(wb);
|
||||
let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
|
||||
let mut sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
|
||||
// A merged active cell is selected whole, as a click on it selects it (#1348).
|
||||
if let Some(sh) = wb.active() {
|
||||
sel.expand_merges(sh);
|
||||
}
|
||||
DocState {
|
||||
saved: wb.clone(),
|
||||
wb,
|
||||
@@ -362,6 +369,7 @@ impl DocState {
|
||||
touched: None,
|
||||
edits: None,
|
||||
go_to_recent: vec![],
|
||||
distinct_disclosed: vec![],
|
||||
}
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
|
||||
@@ -128,10 +128,14 @@ fn aggregate_record(
|
||||
}
|
||||
for row_depth in 0..=row_path.len() {
|
||||
for col_depth in 0..=col_path.len() {
|
||||
let accs = data
|
||||
.aggs
|
||||
.entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec()))
|
||||
.or_insert_with(|| vec![Acc::default(); input.vals.len() + input.extra.len()]);
|
||||
let accs = data.aggs.entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec())).or_insert_with(|| {
|
||||
input
|
||||
.vals
|
||||
.iter()
|
||||
.map(|(_, v)| Acc::for_func(v.func))
|
||||
.chain(std::iter::repeat_n(Acc::default(), input.extra.len()))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
for (acc, (source, _)) in accs.iter_mut().zip(input.vals) {
|
||||
if let ValSrc::Col(column) = source {
|
||||
acc.add(rec.get(*column).unwrap_or(&Value::Empty));
|
||||
@@ -687,7 +691,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
}
|
||||
PivotShowAs::Rank => v.number_format.clone(),
|
||||
_ => v.number_format.clone().or_else(|| match v.func {
|
||||
PivotFunc::Count | PivotFunc::CountNumbers => None,
|
||||
PivotFunc::Count | PivotFunc::CountNumbers | PivotFunc::DistinctCount => None,
|
||||
_ => {
|
||||
let f = match vs {
|
||||
ValSrc::Col(c) => fmt_of(*c),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial};
|
||||
|
||||
// ---------------------------------------------------------------- items
|
||||
@@ -120,10 +122,35 @@ pub(super) struct Acc {
|
||||
mean: f64,
|
||||
m2: f64,
|
||||
err: Option<CellError>,
|
||||
/// The values seen so far, kept only for a Distinct Count accumulator.
|
||||
distinct: Option<HashSet<String>>,
|
||||
}
|
||||
|
||||
/// What makes two values the same for a Distinct Count: text ignores case, like item labels do.
|
||||
fn distinct_key(v: &Value) -> Option<String> {
|
||||
Some(match v {
|
||||
Value::Empty => return None,
|
||||
Value::Number(n) => format!("n{}", if *n == 0.0 { 0.0 } else { *n }.to_bits()),
|
||||
Value::Text(t) if t.is_empty() => return None,
|
||||
Value::Text(t) => format!("t{}", t.to_lowercase()),
|
||||
Value::Bool(b) => format!("b{b}"),
|
||||
Value::Error(e) => format!("e{}", e.as_str()),
|
||||
Value::Array(_) => return distinct_key(&v.scalar()),
|
||||
})
|
||||
}
|
||||
|
||||
impl Acc {
|
||||
/// An accumulator for value field function `f`: a Distinct Count also remembers each value it saw.
|
||||
pub(super) fn for_func(f: PivotFunc) -> Self {
|
||||
Self { distinct: (f == PivotFunc::DistinctCount).then(HashSet::new), ..Self::default() }
|
||||
}
|
||||
|
||||
pub(super) fn add(&mut self, v: &Value) {
|
||||
if let Some(seen) = &mut self.distinct
|
||||
&& let Some(key) = distinct_key(v)
|
||||
{
|
||||
seen.insert(key);
|
||||
}
|
||||
match v {
|
||||
Value::Empty => {}
|
||||
Value::Number(n) => {
|
||||
@@ -158,6 +185,7 @@ impl Acc {
|
||||
match f {
|
||||
PivotFunc::Count => return Value::number(self.count as f64),
|
||||
PivotFunc::CountNumbers => return Value::number(n),
|
||||
PivotFunc::DistinctCount => return Value::number(self.distinct.as_ref().map_or(0, HashSet::len) as f64),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(e) = self.err {
|
||||
@@ -192,7 +220,7 @@ impl Acc {
|
||||
Value::number(if f == PivotFunc::VarP { var } else { var.sqrt() })
|
||||
}
|
||||
}
|
||||
PivotFunc::Count | PivotFunc::CountNumbers => Value::Empty,
|
||||
PivotFunc::Count | PivotFunc::CountNumbers | PivotFunc::DistinctCount => Value::Empty,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,6 +236,7 @@ pub fn func_caption(f: PivotFunc) -> &'static str {
|
||||
PivotFunc::Min => "Min",
|
||||
PivotFunc::Product => "Product",
|
||||
PivotFunc::CountNumbers => "Count",
|
||||
PivotFunc::DistinctCount => "Distinct Count",
|
||||
PivotFunc::StdDev => "StdDev",
|
||||
PivotFunc::StdDevP => "StdDevp",
|
||||
PivotFunc::Var => "Var",
|
||||
|
||||
@@ -154,7 +154,9 @@ mod tests {
|
||||
assert_eq!(functions_in_formula("+SUM(1)"), ["SUM"]);
|
||||
assert_eq!(functions_in_formula("-ABS(A1)"), ["ABS"]);
|
||||
assert!(functions_in_formula("-5").is_empty() && functions_in_formula("+1e3").is_empty(), "numbers");
|
||||
assert!(functions_in_formula("+").is_empty() && functions_in_formula("- SUM(1)").is_empty(), "not formulas");
|
||||
assert!(functions_in_formula("+").is_empty() && functions_in_formula("--").is_empty(), "not formulas");
|
||||
// A sign before a space still starts a formula, as Excel takes `- SUM(1)` (#2023).
|
||||
assert_eq!(functions_in_formula("- SUM(1)"), ["SUM"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -531,7 +531,7 @@ fn edit_parts(bytes: &[u8], mut edit: impl FnMut(&str, String) -> String) -> Vec
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..zip.len() {
|
||||
let mut part = zip.by_index(i).unwrap();
|
||||
let name = part.name().to_string();
|
||||
let name = part.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
part.read_to_end(&mut data).unwrap();
|
||||
let data = match String::from_utf8(data) {
|
||||
|
||||
@@ -252,6 +252,53 @@ fn chart_series_follow_cut_moves_renames_and_sheet_deletes() {
|
||||
assert_eq!(values(&s), "Inputs!$A$1:$A$3");
|
||||
}
|
||||
|
||||
/// A series name that is a bare word is a label, as a chart reads it: renaming a table of that
|
||||
/// name leaves it be, while a series named by a defined name follows the name's rename.
|
||||
#[test]
|
||||
fn chart_series_names_follow_names_but_not_labels() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["v"], [5], [2]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A3", "name": "Sales"})).unwrap();
|
||||
s.execute("formulas.defineName", json!({"name": "Title", "refersTo": "=Sheet1!$A$1"})).unwrap();
|
||||
let chart = id_of(&s.execute("insert.chart", json!({"range": "A2:A3", "type": "column"})).unwrap(), "chart");
|
||||
let set = |s: &mut Session, label: &str, named: &str| {
|
||||
let ch = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap();
|
||||
ch.series.truncate(1);
|
||||
let mut second = ch.series[0].clone();
|
||||
ch.series[0].name = Some(label.into());
|
||||
second.name = Some(named.into());
|
||||
ch.series.push(second);
|
||||
};
|
||||
let names = |s: &Session| -> Vec<String> {
|
||||
sheet(s, 0).charts.iter().find(|c| c.id == chart).map(|c| c.series.iter().filter_map(|se| se.name.clone()).collect()).unwrap_or_default()
|
||||
};
|
||||
// A name another sheet holds isn't one this chart sees.
|
||||
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
s.execute("formulas.defineName", json!({"name": "Sales", "refersTo": "=Two!$A$1", "scope": "Two"})).unwrap();
|
||||
set(&mut s, "Sales", "Title");
|
||||
s.execute("table.rename", json!({"table": "Sales", "name": "Revenue"})).unwrap();
|
||||
assert_eq!(names(&s), ["Sales", "Title"], "a label isn't the table");
|
||||
s.execute("formulas.defineName", json!({"name": "Heading", "refersTo": "=Sheet1!$A$1", "oldName": "Title"})).unwrap();
|
||||
assert_eq!(names(&s), ["Sales", "Heading"], "a defined name follows its rename");
|
||||
// A label shaped like a cell is a label too.
|
||||
set(&mut s, "Q1", "Sheet1!$A$1");
|
||||
s.execute("home.insertRows", json!({"rows": "1:1", "sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(names(&s), ["Q1", "Sheet1!$A$2"]);
|
||||
}
|
||||
|
||||
/// A sheet may be named `#REF!`: a chart's source on it is not taken for one that's gone.
|
||||
#[test]
|
||||
fn a_chart_source_on_a_sheet_named_ref_error_is_kept() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[3], [5]]})).unwrap();
|
||||
s.execute("insert.chart", json!({"range": "A1:A2", "type": "column"})).unwrap();
|
||||
s.execute("sheet.rename", json!({"sheet": 0, "name": "#REF!"})).unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("sheet.rename", json!({"sheet": "Other", "name": "Else"})).unwrap();
|
||||
let source = sheet(&s, s.doc().unwrap().wb.sheet_index("#REF!").unwrap()).charts[0].source.clone();
|
||||
assert_eq!(source.as_deref(), Some("'#REF!'!A1:A2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_sheet_gives_its_objects_fresh_ids() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -531,6 +531,33 @@ fn python_code_with_an_empty_value_counts_as_content() {
|
||||
assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array")));
|
||||
}
|
||||
|
||||
/// Renaming a defined name or a table renames it in Python cells' `xl()` references too.
|
||||
#[test]
|
||||
fn xl_references_follow_name_and_table_renames() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1:B3", "values": [["k", "v"], ["a", 1], ["b", 2]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:B3"})).unwrap();
|
||||
let table = s.doc().unwrap().wb.sheets[0].tables[0].name.clone();
|
||||
s.execute("formulas.defineName", json!({"name": "Opts", "refersTo": "=Sheet1!$A$2:$A$3"})).unwrap();
|
||||
plant(&mut s, 0, "E1", &format!("a = xl(\"Opts\")\nb = xl(\"{table}[v]\")"));
|
||||
s.execute("formulas.defineName", json!({"name": "Choices", "oldName": "Opts", "refersTo": "=Sheet1!$A$2:$A$3"})).unwrap();
|
||||
assert_eq!(code(&s, 0, "E1").as_deref(), Some(format!("a = xl(\"Choices\")\nb = xl(\"{table}[v]\")").as_str()));
|
||||
s.execute("table.rename", json!({"table": table, "name": "Data"})).unwrap();
|
||||
assert_eq!(code(&s, 0, "E1").as_deref(), Some("a = xl(\"Choices\")\nb = xl(\"Data[v]\")"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_python_cell_is_not_a_trend_source() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "2"})).unwrap();
|
||||
plant(&mut s, 0, "A1", "1");
|
||||
let offered = |s: &Session, growth: bool| {
|
||||
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
|
||||
crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r("A1:A2"), r("A1:A5"), growth)
|
||||
};
|
||||
assert!(!offered(&s, false) && !offered(&s, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_a_link_without_text_preserves_an_empty_python_cell() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -56,7 +56,7 @@ fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, &
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
if let Ok(text) = std::str::from_utf8(&data) {
|
||||
@@ -250,7 +250,7 @@ fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let entry = f.name().to_string();
|
||||
let entry = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
let options = zip::write::SimpleFileOptions::default();
|
||||
|
||||
Reference in New Issue
Block a user