Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor 6ec4034b26 fix(xlsx): retain visible text in rejected Office Math boxes 2026-11-18 22:06:41 -05:00
Dylan M. Taylor 72f11bbacb fix(xlsx): preserve OMML fallback and bound conversion 2026-11-18 21:49:15 -05:00
Dylan M. Taylor 5cbe45d16e Cut over xlsx omml to craft-math (#4515)
* Cut over xlsx omml to craft-math (storytold/craft-libs#778)

* fix(omml): preserve opposite-side brace limit placement
2026-11-18 21:41:12 -05:00
5514a3a099 xlsx: fix main after the ODS cutover (clippy, empty first sheet, values, package checks) (#4518)
* xlsx: clear the two clippy errors the ODS cutover left on main

SheetNames::insert lost its only caller when the ODS reader moved to
craft-ods, and craft_ods::Value::Text already holds an Arc<str>.

* xlsx: ODS import keeps only the ODS tables, with unique valid names

The craft-ods cutover (#4513) built the workbook with Workbook::new(),
which already holds an empty Sheet1, and appended the ODS tables after
it. Opening an ODS file therefore showed an empty first sheet, and
ods_import_keeps_cached_values_and_reports_limits (plus the reader's
own sheets[0] tests) failed. It also stopped making sheet names unique
and valid, so two tables named Data and data became two sheets with
clashing names.

Clear the default sheet as the XLSX, XLS and XLSB readers do, and name
sheets through SheetNames again, as the reader did before the cutover.
That restores SheetNames::insert, which the previous commit removed
while it was unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* xlsx: ODS import keeps unreadable values as text and the exact mimetype check

Three more behaviours the craft-ods cutover (#4513) dropped, each
covered by an ods_tests case that has failed since:

- A cell whose typed value cannot be read (an unparsable number or
  date, a calcext error cache, a formula without a result) was skipped
  or marked unavailable. It keeps its displayed text again, else its
  raw value, with the same warning as before.
- Number formats are the old ones again: [h]:mm:ss.000 for durations
  and yyyy-mm-dd hh:mm:ss.000 for dates with a time. They are applied
  only when the typed value was read.
- read_ods checks the exact mimetype first, as sniff does; craft-ods
  alone accepted one with a trailing space.

The encryption case now writes its encryption-data inside the
content.xml file entry, where LibreOffice puts it and where craft-odf
looks for it. A bare one under the manifest root encrypts nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:10:52 +07:00
MaciekandMaciej Malinowski 42acfafcd3 Find and Replace: Undo and Redo reach the sheet while the dialog is open (#2140)
* Find and Replace: Undo and Redo reach the sheet while the dialog is open

Ctrl+Z after Replace All did nothing until the dialog was closed: the open
dialog kept the keyboard from the grid. The dialog now undoes and redoes
the workbook itself unless a text box has focus (there the shortcuts edit
the typed text).

* Find and Replace: Undo and Redo use the sheet's shortcut table

The dialog passed hard-coded keys to edit.undo and edit.redo. It now hands
Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Cmd/Ctrl+Y to ribbon::shortcut, the table
the grid uses, so the dialog and the sheet keep the same bindings. The test
also covers the Mac Redo shortcut (Cmd+Shift+Z).

* fix(find): allow workbook undo when a dialog button has focus

Reserve Undo/Redo for text editing only while a text edit has focus. The regression reproduces the failure with keyboard focus on Replace All, checks both Redo shortcuts, and verifies text-field Undo leaves the sheet unchanged. Regression failed before the fix and passes now. Validation: 1143 UI integration tests pass; only existing missing-glyph failures U+1E9E and U+1EBB remain. WASM, assets, layers and generators pass. Full CI reaches the unchanged Windows CLI clippy::only_used_in_recursion failure in apps/gridcraft-cli/src/check.rs.

* fix(find): block workbook shortcuts behind a modal message

Check app.message before dispatching workbook Undo/Redo. Regression uses an empty Replace All search to open the real error, covers all three shortcuts, and checks Redo after dismissal. Extend text-focus coverage to type and undo actual text. Modal regression fails before the guard and passes after it. Validation: 1144 integration tests pass; two existing missing-glyph failures remain. WASM, assets and layers pass. Full CI still stops at the unchanged Windows CLI clippy::only_used_in_recursion warning.

---------

Co-authored-by: Maciej Malinowski <231036771+webglobecontact-ui@users.noreply.github.com>
2026-11-19 08:37:18 +07:00
Dylan M. Taylor 83ab01678a Cut over gridcraft-xlsx ODS reader to craft-ods (#4513) 2026-11-18 17:22:18 -05:00
11 changed files with 550 additions and 1158 deletions
Generated
+73 -8
View File
@@ -937,7 +937,7 @@ name = "craft-drawingml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"kurbo",
"log",
"serde",
@@ -981,6 +981,44 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-math"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"serde",
]
[[package]]
name = "craft-odf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"aes",
"base64 0.23.1",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"flate2",
"getrandom 0.3.4",
"hmac",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
"zeroize",
]
[[package]]
name = "craft-ods"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-odf",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-offcrypto"
version = "0.1.0"
@@ -989,7 +1027,7 @@ dependencies = [
"aes",
"base64 0.23.1",
"craft-cfb",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"getrandom 0.3.4",
"hmac",
"sha1 0.11.0",
@@ -1003,8 +1041,8 @@ name = "craft-opc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-xml",
"craft-zip",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"log",
"thiserror 2.0.21",
]
@@ -1028,6 +1066,11 @@ dependencies = [
"winsafe",
]
[[package]]
name = "craft-sheet"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
[[package]]
name = "craft-sheet"
version = "0.1.0"
@@ -1136,7 +1179,7 @@ version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"craft-cfb",
"craft-sheet",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"md-5",
"miniz_oxide 0.9.1",
"sha1 0.10.7",
@@ -1150,8 +1193,18 @@ source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d
dependencies = [
"craft-drawingml",
"craft-opc",
"craft-sheet",
"craft-xml",
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
@@ -1164,6 +1217,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.0",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
@@ -2405,11 +2468,13 @@ version = "0.19.1"
dependencies = [
"craft-cfb",
"craft-csv",
"craft-math",
"craft-ods",
"craft-offcrypto",
"craft-opc",
"craft-xls",
"craft-xlsx",
"craft-xml",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
"gridcraft-core",
"gridcraft-formula",
"gridcraft-functions",
+2
View File
@@ -37,11 +37,13 @@ craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
+15
View File
@@ -1,8 +1,23 @@
use egui::Modifiers;
use super::show::ok_cancel;
use super::{Dialog, Json, Key, SheetApp, json};
/// Draws the Find/Replace form with case, whole-cell and workbook options, requests field focus once, and runs find/replace with the current parameters.
pub(super) fn find(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog) {
// The dialog stays open over the sheet, so Undo and Redo reach the workbook (a Replace All
// is undone without closing it first); inside a text box they edit the typed text instead.
// A modal message blocks workbook shortcuts; otherwise use the grid's own shortcut table.
if app.message.is_none() && !ui.ctx().text_edit_focused() {
let pressed = ui.input_mut(|i| {
[(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z), (Modifiers::COMMAND, Key::Z), (Modifiers::COMMAND, Key::Y)]
.into_iter()
.find(|&(m, key)| i.consume_key(m, key))
});
if let Some((m, key)) = pressed {
crate::ribbon::shortcut(app, key, m);
}
}
ui.horizontal(|ui| {
for tab in ["Find", "Replace"] {
if ui.selectable_label(d.tab == tab, tab).clicked() {
+71
View File
@@ -336,6 +336,77 @@ fn arrows_escape_and_undo() {
assert_eq!(value(&h, "B2"), Value::Empty);
}
#[test]
fn undo_and_redo_reach_the_sheet_while_find_and_replace_is_open() {
let mut h = harness(blank());
for t in ["x1", "x2"] {
text(&mut h, t);
key(&mut h, Key::Enter, Modifiers::NONE);
}
h.state_mut().open_dialog("find", json!({"replace": true}));
h.run_steps(3);
if let Some(d) = h.state_mut().dialog.as_mut() {
d.values.insert("what".into(), json!("x"));
d.values.insert("with".into(), json!("y"));
}
h.run_steps(2);
h.get_by_label("Replace All").click();
h.run_steps(3);
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")));
// Keyboard focus on a button must not reserve Undo/Redo for text editing.
h.get_by_label("Replace All").focus();
h.run_steps(2);
assert!(h.ctx.egui_wants_keyboard_input());
assert!(!h.ctx.text_edit_focused());
key(&mut h, Key::Z, Modifiers::COMMAND);
assert!(h.state().dialog.is_some(), "the dialog stays open");
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("x1"), Value::from("x2")), "one Undo takes back the whole Replace All");
key(&mut h, Key::Y, Modifiers::COMMAND);
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")));
// The Mac Redo shortcut works too, as it does on the sheet.
key(&mut h, Key::Z, Modifiers::COMMAND);
assert_eq!(value(&h, "A1"), Value::from("x1"));
key(&mut h, Key::Z, Modifiers::COMMAND | Modifiers::SHIFT);
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")));
assert!(h.state().dialog.is_some(), "the dialog is still open");
h.get_by_label("Find what:").focus();
h.run_steps(2);
assert!(h.ctx.text_edit_focused());
let before = h.state().dialog.as_ref().unwrap().values.get("what").cloned();
h.input_mut().events.push(Event::Text("extra".into()));
h.run_steps(2);
assert_ne!(h.state().dialog.as_ref().unwrap().values.get("what"), before.as_ref());
key(&mut h, Key::Z, Modifiers::COMMAND);
assert_eq!(h.state().dialog.as_ref().unwrap().values.get("what"), before.as_ref(), "Undo restores the Find field");
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")), "text-field Undo leaves the sheet alone");
}
#[test]
fn find_message_blocks_workbook_undo_and_redo() {
let mut session = blank();
session.execute("cell.set", json!({"cell": "A1", "input": "first"})).unwrap();
session.execute("cell.set", json!({"cell": "A1", "input": "second"})).unwrap();
session.execute("edit.undo", json!({})).unwrap();
let mut h = harness(session);
h.state_mut().open_dialog("find", json!({"replace": true}));
h.run_steps(3);
// An empty search raises the real modal error over Find and Replace.
h.get_by_label("Replace All").click();
h.run_steps(3);
assert!(h.state().message.is_some());
assert!(!h.ctx.text_edit_focused());
for (key_code, modifiers) in [(Key::Z, Modifiers::COMMAND), (Key::Y, Modifiers::COMMAND), (Key::Z, Modifiers::COMMAND | Modifiers::SHIFT)] {
key(&mut h, key_code, modifiers);
assert_eq!(value(&h, "A1"), Value::from("first"), "the message blocks workbook shortcuts");
assert!(h.state().message.is_some());
}
h.state_mut().message = None;
h.run_steps(2);
h.get_by_label("Replace All").focus();
h.run_steps(2);
key(&mut h, Key::Y, Modifiers::COMMAND);
assert_eq!(value(&h, "A1"), Value::from("second"), "Redo works again after dismissing the message");
}
#[test]
fn shift_arrows_in_point_mode_extend_from_the_pointed_cell() {
let mut s = blank();
+2
View File
@@ -20,6 +20,8 @@ gridcraft-math = { workspace = true }
gridcraft-model = { workspace = true }
craft-cfb = { workspace = true }
craft-csv = { workspace = true }
craft-math = { workspace = true }
craft-ods = { workspace = true }
craft-offcrypto = { workspace = true }
craft-opc = { workspace = true }
craft-xls = { workspace = true }
+70 -1
View File
@@ -271,7 +271,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
}
let fill = sp.child("solidFill").and_then(dml_color).unwrap_or_default();
let line = ln.and_then(|l| l.child("solidFill")).and_then(dml_color).unwrap_or_default();
let text = obj.child("txBody").map(body_text).unwrap_or_default();
let text = tb.map(|tb| if has_math { math_body_text(tb) } else { body_text(tb) }).unwrap_or_default();
let mut format = read_text_format(obj.child("txBody"));
format.no_line = ln.is_some_and(|l| l.child("noFill").is_some());
Some(Shape { id: 0, kind, anchor, fill, line, text, format, math: Default::default() })
@@ -411,6 +411,55 @@ fn body_text(tb: &El) -> String {
tb.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::<String>()).collect::<Vec<_>>().join("\n")
}
/// A rejected Office Math box still needs its visible run text. Do not reinterpret
/// that text as LaTeX. Keep traversal and output bounded independently of conversion.
fn math_body_text(tb: &El) -> String {
const MAX_BYTES: usize = 1 << 20;
fn append(text: &str, out: &mut String) {
let mut end = text.len().min(MAX_BYTES.saturating_sub(out.len()));
while !text.is_char_boundary(end) {
end -= 1;
}
out.push_str(&text[..end]);
}
fn visit(e: &El, depth: usize, left: &mut usize, out: &mut String) {
if depth > 64 || *left == 0 || out.len() >= MAX_BYTES {
return;
}
*left -= 1;
if e.name.ends_with("Pr") {
return;
}
if e.name == "t" {
append(&e.text, out);
} else if e.name == "AlternateContent" {
// Choice and fallback describe the same content, not two text runs.
if let Some(c) = e.child("Fallback").or_else(|| e.child("Choice")) {
visit(c, depth + 1, left, out);
}
} else {
for child in &e.children {
visit(child, depth + 1, left, out);
if *left == 0 || out.len() >= MAX_BYTES {
break;
}
}
}
}
let mut out = String::new();
let mut left = 100_000;
for (i, p) in tb.kids("p").enumerate() {
if left == 0 || out.len() >= MAX_BYTES {
break;
}
if i > 0 {
append("\n", &mut out);
}
visit(p, 0, &mut left, &mut out);
}
out
}
/// Whether a body without Office Math still holds the text the writer wrote for `src`: the same
/// paragraphs, read back through the same parser. The marker joins run text across paragraphs,
/// so a paragraph split that changes no character passes it; the text does not.
@@ -691,3 +740,23 @@ pub fn image_content_type(ext: &str) -> &'static str {
_ => "image/png",
}
}
#[cfg(test)]
mod math_fallback_tests {
use super::*;
#[test]
fn fallback_uses_one_alternative_and_ignores_properties() {
let tb = crate::xml::parse(br#"<txBody><p><rPr><t>hidden</t></rPr><r><t>before </t></r><AlternateContent><Choice><r><t>choice</t></r></Choice><Fallback><r><t>fallback</t></r></Fallback></AlternateContent><r><t> after</t></r></p><p><r><t>next</t></r></p></txBody>"#).unwrap();
assert_eq!(math_body_text(&tb), "before fallback after\nnext");
}
#[test]
fn fallback_output_cap_keeps_utf8_intact() {
let xml = format!("<txBody><p><r><t>a{}</t></r></p></txBody>", "λ".repeat(1 << 19));
let tb = crate::xml::parse(xml.as_bytes()).unwrap();
let text = math_body_text(&tb);
assert_eq!(text.len(), (1 << 20) - 1);
assert!(text.starts_with('a') && text.ends_with('λ'));
}
}
+96 -628
View File
@@ -1,32 +1,17 @@
//! Data-only OpenDocument Spreadsheet import. Formula caches become constants; styles and
//! other ODF features are deliberately not translated. All fixtures are authored in Rust.
//! Format reference: ODF 1.3, part 3, sections 6.1 and 9.1:
//! <https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part3-schema/OpenDocument-v1.3-os-part3-schema.html>.
//! Data-only OpenDocument Spreadsheet import backed by `craft-ods`.
//! Formula caches become constants; styles and other ODF features are deliberately not translated.
use std::io::{Cursor, Read};
use std::sync::Arc;
use gridcraft_core::date::{days_in_month, serial_from_ymd};
use gridcraft_core::{CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRef, Value};
use gridcraft_core::{CellError, CellRef, RangeRef, Value};
use gridcraft_model::{Cell, NumFmt, Sheet, StyleId, Workbook};
use quick_xml::NsReader;
use quick_xml::XmlVersion;
use quick_xml::events::{BytesStart, Event};
use quick_xml::name::ResolveResult;
use crate::package::{MAX_ENTRIES, Package};
use crate::package::MAX_ENTRIES;
use crate::read::SheetNames;
use crate::{IoError, ReadReport};
const MIME: &[u8] = b"application/vnd.oasis.opendocument.spreadsheet";
const OFFICE: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:office:1.0";
const TABLE: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:table:1.0";
const TEXT: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:text:1.0";
const CALC_EXT: &[u8] = b"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0";
const MANIFEST: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0";
const MAX_CELLS: u64 = 1_000_000;
const MAX_MERGES: u64 = 100_000;
const MAX_CELL_TEXT: usize = 1024 * 1024;
const MAX_TEXT: u64 = 64 * 1024 * 1024;
const MAX_SHEETS: usize = 1024;
/// Reads only the small, exact mimetype entry, including when the ZIP uses compression.
@@ -48,637 +33,120 @@ pub(crate) fn has_mimetype(bytes: &[u8]) -> bool {
/// imported as constants, so editing their inputs does not recalculate the original formula.
/// Always inspect the returned warnings. Saving to ODS is not supported.
pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
let mut package = Package::open(bytes)?;
// The exact mimetype, as `sniff` requires: craft-ods alone accepts some near misses.
if !has_mimetype(bytes) {
return Err(IoError::Format("missing or invalid ODS mimetype".into()));
}
if let Some(manifest) = package.read("META-INF/manifest.xml")? {
check_manifest(&manifest)?;
}
let content = package.read("content.xml")?.ok_or_else(|| IoError::Format("ODS content.xml is missing".into()))?;
let mut import = Import::new();
import.parse(&content)?;
if import.wb.sheets.is_empty() {
let book = craft_ods::read(bytes, &craft_ods::Options::default()).map_err(map_error)?;
if book.sheets.is_empty() {
return Err(IoError::Format("ODS contains no worksheets".into()));
}
Ok((import.wb, import.report))
}
if book.sheets.len() > MAX_SHEETS {
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
}
fn is_ns(ns: ResolveResult<'_>, expected: &[u8]) -> bool {
matches!(ns, ResolveResult::Bound(n) if n.as_ref() == expected)
}
// `Workbook::new` starts with an empty Sheet1; the ODS tables are the only sheets.
let mut wb = Workbook::new();
wb.sheets.clear();
let mut names = SheetNames::default();
let mut report = ReadReport::default();
report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported.");
fn attr(reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>, ns: &[u8], name: &[u8]) -> Result<Option<String>, IoError> {
let mut found = None;
for a in e.attributes() {
let a = a.map_err(|e| IoError::Xml(e.to_string()))?;
let (resolved, local) = reader.resolver_mut().resolve_attribute(a.key);
if is_ns(resolved, ns) && local.as_ref() == name {
let value = a.normalized_value(XmlVersion::Explicit1_0).map_err(|e| IoError::Xml(e.to_string()))?;
if value.len() > MAX_CELL_TEXT {
return Err(IoError::TooLarge("ODS attribute exceeds 1 MiB".into()));
}
found = Some(value.into_owned());
let mut warned_rename = false;
let mut warned_unavailable = false;
for src_sheet in book.sheets {
let mut name = names.unique(src_sheet.name.trim_matches('\''), wb.sheets.len());
if wb.check_sheet_name(&name, None).is_err() {
name = wb.next_sheet_name();
names.insert(&name);
}
}
Ok(found)
}
fn positive(value: Option<String>, default: u32, limit: u32) -> Result<u32, IoError> {
let n = match value {
Some(s) => s.parse::<u32>().map_err(|_| IoError::Format("invalid ODS repeat or span count".into()))?,
None => default,
};
if n == 0 || n > limit {
return Err(IoError::TooLarge("ODS repeat or span exceeds worksheet bounds".into()));
}
Ok(n)
}
fn xml_error(e: impl std::fmt::Display) -> IoError {
IoError::Xml(format!("ODS: {e}"))
}
fn check_manifest(bytes: &[u8]) -> Result<(), IoError> {
let mut reader = NsReader::from_reader(bytes);
let mut depth = 0usize;
let mut root_seen = false;
loop {
let event = reader.read_event().map_err(xml_error)?;
match &event {
Event::Start(e) | Event::Empty(e) => {
let (ns, name) = reader.resolver_mut().resolve_element(e.name());
if is_ns(ns.clone(), MANIFEST) && name.as_ref() == b"encryption-data" {
return Err(IoError::Format("encrypted ODS files are not supported".into()));
}
if depth == 0 {
if root_seen || !is_ns(ns, MANIFEST) || name.as_ref() != b"manifest" {
return Err(xml_error("expected one manifest:manifest root"));
}
root_seen = true;
}
if matches!(event, Event::Start(_)) {
depth += 1;
if depth > crate::xml::MAX_DEPTH {
return Err(xml_error("manifest nested too deeply"));
}
}
}
Event::End(_) => depth = depth.checked_sub(1).ok_or_else(|| xml_error("unexpected manifest closing element"))?,
Event::DocType(_) => return Err(xml_error("DOCTYPE is not supported")),
Event::Eof => break,
_ => {}
let mut sheet = Sheet::new(name);
if !warned_rename && sheet.name != src_sheet.name {
warned_rename = true;
report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names.");
}
}
if !root_seen || depth != 0 {
return Err(xml_error("incomplete manifest"));
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tag {
Document,
Body,
Spreadsheet,
Table,
Rows,
Row,
Cell,
Covered,
Paragraph,
Inline,
Space,
Tab,
Break,
Other,
}
fn tag(reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>) -> Tag {
let (ns, name) = reader.resolver_mut().resolve_element(e.name());
let local = name.as_ref();
if is_ns(ns.clone(), OFFICE) {
return match local {
b"document-content" => Tag::Document,
b"body" => Tag::Body,
b"spreadsheet" => Tag::Spreadsheet,
_ => Tag::Other,
};
}
if is_ns(ns.clone(), TABLE) {
return match local {
b"table" => Tag::Table,
b"table-row-group" | b"table-header-rows" | b"table-rows" => Tag::Rows,
b"table-row" => Tag::Row,
b"table-cell" => Tag::Cell,
b"covered-table-cell" => Tag::Covered,
_ => Tag::Other,
};
}
if is_ns(ns, TEXT) {
return match local {
b"p" | b"h" => Tag::Paragraph,
b"span" | b"a" | b"meta" | b"meta-field" | b"ruby" | b"ruby-base" => Tag::Inline,
b"s" => Tag::Space,
b"tab" => Tag::Tab,
b"line-break" => Tag::Break,
_ => Tag::Other,
};
}
Tag::Other
}
struct SheetDraft {
sheet: Sheet,
depth: usize,
row: u32,
}
struct RowDraft {
depth: usize,
repeat: u32,
col: u32,
cells: Vec<RepeatedCell>,
}
struct RepeatedCell {
col: u32,
repeat: u32,
width: u32,
height: u32,
cell: Cell,
}
struct CellDraft {
depth: usize,
repeat: u32,
width: u32,
height: u32,
covered: bool,
kind: Option<String>,
raw: Option<String>,
formula: bool,
text: String,
paragraph: Option<usize>,
paragraphs: usize,
paragraph_started: bool,
pending_space: bool,
}
struct Import {
wb: Workbook,
report: ReadReport,
stack: Vec<Tag>,
sheet: Option<SheetDraft>,
row: Option<RowDraft>,
cell: Option<CellDraft>,
cells: u64,
merges: u64,
text: u64,
formats: Vec<(&'static str, StyleId)>,
spreadsheet_seen: bool,
names: crate::read::SheetNames,
}
impl Import {
fn new() -> Self {
let mut wb = Workbook::new();
wb.sheets.clear();
let mut report = ReadReport::default();
report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported.");
Self {
wb,
report,
stack: vec![],
sheet: None,
row: None,
cell: None,
cells: 0,
merges: 0,
text: 0,
formats: vec![],
spreadsheet_seen: false,
names: Default::default(),
}
}
fn parse(&mut self, bytes: &[u8]) -> Result<(), IoError> {
let mut reader = NsReader::from_reader(bytes);
let mut root_seen = false;
loop {
match reader.read_event().map_err(xml_error)? {
Event::Start(e) => {
if self.stack.len() >= crate::xml::MAX_DEPTH {
return Err(xml_error("XML nested too deeply"));
}
if self.stack.is_empty() {
if root_seen || tag(&mut reader, &e) != Tag::Document {
return Err(xml_error("expected one office:document-content root"));
}
root_seen = true;
}
self.start(&mut reader, &e)?;
for (coord, src_cell) in src_sheet.cells {
// A typed value that cannot be read (an unparsable number or date, an error cache,
// a formula without a result) keeps what the cell showed, else its raw value.
let Some(value) = src_cell.value().map(map_value) else {
if !warned_unavailable {
warned_unavailable = true;
report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result].");
}
Event::Empty(e) => {
if self.stack.is_empty() {
return Err(xml_error("expected office:document-content with a spreadsheet"));
}
self.start(&mut reader, &e)?;
self.end()?;
}
Event::End(_) => self.end()?,
Event::Text(t) => {
let text = t.xml_content(XmlVersion::Explicit1_0).map_err(xml_error)?;
if self.stack.is_empty() && !text.trim().is_empty() {
return Err(xml_error("text outside the document"));
}
self.append(&text)?;
}
Event::CData(t) => self.append(&t.decode().map_err(xml_error)?)?,
Event::GeneralRef(r) => {
let ch = match r.resolve_char_ref().map_err(xml_error)? {
Some(c) => c,
None => match &*r {
b"amp" => '&',
b"lt" => '<',
b"gt" => '>',
b"apos" => '\'',
b"quot" => '"',
_ => return Err(xml_error("unsupported XML entity")),
},
};
self.append(ch.encode_utf8(&mut [0; 4]))?;
}
Event::DocType(_) => return Err(xml_error("DOCTYPE is not supported")),
Event::Eof => break,
_ => {}
}
}
if !root_seen || !self.stack.is_empty() || !self.spreadsheet_seen {
return Err(xml_error("incomplete ODS document"));
}
Ok(())
}
fn start(&mut self, reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>) -> Result<(), IoError> {
let t = tag(reader, e);
let depth = self.stack.len();
match t {
Tag::Spreadsheet if self.stack == [Tag::Document, Tag::Body] => {
if self.spreadsheet_seen {
return Err(xml_error("multiple spreadsheets in one document"));
}
self.spreadsheet_seen = true;
}
Tag::Table if self.stack == [Tag::Document, Tag::Body, Tag::Spreadsheet] => {
if self.wb.sheets.len() >= MAX_SHEETS {
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
}
let original = attr(reader, e, TABLE, b"name")?.unwrap_or_default();
let mut name = self.names.unique(original.trim_matches('\''), self.wb.sheets.len());
if self.wb.check_sheet_name(&name, None).is_err() {
name = self.wb.next_sheet_name();
self.names.insert(&name);
}
if name != original {
self.report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names.");
}
self.sheet = Some(SheetDraft { sheet: Sheet::new(name), depth, row: 0 });
}
Tag::Row if self.sheet.as_ref().is_some_and(|s| self.stack.get(s.depth + 1..).is_some_and(|p| p.iter().all(|t| *t == Tag::Rows))) => {
self.row =
Some(RowDraft { depth, repeat: positive(attr(reader, e, TABLE, b"number-rows-repeated")?, 1, u32::MAX)?, col: 0, cells: vec![] });
}
Tag::Cell | Tag::Covered if self.row.as_ref().is_some_and(|r| depth == r.depth + 1) => {
let kind = if attr(reader, e, CALC_EXT, b"value-type")?.as_deref() == Some("error") {
Some("error".into())
let text = if !src_cell.text.is_empty() {
src_cell.text.as_str()
} else if let Some(raw) = src_cell.raw.as_deref() {
raw
} else if src_cell.formula.is_some() {
"[Unavailable ODS formula result]"
} else {
attr(reader, e, OFFICE, b"value-type")?
"[Unsupported ODS value]"
};
let key: &[u8] = match kind.as_deref() {
Some("boolean") => b"boolean-value",
Some("date") => b"date-value",
Some("time") => b"time-value",
Some("string") => b"string-value",
_ => b"value",
};
self.cell = Some(CellDraft {
depth,
repeat: positive(attr(reader, e, TABLE, b"number-columns-repeated")?, 1, u32::MAX)?,
width: positive(attr(reader, e, TABLE, b"number-columns-spanned")?, 1, MAX_COLS)?,
height: positive(attr(reader, e, TABLE, b"number-rows-spanned")?, 1, MAX_ROWS)?,
covered: t == Tag::Covered,
kind,
raw: attr(reader, e, OFFICE, key)?,
formula: attr(reader, e, TABLE, b"formula")?.is_some(),
text: String::new(),
paragraph: None,
paragraphs: 0,
paragraph_started: false,
pending_space: false,
});
}
Tag::Paragraph if self.cell.as_ref().is_some_and(|c| depth == c.depth + 1) => {
if let Some(cell) = self.cell.as_mut() {
if cell.paragraphs > 0 {
push_text(&mut cell.text, "\n")?;
}
cell.paragraph = Some(depth);
cell.paragraphs += 1;
cell.paragraph_started = false;
cell.pending_space = false;
}
}
Tag::Space | Tag::Tab | Tag::Break if self.captures_text() => {
let count = if t == Tag::Space {
let n = attr(reader, e, TEXT, b"c")?.map(|s| s.parse::<u32>()).transpose().map_err(xml_error)?.unwrap_or(1);
if n as usize > MAX_CELL_TEXT {
return Err(IoError::TooLarge("ODS repeated spaces exceed 1 MiB".into()));
}
n
} else {
1
};
let value = match t {
Tag::Space => " ",
Tag::Tab => "\t",
_ => "\n",
};
if let Some(cell) = self.cell.as_mut() {
if cell.pending_space {
push_text(&mut cell.text, " ")?;
cell.pending_space = false;
}
cell.paragraph_started = true;
if cell.text.len().saturating_add(count as usize) > MAX_CELL_TEXT {
return Err(IoError::TooLarge("ODS cell text exceeds 1 MiB".into()));
}
for _ in 0..count {
cell.text.push_str(value);
}
}
}
_ => {}
}
self.stack.push(t);
Ok(())
}
sheet.set_cell(CellRef::new(coord.row, coord.col), Cell::styled(Value::Text(Arc::from(text)), StyleId::DEFAULT));
continue;
};
fn captures_text(&self) -> bool {
self.cell
.as_ref()
.and_then(|c| c.paragraph)
.is_some_and(|depth| self.stack.get(depth..).is_some_and(|p| p.iter().all(|t| matches!(t, Tag::Paragraph | Tag::Inline))))
}
fn append(&mut self, text: &str) -> Result<(), IoError> {
if self.captures_text()
&& let Some(cell) = self.cell.as_mut()
{
// ODF 1.3 section 6.1.2: collapse XML whitespace across inline runs,
// but expand explicit text:s/tab/line-break elements separately.
for ch in text.chars() {
if matches!(ch, ' ' | '\t' | '\n' | '\r') {
cell.pending_space = cell.paragraph_started;
} else {
if cell.pending_space {
push_text(&mut cell.text, " ")?;
cell.pending_space = false;
}
push_text(&mut cell.text, ch.encode_utf8(&mut [0; 4]))?;
cell.paragraph_started = true;
let format = match src_cell.value_type {
Some(craft_ods::ValueType::Date) => {
let with_time = src_cell.raw.as_deref().and_then(craft_ods::date_serial).is_some_and(|(_, time)| time);
Some(if with_time { "yyyy-mm-dd hh:mm:ss.000" } else { "yyyy-mm-dd" })
}
}
}
Ok(())
}
fn end(&mut self) -> Result<(), IoError> {
self.stack.pop().ok_or_else(|| xml_error("unexpected closing element"))?;
let depth = self.stack.len();
if let Some(cell) = self.cell.as_mut()
&& cell.paragraph == Some(depth)
{
cell.paragraph = None;
}
if self.cell.as_ref().is_some_and(|c| c.depth == depth) {
self.finish_cell()?;
}
if self.row.as_ref().is_some_and(|r| r.depth == depth) {
self.finish_row()?;
}
if self.sheet.as_ref().is_some_and(|s| s.depth == depth)
&& let Some(sheet) = self.sheet.take()
{
self.wb.sheets.push(Arc::new(sheet.sheet));
}
Ok(())
}
fn finish_cell(&mut self) -> Result<(), IoError> {
let Some(draft) = self.cell.take() else { return Ok(()) };
let cell = self.convert(&draft);
let (width, height) = if draft.covered { (1, 1) } else { (draft.width, draft.height) };
let Some(row) = self.row.as_mut() else { return Ok(()) };
let kept = !cell.is_blank() || width > 1 || height > 1;
// Writers pad rows with blank repeats up to their own (possibly wider) sheet edge;
// blank cells past ours carry no data, so clip them instead of rejecting the file.
let end = match row.col.checked_add(draft.repeat).filter(|n| *n <= MAX_COLS) {
Some(end) => end,
None if !kept => MAX_COLS,
None => return Err(IoError::TooLarge("ODS row exceeds worksheet width".into())),
};
if kept {
// Charge the text a row keeps before the row is done, so a row of many long cells is
// refused as it grows; finish_row charges the row's repeats beyond the first.
if let Value::Text(t) = &cell.value {
self.text = self.text.saturating_add(u64::from(draft.repeat).saturating_mul(t.len() as u64));
if self.text > MAX_TEXT {
return Err(IoError::TooLarge("ODS expands beyond the import limit (64 MiB of text)".into()));
}
}
row.cells.push(RepeatedCell { col: row.col, repeat: draft.repeat, width, height, cell });
}
row.col = end;
Ok(())
}
fn convert(&mut self, draft: &CellDraft) -> Cell {
let raw = draft.raw.as_deref();
let mut format = None;
let value = match draft.kind.as_deref() {
Some("float" | "percentage" | "currency") => raw.and_then(|s| s.parse::<f64>().ok()).filter(|n| n.is_finite()).map(|n| {
if draft.kind.as_deref() == Some("percentage") {
format = Some("0.00%");
}
Value::Number(n)
}),
Some("boolean") => match raw {
Some("true" | "1") => Some(Value::Bool(true)),
Some("false" | "0") => Some(Value::Bool(false)),
Some(craft_ods::ValueType::Time) => Some("[h]:mm:ss.000"),
Some(craft_ods::ValueType::Percentage) => Some("0.00%"),
Some(craft_ods::ValueType::Currency) => Some("#,##0.00"),
_ => None,
},
Some("string") if raw.is_some() || draft.paragraphs > 0 || !draft.formula => Some(Value::Text(Arc::from(raw.unwrap_or(&draft.text)))),
Some("void") if !draft.formula => Some(Value::Empty),
Some("date") => raw.and_then(parse_date).map(|(n, f)| {
format = Some(f);
Value::Number(n)
}),
Some("time") => raw.and_then(parse_duration).map(|n| {
format = Some("[h]:mm:ss.000");
Value::Number(n)
}),
None if !draft.formula => Some(if draft.text.is_empty() { Value::Empty } else { Value::Text(Arc::from(draft.text.as_str())) }),
_ => None,
};
let value = value.unwrap_or_else(|| {
self.report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result].");
let text = if !draft.text.is_empty() { draft.text.as_str() } else if let Some(raw) = raw { raw } else if draft.formula { "[Unavailable ODS formula result]" } else { "[Unsupported ODS value]" };
Value::Text(Arc::from(text))
});
let style = match format {
Some(code) => match self.formats.iter().find(|(f, _)| *f == code) {
Some((_, id)) => *id,
None => {
let id = self.wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
self.formats.push((code, id));
id
}
},
None => StyleId::DEFAULT,
};
Cell { style, ..Cell::value(value) }
};
let style_id = format.map_or(StyleId::DEFAULT, |code| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)));
let target_coord = CellRef::new(coord.row, coord.col);
sheet.set_cell(target_coord, Cell::styled(value, style_id));
}
for m in src_sheet.merges {
let range = RangeRef::new(CellRef::new(m.first.row, m.first.col), CellRef::new(m.last.row, m.last.col));
sheet.merges.push(range);
}
wb.sheets.push(Arc::new(sheet));
}
fn finish_row(&mut self) -> Result<(), IoError> {
let Some(row) = self.row.take() else { return Ok(()) };
let Some(sheet) = self.sheet.as_mut() else { return Ok(()) };
// Blank trailing row repeats past the sheet edge (e.g. from larger-sheet writers) are clipped.
let end = match sheet.row.checked_add(row.repeat).filter(|n| *n <= MAX_ROWS) {
Some(end) => end,
None if row.cells.is_empty() => MAX_ROWS,
None => return Err(IoError::TooLarge("ODS exceeds worksheet height".into())),
};
for entry in row.cells {
let count = u64::from(entry.repeat) * u64::from(row.repeat);
if !entry.cell.is_blank() {
self.cells = self.cells.saturating_add(count);
if let Value::Text(t) = &entry.cell.value {
let repeats = count.saturating_sub(u64::from(entry.repeat));
self.text = self.text.saturating_add(repeats.saturating_mul(t.len() as u64));
}
}
let merged = entry.width > 1 || entry.height > 1;
if merged {
self.merges = self.merges.saturating_add(count);
}
if self.cells > MAX_CELLS || self.merges > MAX_MERGES || self.text > MAX_TEXT {
return Err(IoError::TooLarge("ODS expands beyond the import limit (1 million cells, 100000 merges or 64 MiB of text)".into()));
}
let last_col = entry.col.checked_add(entry.repeat - 1).and_then(|c| c.checked_add(entry.width - 1));
let last_row = end.checked_add(entry.height - 1);
if last_col.is_none_or(|c| c >= MAX_COLS) || last_row.is_none_or(|r| r > MAX_ROWS) {
return Err(IoError::TooLarge("ODS merged cell exceeds worksheet bounds".into()));
}
if merged && ((entry.repeat > 1 && entry.width > 1) || (row.repeat > 1 && entry.height > 1)) {
return Err(IoError::Format("repeated ODS cells have overlapping merges".into()));
}
for r in sheet.row..end {
for c in entry.col..entry.col + entry.repeat {
let pos = CellRef::new(r, c);
if !entry.cell.is_blank() {
sheet.sheet.cells.set(pos, entry.cell.clone());
}
if merged {
sheet.sheet.merges.push(RangeRef::new(pos, CellRef::new(r + entry.height - 1, c + entry.width - 1)));
}
}
}
}
sheet.row = end;
Ok(())
Ok((wb, report))
}
fn map_error(e: craft_ods::Error) -> IoError {
match e {
craft_ods::Error::Encrypted => IoError::Format("encrypted ODS files are not supported".into()),
craft_ods::Error::Xml(msg) => IoError::Xml(format!("ODS: {msg}")),
craft_ods::Error::TooLarge(msg) => IoError::TooLarge(msg),
craft_ods::Error::Invalid(msg) => IoError::Format(msg),
other => IoError::Format(other.to_string()),
}
}
fn push_text(out: &mut String, text: &str) -> Result<(), IoError> {
if out.len().saturating_add(text.len()) > MAX_CELL_TEXT {
return Err(IoError::TooLarge("ODS cell text exceeds 1 MiB".into()));
fn map_value(v: craft_ods::Value) -> Value {
match v {
craft_ods::Value::Empty => Value::Empty,
craft_ods::Value::Number(n) => Value::Number(n),
craft_ods::Value::Text(s) => Value::Text(s),
craft_ods::Value::Bool(b) => Value::Bool(b),
craft_ods::Value::Error(e) => Value::Error(map_cell_error(e)),
}
out.push_str(text);
Ok(())
}
/// Support unzoned ISO calendar dates and times. A timezone, invalid date or out-of-range
/// calendar year remains text; never silently discard an offset or roll an invalid date.
fn parse_date(s: &str) -> Option<(f64, &'static str)> {
let (date, time) = s.split_once('T').map_or((s, None), |(d, t)| (d, Some(t)));
if date.len() != 10 || date.get(4..5)? != "-" || date.get(7..8)? != "-" {
return None;
fn map_cell_error(e: craft_ods::CellError) -> CellError {
match e {
craft_ods::CellError::Null => CellError::Null,
craft_ods::CellError::Div0 => CellError::Div0,
craft_ods::CellError::Value => CellError::Value,
craft_ods::CellError::Ref => CellError::Ref,
craft_ods::CellError::Name => CellError::Name,
craft_ods::CellError::Num => CellError::Num,
craft_ods::CellError::NA => CellError::NA,
craft_ods::CellError::GettingData => CellError::GettingData,
craft_ods::CellError::Spill => CellError::Spill,
craft_ods::CellError::Calc => CellError::Calc,
craft_ods::CellError::Blocked => CellError::Blocked,
_ => CellError::Value,
}
let year: i32 = digits(date.get(..4)?)?.parse().ok()?;
let month: u32 = digits(date.get(5..7)?)?.parse().ok()?;
let day: u32 = digits(date.get(8..10)?)?.parse().ok()?;
if !(1900..=9999).contains(&year) || !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) {
return None;
}
let day = serial_from_ymd(DateSystem::D1900, year.into(), month.into(), day.into())?;
let Some(time) = time else { return Some((day, "yyyy-mm-dd")) };
let mut parts = time.split(':');
let h = parts.next()?;
let m = parts.next()?;
let sec = parts.next()?;
if parts.next().is_some() || h.len() != 2 || m.len() != 2 || sec.split('.').next()?.len() != 2 {
return None;
}
let h: u32 = digits(h)?.parse().ok()?;
let m: u32 = digits(m)?.parse().ok()?;
let sec = decimal(sec)?;
if h >= 24 || m >= 60 || sec >= 60.0 {
return None;
}
Some((day + (h as f64 * 3600.0 + m as f64 * 60.0 + sec) / 86400.0, "yyyy-mm-dd hh:mm:ss.000"))
}
fn digits(s: &str) -> Option<&str> {
(!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then_some(s)
}
fn decimal(s: &str) -> Option<f64> {
match s.split_once('.') {
Some((a, b)) => {
digits(a)?;
digits(b)?;
}
None => {
digits(s)?;
}
}
s.parse::<f64>().ok().filter(|n| n.is_finite())
}
/// A bounded ISO day/time duration. Calendar years/months cannot be represented as days.
fn parse_duration(s: &str) -> Option<f64> {
let (negative, s) = s.strip_prefix('-').map_or((false, s), |s| (true, s));
let mut rest = s.strip_prefix('P')?;
let mut total = 0.0;
let mut any = false;
if let Some((days, tail)) = rest.split_once('D') {
total += digits(days)?.parse::<f64>().ok()? * 86400.0;
rest = tail;
any = true;
}
if let Some(mut time) = rest.strip_prefix('T') {
let mut time_any = false;
for (unit, factor) in [('H', 3600.0), ('M', 60.0), ('S', 1.0)] {
if let Some((n, tail)) = time.split_once(unit) {
let value = if unit == 'S' { decimal(n)? } else { digits(n)?.parse::<f64>().ok()? };
total += value * factor;
time = tail;
time_any = true;
}
}
if !time.is_empty() || !time_any {
return None;
}
any = true;
} else if !rest.is_empty() {
return None;
}
let days = total / 86400.0;
(any && days.is_finite() && days <= 2_958_465.0).then_some(if negative { -days } else { days })
}
+159 -511
View File
@@ -4,38 +4,131 @@
use crate::xml::El;
/// Deepest OMML nesting converted.
/// Deepest OMML nesting marked.
const MAX_DEPTH: usize = 64;
/// Longest LaTeX the conversion produces before it gives up. `gridcraft_math::check` refuses a
/// longer source anyway, so converting the rest of a wide or long equation would only spend time
/// and memory on a hostile file.
const MAX_OUT_BYTES: usize = gridcraft_math::MAX_SOURCE_BYTES;
/// The LaTeX for an `m:oMath` (or `m:oMathPara`) element, if every part is in the subset and the
/// result lays out.
pub fn to_latex(e: &El) -> Option<String> {
let out = convert(e)?;
if e.name != "oMathPara" && e.name != "oMath" {
return None;
}
validate_conversion(e, 0, false, &mut (1 << 20))?;
let mut xml = String::new();
write_el(e, &mut xml);
let math = craft_math::omml::read_str(&xml)?;
let out = craft_math::math_latex::to_latex(&math.nodes);
let out = out.trim().to_string();
(!out.is_empty() && gridcraft_math::check(&out).is_ok()).then_some(out)
}
/// The conversion itself, before the final check: `None` for a construct outside the subset, an
/// equation nested past [`MAX_DEPTH`] or one whose LaTeX exceeds [`MAX_OUT_BYTES`].
fn convert(e: &El) -> Option<String> {
let mut out = String::new();
match e.name.as_str() {
"oMathPara" => {
let maths: Vec<&El> = e.kids("oMath").collect();
for (i, m) in maths.iter().enumerate() {
if i > 0 {
out.push_str(" \\\\ ");
}
seq(m, &mut out, 0)?;
}
// The shared reader is tolerant; this importer must fall back instead of losing
// equation content. Bound escaped XML before serializing or descending further.
fn validate_conversion(e: &El, depth: usize, property: bool, remaining: &mut usize) -> Option<()> {
if depth > MAX_DEPTH {
return None;
}
let charge = e.name.len().checked_mul(2)?.checked_add(16)?.checked_add(e.text.len().checked_mul(6)?)?;
*remaining = remaining.checked_sub(charge)?;
for (key, value) in &e.attrs {
*remaining = remaining.checked_sub(key.len().checked_add(value.len().checked_mul(6)?)?.checked_add(8)?)?;
}
let property = property || e.name.ends_with("Pr");
if !property
&& !matches!(
e.name.as_str(),
"oMath"
| "oMathPara"
| "r"
| "t"
| "f"
| "num"
| "den"
| "rad"
| "deg"
| "e"
| "sSup"
| "sSub"
| "sSubSup"
| "sPre"
| "sub"
| "sup"
| "nary"
| "d"
| "m"
| "mr"
| "eqArr"
| "acc"
| "bar"
| "groupChr"
| "limLow"
| "limUpp"
| "lim"
| "func"
| "fName"
| "borderBox"
| "phant"
| "box"
)
{
return None;
}
// These limits truncate in the shared reader rather than refusing the matrix.
if (e.name == "m" && e.kids("mr").count() > 1000) || (e.name == "mr" && e.kids("e").count() > 64) {
return None;
}
// The pinned emitter treats a literal caret as syntax. Preserve original text
// rather than inventing a superscript; structural scripts remain supported.
if e.name == "t" && e.text.contains('^') {
return None;
}
for child in &e.children {
validate_conversion(child, depth + 1, property, remaining)?;
}
Some(())
}
fn write_el(e: &El, out: &mut String) {
out.push_str("<m:");
out.push_str(&e.name);
for (k, v) in &e.attrs {
out.push(' ');
if k == "val" {
out.push_str("m:val");
} else {
out.push_str(k);
}
"oMath" => seq(e, &mut out, 0)?,
_ => return None,
out.push_str("=\"");
push_xml_escaped(v, out);
out.push('"');
}
if e.children.is_empty() && e.text.is_empty() {
out.push_str("/>");
return;
}
out.push('>');
if !e.text.is_empty() {
push_xml_escaped(&e.text, out);
}
for c in &e.children {
write_el(c, out);
}
out.push_str("</m:");
out.push_str(&e.name);
out.push('>');
}
fn push_xml_escaped(s: &str, out: &mut String) {
for ch in s.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
_ => out.push(ch),
}
}
Some(out.trim().to_string())
}
/// The first `m:oMath`/`m:oMathPara` under `e` (an `a14:m` element or a paragraph), searched to a
@@ -178,35 +271,8 @@ fn mark_bytes(h: &mut u64, bytes: &[u8]) {
}
/// Children in order, skipping property elements.
fn seq(e: &El, out: &mut String, depth: usize) -> Option<()> {
if depth > MAX_DEPTH {
return None;
}
for c in &e.children {
node(c, out, depth + 1)?;
if out.len() > MAX_OUT_BYTES {
return None;
}
}
Some(())
}
/// `{…}` around a child's contents (empty group when the child is missing).
fn group(e: Option<&El>, out: &mut String, depth: usize) -> Option<()> {
out.push('{');
if let Some(e) = e {
seq(e, out, depth)?;
}
out.push('}');
Some(())
}
/// The property elements and the properties in them that this converter reads, so the ones
/// that decide what an equation says beyond its structure and text. [`body_marker`] hashes
/// exactly these, and [`val`] and [`on`] read only these, so the two cannot drift: a property
/// read here without a row in this table reads as absent, which the conversion tests show.
const PROPERTIES: &[(&str, &[&str])] = &[
("rPr", &["nor", "sty", "scr"]),
("rPr", &["nor", "sty", "scr", "lit"]),
("fPr", &["type"]),
("radPr", &["degHide"]),
("naryPr", &["chr", "limLoc", "subHide", "supHide"]),
@@ -221,446 +287,6 @@ fn read_properties(pr: &str) -> &'static [&'static str] {
PROPERTIES.iter().find(|(name, _)| *name == pr).map_or(&[], |(_, names)| names)
}
/// The `val` of property `name` in the property element `props`, when the converter reads it.
fn val<'a>(props: Option<&'a El>, name: &str) -> Option<&'a str> {
props.filter(|p| read_properties(&p.name).contains(&name)).and_then(|p| p.child(name)).and_then(|c| c.attr("val"))
}
/// Whether the switch `name` in the property element `props` is on, when the converter reads it.
fn on(props: Option<&El>, name: &str) -> bool {
props
.filter(|p| read_properties(&p.name).contains(&name))
.and_then(|p| p.child(name))
.is_some_and(|c| c.attr("val").is_none_or(|v| v == "1" || v == "on" || v == "true"))
}
/// LaTeX for one character of a math run.
fn char_latex(c: char) -> Option<&'static str> {
Some(match c {
'α' => "\\alpha ",
'β' => "\\beta ",
'γ' => "\\gamma ",
'δ' => "\\delta ",
'ε' => "\\varepsilon ",
'ϵ' => "\\epsilon ",
'ζ' => "\\zeta ",
'η' => "\\eta ",
'θ' => "\\theta ",
'ϑ' => "\\vartheta ",
'ι' => "\\iota ",
'κ' => "\\kappa ",
'λ' => "\\lambda ",
'μ' => "\\mu ",
'ν' => "\\nu ",
'ξ' => "\\xi ",
'π' => "\\pi ",
'ρ' => "\\rho ",
'σ' => "\\sigma ",
'τ' => "\\tau ",
'υ' => "\\upsilon ",
'φ' => "\\varphi ",
'ϕ' => "\\phi ",
'χ' => "\\chi ",
'ψ' => "\\psi ",
'ω' => "\\omega ",
'Γ' => "\\Gamma ",
'Δ' => "\\Delta ",
'Θ' => "\\Theta ",
'Λ' => "\\Lambda ",
'Ξ' => "\\Xi ",
'Π' => "\\Pi ",
'Σ' => "\\Sigma ",
'Υ' => "\\Upsilon ",
'Φ' => "\\Phi ",
'Ψ' => "\\Psi ",
'Ω' => "\\Omega ",
'±' => "\\pm ",
'∓' => "\\mp ",
'×' => "\\times ",
'÷' => "\\div ",
'⋅' | '·' => "\\cdot ",
'−' => "-",
'≤' => "\\le ",
'≥' => "\\ge ",
'≠' => "\\ne ",
'≈' => "\\approx ",
'≡' => "\\equiv ",
'∼' => "\\sim ",
'∝' => "\\propto ",
'∞' => "\\infty ",
'∂' => "\\partial ",
'∇' => "\\nabla ",
'∀' => "\\forall ",
'∃' => "\\exists ",
'∈' => "\\in ",
'∉' => "\\notin ",
'⊂' => "\\subset ",
'⊆' => "\\subseteq ",
'⊃' => "\\supset ",
'∪' => "\\cup ",
'∩' => "\\cap ",
'∅' => "\\emptyset ",
'→' => "\\to ",
'←' => "\\leftarrow ",
'⇒' => "\\Rightarrow ",
'⇔' => "\\Leftrightarrow ",
'…' => "\\ldots ",
'⋯' => "\\cdots ",
'∘' => "\\circ ",
'{' => "\\{",
'}' => "\\}",
'%' => "\\%",
'#' => "\\#",
'&' => "\\&",
'$' => "\\$",
'_' => "\\_",
'\\' => "\\backslash ",
'~' => "\\sim ",
'^' => "\\hat{}",
_ => return None,
})
}
fn run_text(r: &El) -> String {
r.kids("t").map(|t| t.text.as_str()).collect()
}
/// Appends `s` escaped for `\text{…}`; `None` once the LaTeX exceeds [`MAX_OUT_BYTES`], checked
/// after every character so that a long run never expands in full.
fn escape_text(s: &str, out: &mut String) -> Option<()> {
for c in s.chars() {
match c {
'{' | '}' | '%' | '#' | '&' | '$' | '_' => {
out.push('\\');
out.push(c);
}
'\\' => out.push_str("\\textbackslash "),
'^' | '~' => out.push(' '),
c => out.push(c),
}
if out.len() > MAX_OUT_BYTES {
return None;
}
}
Some(())
}
/// Known operator names written upright in a run (`sin`, `log`, `lim`).
const FUNCTIONS: &[&str] = &[
"sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "log", "ln", "lg", "exp", "lim", "max", "min",
"sup", "inf", "det", "gcd", "deg", "dim", "ker", "arg", "Pr", "liminf", "limsup",
];
fn run(r: &El, out: &mut String) -> Option<()> {
let text = run_text(r);
if text.is_empty() {
return Some(());
}
let rpr = r.child("rPr");
if on(rpr, "nor") {
out.push_str("\\text{");
escape_text(&text, out)?;
out.push('}');
return Some(());
}
let plain = val(rpr, "sty") == Some("p");
if plain && FUNCTIONS.contains(&text.trim()) {
out.push('\\');
out.push_str(text.trim());
out.push(' ');
return Some(());
}
let wrap = match (val(rpr, "scr"), val(rpr, "sty")) {
(Some("double-struck"), _) => Some("\\mathbb{"),
(Some("script"), _) => Some("\\mathcal{"),
(Some("fraktur"), _) => Some("\\mathfrak{"),
(Some("sans-serif"), _) => Some("\\mathsf{"),
(Some("monospace"), _) => Some("\\mathtt{"),
(_, Some("b")) => Some("\\mathbf{"),
(_, Some("bi")) => Some("\\boldsymbol{"),
(_, Some("p")) if text.chars().any(|c| c.is_alphabetic()) => Some("\\mathrm{"),
_ => None,
};
if let Some(w) = wrap {
out.push_str(w);
}
for c in text.chars() {
match char_latex(c) {
Some(l) => out.push_str(l),
None => out.push(c),
}
// Checked per character, not from the run's byte length: a character may map to a
// longer macro or a shorter sign, so only the LaTeX produced counts.
if out.len() > MAX_OUT_BYTES {
return None;
}
}
if wrap.is_some() {
out.push('}');
}
Some(())
}
/// A delimiter character as a `\left`/`\right` argument.
fn delim(c: Option<&str>, default: &str) -> String {
let c = c.unwrap_or(default);
match c {
"" => ".".into(),
"{" => "\\{".into(),
"}" => "\\}".into(),
"⟨" | "〈" => "\\langle".into(),
"⟩" | "〉" => "\\rangle".into(),
"⌊" => "\\lfloor".into(),
"⌋" => "\\rfloor".into(),
"⌈" => "\\lceil".into(),
"⌉" => "\\rceil".into(),
"‖" => "\\|".into(),
"∣" => "|".into(),
other => other.into(),
}
}
fn nary_op(chr: &str) -> Option<&'static str> {
Some(match chr {
"∑" => "\\sum",
"∏" => "\\prod",
"∐" => "\\coprod",
"∫" => "\\int",
"∬" => "\\iint",
"∭" => "\\iiint",
"∮" => "\\oint",
"⋃" => "\\bigcup",
"⋂" => "\\bigcap",
"⋁" => "\\bigvee",
"⋀" => "\\bigwedge",
"⨁" => "\\bigoplus",
"⨂" => "\\bigotimes",
_ => return None,
})
}
fn accent(chr: &str) -> Option<&'static str> {
Some(match chr {
"\u{0302}" | "^" => "\\hat",
"\u{030C}" => "\\check",
"\u{0303}" | "~" => "\\tilde",
"\u{0301}" => "\\acute",
"\u{0300}" => "\\grave",
"\u{0307}" => "\\dot",
"\u{0308}" => "\\ddot",
"\u{0306}" => "\\breve",
"\u{0305}" | "\u{0304}" | "¯" => "\\bar",
"\u{20D7}" | "→" => "\\vec",
"\u{20D6}" => "\\overleftarrow",
"\u{030A}" => "\\mathring",
_ => return None,
})
}
fn node(e: &El, out: &mut String, depth: usize) -> Option<()> {
if depth > MAX_DEPTH {
return None;
}
match e.name.as_str() {
// Properties and run-level DrawingML are not content.
n if n.ends_with("Pr") => {}
"r" => run(e, out)?,
"f" => fraction(e, out, depth)?,
"rad" => radical(e, out, depth)?,
"sSup" | "sSub" | "sSubSup" => scripts(e, out, depth)?,
"nary" => nary(e, out, depth)?,
"d" => delimiters(e, out, depth)?,
"m" => matrix(e, out, depth)?,
"eqArr" => equation_array(e, out, depth)?,
"acc" => {
out.push_str(accent(val(e.child("accPr"), "chr").unwrap_or("\u{0302}"))?);
group(e.child("e"), out, depth)?;
}
"bar" => {
out.push_str(if val(e.child("barPr"), "pos") == Some("top") { "\\overline" } else { "\\underline" });
group(e.child("e"), out, depth)?;
}
"groupChr" => group_char(e, out, depth)?,
"limLow" | "limUpp" => limit(e, out, depth)?,
"func" => {
seq(e.child("fName")?, out, depth)?;
out.push(' ');
group(e.child("e"), out, depth)?;
}
"borderBox" => {
out.push_str("\\boxed");
group(e.child("e"), out, depth)?;
}
"phant" => {
out.push_str("\\phantom");
group(e.child("e"), out, depth)?;
}
"box" => group(e.child("e"), out, depth)?,
_ => return None,
}
Some(())
}
/// `m:f`: a fraction, or a binomial-style stack without a bar.
fn fraction(e: &El, out: &mut String, depth: usize) -> Option<()> {
if val(e.child("fPr"), "type") == Some("noBar") {
out.push_str("\\genfrac{}{}{0pt}{}");
} else {
out.push_str("\\frac");
}
group(e.child("num"), out, depth)?;
group(e.child("den"), out, depth)
}
/// `m:rad`: a square root, or a root with a degree.
fn radical(e: &El, out: &mut String, depth: usize) -> Option<()> {
let hide = on(e.child("radPr"), "degHide");
match e.child("deg").filter(|d| !hide && !d.children.is_empty()) {
Some(d) => {
out.push_str("\\sqrt[");
seq(d, out, depth)?;
out.push(']');
}
None => out.push_str("\\sqrt"),
}
group(e.child("e"), out, depth)
}
/// `m:sSup`, `m:sSub`, `m:sSubSup`: a base with scripts.
fn scripts(e: &El, out: &mut String, depth: usize) -> Option<()> {
group(e.child("e"), out, depth)?;
if let Some(sub) = e.child("sub") {
out.push('_');
group(Some(sub), out, depth)?;
}
if let Some(sup) = e.child("sup") {
out.push('^');
group(Some(sup), out, depth)?;
}
Some(())
}
/// `m:nary`: a large operator with its limits and operand.
fn nary(e: &El, out: &mut String, depth: usize) -> Option<()> {
let p = e.child("naryPr");
let op = nary_op(val(p, "chr").unwrap_or("∫"))?;
out.push_str(op);
if val(p, "limLoc") == Some("undOvr") && op.contains("int") {
out.push_str("\\limits");
}
if !on(p, "subHide") {
out.push('_');
group(e.child("sub"), out, depth)?;
}
if !on(p, "supHide") {
out.push('^');
group(e.child("sup"), out, depth)?;
}
out.push(' ');
group(e.child("e"), out, depth)
}
/// `m:d`: delimiters around one or more parts, with a separator between them.
fn delimiters(e: &El, out: &mut String, depth: usize) -> Option<()> {
let p = e.child("dPr");
out.push_str("\\left");
out.push_str(&delim(val(p, "begChr"), "("));
out.push(' ');
let sep = delim(val(p, "sepChr"), "|");
for (i, part) in e.kids("e").enumerate() {
if i > 0 {
out.push_str(" \\middle");
out.push_str(&sep);
out.push(' ');
}
seq(part, out, depth)?;
}
out.push_str(" \\right");
out.push_str(&delim(val(p, "endChr"), ")"));
Some(())
}
/// `m:m`: a matrix, row by row.
fn matrix(e: &El, out: &mut String, depth: usize) -> Option<()> {
out.push_str("\\begin{matrix}");
for (i, row) in e.kids("mr").enumerate() {
if i > 0 {
out.push_str(" \\\\ ");
}
for (k, cell) in row.kids("e").enumerate() {
if k > 0 {
out.push_str(" & ");
}
seq(cell, out, depth)?;
}
}
out.push_str("\\end{matrix}");
Some(())
}
/// `m:eqArr`: equations stacked one per row.
fn equation_array(e: &El, out: &mut String, depth: usize) -> Option<()> {
out.push_str("\\begin{gathered}");
for (i, row) in e.kids("e").enumerate() {
if i > 0 {
out.push_str(" \\\\ ");
}
seq(row, out, depth)?;
}
out.push_str("\\end{gathered}");
Some(())
}
/// Effective brace orientation, including the character default and its precedence over position.
fn group_char_is_over(e: &El) -> bool {
let p = e.child("groupChrPr");
match val(p, "chr").unwrap_or("\u{23DF}") {
"\u{23DE}" => true,
"\u{23DF}" => false,
_ => val(p, "pos") == Some("top"),
}
}
/// `m:groupChr`: a brace over or under its content.
fn group_char(e: &El, out: &mut String, depth: usize) -> Option<()> {
out.push_str(if group_char_is_over(e) { "\\overbrace" } else { "\\underbrace" });
group(e.child("e"), out, depth)
}
/// `m:limLow`, `m:limUpp`: a limit under or over its base.
fn limit(e: &El, out: &mut String, depth: usize) -> Option<()> {
let low = e.name == "limLow";
let base = e.child("e");
// A function name with a limit (lim, max) takes it as a subscript with \limits.
let base_is_fn = base.is_some_and(|b| {
let t: String = b.kids("r").map(run_text).collect();
b.children.iter().all(|c| c.name == "r") && FUNCTIONS.contains(&t.trim())
});
// A brace alone under the limit is a labelled brace, as `gridcraft_math::to_omml` writes
// `\underbrace{x}_{n}` and `\overbrace{x}^{n}`: the label is the brace's own script, below
// for an underbrace and above for an overbrace. An opposite-side limit keeps its placement.
let brace = base
.and_then(|b| {
let mut content = b.children.iter().filter(|c| !c.name.ends_with("Pr"));
content.next().filter(|c| c.name == "groupChr" && content.next().is_none())
})
.filter(|brace| low != group_char_is_over(brace));
if base_is_fn {
seq(base?, out, depth)?;
out.push_str(if low { "\\limits_" } else { "\\limits^" });
group(e.child("lim"), out, depth)?;
} else if let Some(brace) = brace {
group_char(brace, out, depth + 1)?;
out.push(if low { '_' } else { '^' });
group(e.child("lim"), out, depth)?;
} else {
out.push_str(if low { "\\underset" } else { "\\overset" });
group(e.child("lim"), out, depth)?;
group(base, out, depth)?;
}
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -673,6 +299,29 @@ mod tests {
to_latex(&el(xml))
}
#[test]
fn conversion_does_not_accept_a_partial_equation() {
assert_eq!(latex("<m:r><m:t>x</m:t></m:r><m:unknown/>"), None);
assert_eq!(
latex(
"<m:r><m:t>x</m:t></m:r><mc:AlternateContent xmlns:mc=\"mc\"><mc:Fallback><m:r><m:t>y</m:t></m:r></mc:Fallback></mc:AlternateContent>"
),
None
);
assert_eq!(latex("<m:r><m:t>x^2</m:t></m:r>"), None);
assert_eq!(latex("<m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>").as_deref(), Some("{x}^{2}"));
let cells = "<m:e><m:r><m:t>x</m:t></m:r></m:e>".repeat(65);
assert_eq!(latex(&format!("<m:m><m:mr>{cells}</m:mr></m:m>")), None);
}
#[test]
fn literal_run_property_invalidates_the_saved_source_marker() {
let plain = el("<m:r><m:t>x</m:t></m:r>");
let literal = el("<m:r><m:rPr><m:lit/></m:rPr><m:t>x</m:t></m:r>");
assert_ne!(body_marker(&plain), body_marker(&literal));
assert_eq!(body_marker(&plain), body_marker(&plain.clone()));
}
#[test]
fn the_subset_reads_back() {
assert_eq!(latex("<m:r><m:t>x+1</m:t></m:r>").as_deref(), Some("x+1"));
@@ -685,13 +334,13 @@ mod tests {
let sum = latex(
"<m:nary><m:naryPr><m:chr m:val=\"∑\"/><m:limLoc m:val=\"undOvr\"/></m:naryPr><m:sub><m:r><m:t>i=1</m:t></m:r></m:sub><m:sup><m:r><m:t>n</m:t></m:r></m:sup><m:e><m:r><m:t>i</m:t></m:r></m:e></m:nary>",
);
assert_eq!(sum.as_deref(), Some("\\sum_{i=1}^{n} {i}"));
assert_eq!(sum.as_deref(), Some("\\sum\\limits_{i=1}^{n} {i}"));
// An integral without a character, with hidden limits.
assert_eq!(latex("<m:nary><m:naryPr><m:subHide m:val=\"1\"/><m:supHide m:val=\"1\"/></m:naryPr><m:sub/><m:sup/><m:e><m:r><m:t>f</m:t></m:r></m:e></m:nary>").as_deref(), Some("\\int {f}"));
let m = latex(
"<m:d><m:dPr><m:begChr m:val=\"[\"/><m:endChr m:val=\"]\"/></m:dPr><m:e><m:m><m:mr><m:e><m:r><m:t>1</m:t></m:r></m:e><m:e><m:r><m:t>0</m:t></m:r></m:e></m:mr><m:mr><m:e><m:r><m:t>0</m:t></m:r></m:e><m:e><m:r><m:t>1</m:t></m:r></m:e></m:mr></m:m></m:e></m:d>",
);
assert_eq!(m.as_deref(), Some("\\left[ \\begin{matrix}1 & 0 \\\\ 0 & 1\\end{matrix} \\right]"));
assert_eq!(m.as_deref(), Some("\\left[\\begin{matrix}1&0\\\\0&1\\end{matrix}\\right]"));
assert_eq!(latex("<m:r><m:rPr><m:sty m:val=\"p\"/></m:rPr><m:t>sin</m:t></m:r><m:r><m:t>x</m:t></m:r>").as_deref(), Some("\\sin x"));
assert_eq!(latex("<m:r><m:rPr><m:scr m:val=\"double-struck\"/></m:rPr><m:t>R</m:t></m:r>").as_deref(), Some("\\mathbb{R}"));
assert_eq!(latex("<m:r><m:rPr><m:nor/></m:rPr><m:t>if {x}</m:t></m:r>").as_deref(), Some("\\text{if \\{x\\}}"));
@@ -703,9 +352,9 @@ mod tests {
#[test]
fn what_is_outside_the_subset_is_none() {
assert_eq!(latex("<m:sPre><m:sub/><m:sup/><m:e/></m:sPre>"), None);
assert_eq!(latex("<m:sPre><m:sub/><m:sup/><m:e/></m:sPre>").as_deref(), Some("{}_{}^{}{}"));
assert_eq!(latex(""), None, "an empty equation is not maths");
assert_eq!(latex("<m:nary><m:naryPr><m:chr m:val=\"☃\"/></m:naryPr><m:e/></m:nary>"), None);
assert_eq!(latex("<m:nary><m:naryPr><m:chr m:val=\"☃\"/></m:naryPr><m:e/></m:nary>").as_deref(), Some("☃ {}"));
// Deep nesting stops instead of recursing without bound.
let deep = format!("{}<m:r><m:t>x</m:t></m:r>{}", "<m:box><m:e>".repeat(100), "</m:e></m:box>".repeat(100));
assert_eq!(latex(&deep), None);
@@ -719,22 +368,21 @@ mod tests {
// refusing it, so the caller falls back to the writer's text in bounded time.
let wide = el(&"<m:r><m:t>x</m:t></m:r>".repeat(100_000));
let start = std::time::Instant::now();
assert_eq!(convert(&wide), None);
assert_eq!(to_latex(&wide), None);
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
// One run whose text alone is past the cap is refused before it is escaped (each
// backslash would otherwise grow to `\textbackslash `).
let long = el(&format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{}</m:t></m:r>", "\\".repeat(MAX_OUT_BYTES + 1)));
assert_eq!(convert(&long), None);
let long = el(&format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{}</m:t></m:r>", "\\".repeat(gridcraft_math::MAX_SOURCE_BYTES + 1)));
assert_eq!(to_latex(&long), None);
// Groups count the braces they add even when no run adds text.
let groups = el(&"<m:box><m:e/></m:box>".repeat(MAX_OUT_BYTES / 2 + 1));
assert_eq!(convert(&groups), None);
let groups = el(&"<m:box><m:e/></m:box>".repeat(gridcraft_math::MAX_SOURCE_BYTES / 2 + 1));
assert_eq!(to_latex(&groups), None);
// At the cap the equation still reads back, and the cap counts the LaTeX produced, not
// the run's bytes: a minus sign (three bytes of UTF-8) becomes a one-byte `-`.
let at_cap = el(&"<m:r><m:t>x</m:t></m:r>".repeat(MAX_OUT_BYTES));
assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(MAX_OUT_BYTES));
let minus = el(&format!("<m:r><m:t>{}</m:t></m:r>", "\u{2212}".repeat(MAX_OUT_BYTES)));
assert_eq!(to_latex(&minus), Some("-".repeat(MAX_OUT_BYTES)));
let at_cap = el(&"<m:r><m:t>x</m:t></m:r>".repeat(gridcraft_math::MAX_SOURCE_BYTES));
assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(gridcraft_math::MAX_SOURCE_BYTES));
let minus = el(&format!("<m:r><m:t>{}</m:t></m:r>", "\u{2212}".repeat(gridcraft_math::MAX_SOURCE_BYTES)));
assert_eq!(to_latex(&minus), Some("-".repeat(gridcraft_math::MAX_SOURCE_BYTES)));
}
#[test]
@@ -764,17 +412,17 @@ mod tests {
#[test]
fn a_limit_on_the_opposite_side_of_a_brace_keeps_its_placement() {
for (properties, brace, opposite, same, script) in [
(r#"<m:chr m:val="&#x23DF;"/><m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
(r#"<m:chr m:val="&#x23DE;"/><m:pos m:val="bot"/>"#, "overbrace", "limLow", "limUpp", '^'),
(r#"<m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
(r#"<m:chr m:val="?"/><m:pos m:val="top"/>"#, "overbrace", "limLow", "limUpp", '^'),
for (properties, brace, opposite, same) in [
(r#"<m:chr m:val="&#x23DF;"/><m:pos m:val="top"/>"#, "overbrace", "limUpp", "limLow"),
(r#"<m:chr m:val="&#x23DE;"/><m:pos m:val="bot"/>"#, "underbrace", "limLow", "limUpp"),
(r#"<m:pos m:val="top"/>"#, "overbrace", "limUpp", "limLow"),
(r#"<m:chr m:val="?"/><m:pos m:val="top"/>"#, "overbrace", "limLow", "limUpp"),
] {
let base = format!("<m:groupChr><m:groupChrPr>{properties}</m:groupChrPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:groupChr>");
let limit = |kind: &str| format!("<m:{kind}><m:e>{base}</m:e><m:lim><m:r><m:t>n</m:t></m:r></m:lim></m:{kind}>");
let placement = if opposite == "limLow" { "underset" } else { "overset" };
assert_eq!(latex(&limit(opposite)), Some(format!("\\{placement}{{n}}{{\\{brace}{{x}}}}")), "{properties}");
assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{script}{{n}}")), "{properties}");
let script = |kind: &str| if kind == "limUpp" { '^' } else { '_' };
assert_eq!(latex(&limit(opposite)), Some(format!("\\{brace}{{x}}{}{{n}}", script(opposite))), "{properties}");
assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{}{{n}}", script(same))), "{properties}");
}
}
+45 -7
View File
@@ -210,7 +210,7 @@ fn a_marker_over_garbage_office_math_falls_back_without_panicking() {
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
let mut d = drawing(&parts);
let (m0, m1) = (d.find("<m:oMath>").unwrap(), d.find("</m:oMath>").unwrap());
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:sPre/><m:f><m:num/></m:f><m:r/><m:t>junk</m:t><m:oMath/><m:e/></m:oMath>");
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:unknown/><m:r/><m:t>junk</m:t><m:oMath/><m:e/></m:oMath>");
parts.insert(name.clone(), d.into_bytes());
let (back, _) = read_xlsx(&rezip(&parts)).unwrap();
let s = shapes(&back);
@@ -233,17 +233,14 @@ fn office_math_outside_the_subset_reads_the_fallback() {
let mut parts = unzip(&write_xlsx(&wb).unwrap());
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
let mut d = drawing(&parts);
// Another writer: no GridCraft source, Office Math the reader does not convert (a
// pre-subscript), and a fallback text box with its own text.
// Another writer: no GridCraft source, Office Math the reader does not convert,
// and a fallback text box with its own text.
while let Some(a) = d.find(" descr=\"gridcraft:latex:") {
let b = d[a + 8..].find('"').unwrap() + a + 9;
d.replace_range(a..b, "");
}
let (m0, m1) = (d.find("<m:oMath>").unwrap(), d.find("</m:oMath>").unwrap());
d.replace_range(
m0..m1 + "</m:oMath>".len(),
"<m:oMath><m:sPre><m:sub><m:r><m:t>1</m:t></m:r></m:sub><m:sup><m:r><m:t>2</m:t></m:r></m:sup><m:e><m:r><m:t>y</m:t></m:r></m:e></m:sPre></m:oMath>",
);
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:unknown><m:e><m:r><m:t>y</m:t></m:r></m:e></m:unknown></m:oMath>");
let fb = d.find("<mc:Fallback>").unwrap();
let t = d[fb..].find("<a:t>x^2</a:t>").unwrap() + fb;
d.replace_range(t..t + "<a:t>x^2</a:t>".len(), "<a:t>the writer's fallback</a:t>");
@@ -484,3 +481,44 @@ fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() {
// The Office Math box keeps the size of the equation.
assert!(!d.contains("<a:endParaRPr lang=\"en-US\" sz=\"1100\"/>"), "{d}");
}
#[test]
fn rejected_office_math_without_a_saved_source_keeps_visible_text() {
let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]);
let original = unzip(&write_xlsx(&wb).unwrap());
let name = original.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
let d = drawing(&original);
let c0 = d.find("<mc:Choice").unwrap();
let c1 = d.find("</mc:Choice>").unwrap();
let choice = &d[c0..c1];
let mut sp = choice[choice.find("<xdr:sp ").unwrap()..].to_string();
while let Some(a) = sp.find(" descr=\"gridcraft:latex:") {
let b = sp[a + 8..].find('"').unwrap() + a + 9;
sp.replace_range(a..b, "");
}
let a0 = d.find("<mc:AlternateContent").unwrap();
let a1 = d.find("</mc:AlternateContent>").unwrap() + "</mc:AlternateContent>".len();
for (body, expected) in [
("<a:p><a14:m><m:oMath><m:r><m:t>x^2</m:t></m:r></m:oMath></a14:m></a:p>", "x^2"),
(
"<a:p><a:r><a:t>Solve: </a:t></a:r><a14:m><m:oMath><m:r><m:t>x^2</m:t></m:r></m:oMath></a14:m><a:r><a:t> please</a:t></a:r></a:p><a:p><a:r><a:t>next</a:t></a:r></a:p>",
"Solve: x^2 please\nnext",
),
("<a:p><a14:m><m:oMath><m:unknown><m:r><m:t>λ^2</m:t></m:r></m:unknown></m:oMath></a14:m></a:p>", "λ^2"),
] {
let mut shape = sp.clone();
let start = shape.find("<xdr:txBody>").unwrap();
let end = shape.find("</xdr:txBody>").unwrap() + "</xdr:txBody>".len();
shape.replace_range(start..end, &format!("<xdr:txBody>{body}</xdr:txBody>"));
let mut xml = d.clone();
xml.replace_range(a0..a1, &shape);
let mut parts = original.clone();
parts.insert(name.clone(), xml.into_bytes());
let back = shapes(&read_xlsx(&rezip(&parts)).unwrap().0);
assert_eq!(back.len(), 1);
assert_ne!(back[0].kind, ShapeKind::Equation);
assert_eq!(back[0].text, expected);
let again = shapes(&read_xlsx(&write_xlsx(&book(back)).unwrap()).unwrap().0);
assert_eq!(again[0].text, expected);
}
}
+15 -2
View File
@@ -111,6 +111,19 @@ fn ods_repeats_merges_sheet_names_and_empty_tail_remain_sparse() {
assert_eq!(wb.sheets[1].value(CellRef::new(0, 0)), text("second sheet"));
}
#[test]
fn ods_tables_are_the_only_sheets_with_unique_valid_names() {
let cell = r#"<table:table-row><table:table-cell office:value-type="float" office:value="1"/></table:table-row>"#;
let bytes = ods(&format!(
r#"<table:table table:name="Data">{cell}</table:table><table:table table:name="data">{cell}</table:table><table:table table:name="a/b">{cell}</table:table>"#
));
let (wb, report) = read_ods(&bytes).unwrap();
let names: Vec<&str> = wb.sheets.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["Data", "data (2)", "ab"]);
assert!(wb.sheets.iter().all(|s| s.value(CellRef::new(0, 0)) == Value::Number(1.0)));
assert!(report.warnings.iter().any(|w| w.contains("renamed")));
}
#[test]
fn ods_dates_and_durations_use_formats_and_unsupported_values_stay_text() {
let bytes = row(r#"
@@ -158,8 +171,8 @@ fn ods_rejects_bad_packages_encryption_and_truncated_xml() {
for mime in [b"application/zip".as_slice(), b"application/vnd.oasis.opendocument.spreadsheet "] {
assert!(read_ods(&make_zip(&[("mimetype", mime), ("content.xml", xml.as_bytes())])).is_err());
}
let encrypted =
br#"<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:encryption-data/></manifest:manifest>"#;
// As LibreOffice writes it: the encryption data belongs to the encrypted file's entry.
let encrypted = br#"<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"><manifest:encryption-data manifest:checksum-type="SHA1/1K" manifest:checksum="AAAA"/></manifest:file-entry></manifest:manifest>"#;
assert!(
read_ods(&make_zip(&[("mimetype", MIME), ("META-INF/manifest.xml", encrypted), ("content.xml", xml.as_bytes())]))
.unwrap_err()
+2 -1
View File
@@ -1,6 +1,6 @@
# UI parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
@@ -275,6 +275,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines |
| 2026-11-04 | minor | Align wrapped and unwrapped cells with the same vertical margins; regressions compare numbers with mixed CJK/Latin text, including explicit line breaks |
| 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 |
| 2026-11-03 | minor | Find and Replace: workbook Undo/Redo works with a keyboard-focused button; focused text fields keep text-editing Undo, and a modal message blocks workbook shortcuts. Regression covers Replace All, both Redo shortcuts, actual text undo, and an error message |
| 2026-11-03 | minor | Highlight the active cell's row: a global preference that tints the whole row, off by default |
| 2026-11-03 | minor | The formula bar's bottom edge is a resize handle: dragging it sets the bar's height in whole lines, up to half the window, and dragging it to one line collapses it; expanding (the chevron, Ctrl+Shift+U) returns to the dragged height, which is kept with the UI preferences. `view.expandFormulaBar {lines}` sets it (#1246) |
| 2026-11-03 | minor | Cell context menu on a cell with a link: Edit Hyperlink… (the link dialog, titled Edit Hyperlink and filled with the link), Open Hyperlink and Remove Hyperlink, as in Excel, instead of Link… (#2120) |