mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-18 20:09:54 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7989911c09 |
Generated
+6
-41
@@ -982,32 +982,12 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
name = "craft-math"
|
||||
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",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1033,7 +1013,7 @@ version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"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)",
|
||||
"craft-zip",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1057,11 +1037,6 @@ 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"
|
||||
@@ -1170,7 +1145,7 @@ version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"craft-sheet",
|
||||
"md-5",
|
||||
"miniz_oxide 0.9.1",
|
||||
"sha1 0.10.7",
|
||||
@@ -1184,7 +1159,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"craft-sheet",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1208,16 +1183,6 @@ 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"
|
||||
@@ -2459,7 +2424,7 @@ version = "0.19.1"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-csv",
|
||||
"craft-ods",
|
||||
"craft-math",
|
||||
"craft-offcrypto",
|
||||
"craft-opc",
|
||||
"craft-xls",
|
||||
|
||||
+1
-1
@@ -37,12 +37,12 @@ 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.
|
||||
|
||||
@@ -1,23 +1,8 @@
|
||||
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() {
|
||||
|
||||
@@ -336,77 +336,6 @@ 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();
|
||||
|
||||
@@ -20,7 +20,7 @@ gridcraft-math = { workspace = true }
|
||||
gridcraft-model = { workspace = true }
|
||||
craft-cfb = { workspace = true }
|
||||
craft-csv = { workspace = true }
|
||||
craft-ods = { workspace = true }
|
||||
craft-math = { workspace = true }
|
||||
craft-offcrypto = { workspace = true }
|
||||
craft-opc = { workspace = true }
|
||||
craft-xls = { workspace = true }
|
||||
|
||||
+633
-76
@@ -1,16 +1,32 @@
|
||||
//! Data-only OpenDocument Spreadsheet import backed by `craft-ods`.
|
||||
//! Formula caches become constants; styles and other ODF features are deliberately not translated.
|
||||
//! 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>.
|
||||
|
||||
use std::io::{Cursor, Read};
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_core::{CellError, CellRef, RangeRef, Value};
|
||||
use gridcraft_core::date::{days_in_month, serial_from_ymd};
|
||||
use gridcraft_core::{CellRef, DateSystem, MAX_COLS, MAX_ROWS, 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;
|
||||
use crate::package::{MAX_ENTRIES, Package};
|
||||
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.
|
||||
@@ -32,96 +48,637 @@ 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 book = craft_ods::read(bytes, &craft_ods::Options::default()).map_err(map_error)?;
|
||||
if book.sheets.is_empty() {
|
||||
let mut package = Package::open(bytes)?;
|
||||
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() {
|
||||
return Err(IoError::Format("ODS contains no worksheets".into()));
|
||||
}
|
||||
if book.sheets.len() > MAX_SHEETS {
|
||||
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
|
||||
}
|
||||
Ok((import.wb, import.report))
|
||||
}
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
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 is_ns(ns: ResolveResult<'_>, expected: &[u8]) -> bool {
|
||||
matches!(ns, ResolveResult::Bound(n) if n.as_ref() == expected)
|
||||
}
|
||||
|
||||
let mut warned_rename = false;
|
||||
let mut warned_unavailable = false;
|
||||
|
||||
for src_sheet in book.sheets {
|
||||
let mut sheet = Sheet::new(&src_sheet.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.");
|
||||
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());
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
for (coord, src_cell) in src_sheet.cells {
|
||||
let value = match src_cell.value() {
|
||||
Some(v) => map_value(v),
|
||||
None if src_cell.formula.is_some() => {
|
||||
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].");
|
||||
}
|
||||
Value::Text(Arc::from("[Unavailable ODS formula result]"))
|
||||
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()));
|
||||
}
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let style_id = match src_cell.value_type {
|
||||
Some(craft_ods::ValueType::Date) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("yyyy-mm-dd")),
|
||||
Some(craft_ods::ValueType::Time) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("[h]:mm:ss")),
|
||||
Some(craft_ods::ValueType::Percentage) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("0.00%")),
|
||||
Some(craft_ods::ValueType::Currency) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("#,##0.00")),
|
||||
_ => StyleId::DEFAULT,
|
||||
};
|
||||
|
||||
let target_coord = CellRef::new(coord.row, coord.col);
|
||||
sheet.set_cell(target_coord, Cell::styled(value, style_id));
|
||||
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,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !root_seen || depth != 0 {
|
||||
return Err(xml_error("incomplete manifest"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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);
|
||||
#[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(),
|
||||
}
|
||||
wb.sheets.push(Arc::new(sheet));
|
||||
}
|
||||
|
||||
Ok((wb, report))
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
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 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 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())
|
||||
} else {
|
||||
attr(reader, e, OFFICE, b"value-type")?
|
||||
};
|
||||
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(())
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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)),
|
||||
_ => 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) }
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
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(Arc::from(s)),
|
||||
craft_ods::Value::Bool(b) => Value::Bool(b),
|
||||
craft_ods::Value::Error(e) => Value::Error(map_cell_error(e)),
|
||||
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()));
|
||||
}
|
||||
out.push_str(text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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,
|
||||
/// 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;
|
||||
}
|
||||
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 })
|
||||
}
|
||||
|
||||
+64
-507
@@ -4,38 +4,64 @@
|
||||
|
||||
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;
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
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);
|
||||
}
|
||||
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("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(ch),
|
||||
}
|
||||
"oMath" => seq(e, &mut out, 0)?,
|
||||
_ => return None,
|
||||
}
|
||||
Some(out.trim().to_string())
|
||||
}
|
||||
|
||||
/// The first `m:oMath`/`m:oMathPara` under `e` (an `a14:m` element or a paragraph), searched to a
|
||||
@@ -178,33 +204,6 @@ 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"]),
|
||||
("fPr", &["type"]),
|
||||
@@ -221,446 +220,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::*;
|
||||
@@ -685,13 +244,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 +262,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 +278,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]
|
||||
@@ -765,15 +323,14 @@ 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="⏟"/><m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
|
||||
(r#"<m:chr m:val="⏞"/><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", "limUpp", "limLow", '^'),
|
||||
(r#"<m:chr m:val="⏞"/><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(opposite)), Some(format!("\\{brace}{{x}}{script}{{n}}")), "{properties}");
|
||||
assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{script}{{n}}")), "{properties}");
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **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
|
||||
> **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
|
||||
|
||||
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,7 +275,6 @@ 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) |
|
||||
|
||||
Reference in New Issue
Block a user