diff --git a/crates/xlsx/README.md b/crates/xlsx/README.md index 36893f43c..34ebce918 100644 --- a/crates/xlsx/README.md +++ b/crates/xlsx/README.md @@ -8,7 +8,8 @@ This is the part layer. `Package::open` opens the container through `craft-opc` | Call | Gives | |---|---| -| `workbook()` | `Workbook`: sheets in tab order (name, id, visibility, kind, part), the 1904 date flag, defined names, the active tab, and the whole part as a tree | +| `workbook()` | `Workbook`: sheets in tab order (name, id, visibility, kind, part), the 1904 date flag, defined names, the active tab, the external references, and the whole part as a tree | +| `external_links(workbook)` | each `ExternalLink` in `externalReferences` order, so a formula's `[n]` is entry `n - 1` (a reference without an id keeps its place, empty); a binary workbook's are read once, with its workbook part: another workbook's target, sheet names, defined names (`refersTo`, `sheetId`) and cached cells; a DDE or OLE link as `Other` | | `shared_strings()` | `StringItem`s: text, formatted runs, phonetic readings | | `styles()` | `Styles`: number formats, fonts, fills, borders, cell and cell-style formats, named styles, differential formats, the indexed palette, as indexed tables | | `sheet(entry, each)` | each `Row` of `Cell`s to a callback, then a `SheetPart`: the rest of the worksheet as a tree, its relationships, columns and merged cells | @@ -109,7 +110,7 @@ implicit `@`, the spaces and line breaks typed in the formula, numbers as Excel metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the file keeps the tokens once. A formula whose decoding needs something the reader does not read keeps only its saved result, with a warning saying why: a defined name left out, a table whose part can't -be read, other workbooks, Python code stored outside the cell, data tables. +be read, an unavailable external link, Python code stored outside the cell, data tables. A binary workbook's tables (`tableN.bin`, listed by the sheet's `BrtListPart`s) read through `Package::tables` into the same `Table`, as Excel writes the table in `.xlsx`: the calculated and @@ -127,6 +128,14 @@ a table that can't be read, to a deleted table or into another workbook keeps th result. The XLSB function table (`xlsb/ftab.rs`) and the expression printer are this crate's own, apart from `craft-xls`'s. +A reference to another workbook is spelled as `.xlsx` has it (`[1]Data!$A$1`, `'[1]Other Sheet'!A1`, +`'[1]A:C'!A1`, `[1]!ExtName`, a DDE item `[2]!'R1C1'`), numbered by its `BrtSupBookSrc`, from the +sheet and name lists of its `externalLinkN.bin`, read when the workbook part is; Excel quotes such a +sheet only for a leading digit or a character outside letters, digits, `_` and `.`. Excel's binary +file may record a sheet-scoped name of the other workbook as workbook-level (`iSheet` 0); such a +name reads as Excel itself reads it back, `[1]!Local`. A reference to a link that can't be read, a +deleted sheet of it or a name it lacks keeps the cell's saved result. + ## Hostile input - `Limits.package`: ZIP entries, bytes per part and in all (`craft-opc`). diff --git a/crates/xlsx/src/external.rs b/crates/xlsx/src/external.rs new file mode 100644 index 000000000..235d3293f --- /dev/null +++ b/crates/xlsx/src/external.rs @@ -0,0 +1,104 @@ +//! External links (`xl/externalLinks/externalLinkN.xml`, ECMA-376 Part 1, 18.14): the other +//! workbooks a workbook's formulas refer to as `[1]Sheet1!A1`, numbered in the order of the +//! workbook's `externalReferences` ([`crate::Workbook::external_references`]). A binary workbook's +//! `externalLinkN.bin` reads into the same types. + +use craft_opc::Rels; +use craft_sheet::{CellError, CellRef, Value}; +use craft_xml::El; + +/// One external link part. +#[derive(Clone, Debug, PartialEq)] +pub enum ExternalLink { + /// `externalBook`: another workbook. + Book(ExternalBook), + /// `ddeLink` or `oleLink`: a DDE or OLE source, not read. + Other, +} + +/// `externalBook`: another workbook, what its formulas use of it, and the values last read from it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ExternalBook { + /// The other workbook as its relationship's target is written (`Src%20One.xlsx`, + /// `sub/three.xlsx`, a URL); `None` without one. + pub target: Option, + /// `sheetNames`: the other workbook's sheets, which `sheet_id`s index. + pub sheet_names: Vec, + pub defined_names: Vec, + /// `sheetDataSet`: the cached cells, one entry per cached sheet. + pub sheet_data: Vec, +} + +/// `definedName` in an external book: a name in the other workbook that formulas here use. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ExternalName { + pub name: String, + /// `refersTo` as written (`='Data'!$A$1:$A$3`, `#REF!`); `None` when the other workbook didn't + /// define it. + pub refers_to: Option, + /// `sheetId`: the sheet it is scoped to, an index into [`ExternalBook::sheet_names`]. + pub sheet_id: Option, +} + +/// `sheetData` in an external book: the cached cells of one sheet. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ExternalSheetData { + /// An index into [`ExternalBook::sheet_names`]. + pub sheet_id: u32, + /// `refreshError`: the last update of this sheet's cells failed. + pub refresh_error: bool, + /// The cells, in file order: `Value::Empty` for a cell with no value. + pub cells: Vec<(CellRef, Value)>, +} + +impl ExternalLink { + /// An external link part read with [`crate::ns::CANONICAL`], with its relationships (for the + /// target). + pub fn read(root: &El, rels: &Rels) -> ExternalLink { + let Some(book) = root.child("externalBook") else { return ExternalLink::Other }; + let target = book.attr_or_plain("r:id").and_then(|id| rels.by_id(id)).map(|r| r.target_raw.clone()); + let sheet_names = book + .child("sheetNames") + .map(|s| s.children("sheetName").map(|n| n.attr("val").unwrap_or_default().to_string()).collect()) + .unwrap_or_default(); + let defined_names = book + .child("definedNames") + .map(|d| { + d.children("definedName") + .map(|n| ExternalName { + name: n.attr("name").unwrap_or_default().to_string(), + refers_to: n.attr("refersTo").map(str::to_string), + sheet_id: n.attr_u32("sheetId"), + }) + .collect() + }) + .unwrap_or_default(); + let sheet_data = book + .child("sheetDataSet") + .map(|set| { + set.children("sheetData") + .map(|d| ExternalSheetData { + sheet_id: d.attr_u32("sheetId").unwrap_or(0), + refresh_error: d.flag("refreshError", false), + cells: d.children("row").flat_map(|r| r.children("cell")).filter_map(cell).collect(), + }) + .collect() + }) + .unwrap_or_default(); + ExternalLink::Book(ExternalBook { target, sheet_names, defined_names, sheet_data }) + } +} + +/// A cached `cell`: its value by `t` (a number by default; `str`, `b`, `e`). One without a +/// readable reference is skipped. +fn cell(c: &El) -> Option<(CellRef, Value)> { + let at = CellRef::parse(c.attr("r")?)?; + let Some(v) = c.child("v").map(|v| v.text().into_owned()) else { return Some((at, Value::Empty)) }; + let value = match c.attr("t") { + Some("str" | "s" | "inlineStr") => Value::Text(v.into()), + Some("b") => Value::Bool(v.trim() == "1" || v.trim().eq_ignore_ascii_case("true")), + Some("e") => CellError::parse(v.trim()).map_or(Value::Text(v.into()), Value::Error), + _ => v.trim().parse::().map_or(Value::Text(v.into()), Value::number), + }; + Some((at, value)) +} diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 14d1a9f3c..0e927a314 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -51,6 +51,7 @@ mod document; mod drawing; +mod external; #[macro_use] mod features; pub mod ns; @@ -74,6 +75,7 @@ pub use craft_sheet::{ }; pub use document::{Document, DrawingPart, KeptPart, PivotCachePart, PivotTablePart, TablePart, Worksheet, XlsxKind}; pub use drawing::{Anchor, Drawing, Item, Marker, ObjectKind, Placement}; +pub use external::{ExternalBook, ExternalLink, ExternalName, ExternalSheetData}; pub use features::{ Break, CfRule, Cfvo, ColorScale, Comment, Comments, ConditionalFormatting, DataBar, DataValidation, DataValidations, Features, HeaderFooter, Hyperlink, IconSet, NoteShape, PageMargins, PageSetup, Pane, Print, PrintOptions, Selection, SheetFormat, SheetView, Table, TableColumn, diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index 44b0fbf22..08c4078e5 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -7,6 +7,7 @@ use craft_drawingml::chart::Chart; use craft_drawingml::theme::Theme; use crate::drawing::Drawing; +use crate::external::ExternalLink; use crate::features::{Comments, NoteShape, Table}; use crate::pivot::{CacheRecord, PivotCacheDefinition, PivotTableDefinition, read_record}; use crate::sheet::{Row, RowReader, SheetPart}; @@ -34,6 +35,9 @@ pub struct Package<'a> { binary_links: Option>, /// Shared strings in a binary workbook, once counted: a cell's index is checked against it. binary_strings: Option, + /// A binary workbook's external links, read once with its workbook part, for the formulas' + /// index and for [`Package::external_links`]. + binary_external: Option>>, } /// Is this a binary workbook (`.xlsb`): a package whose one workbook relationship points at a @@ -72,6 +76,7 @@ impl<'a> Package<'a> { budget: xlsb::Budget::default(), binary_links: None, binary_strings: None, + binary_external: None, }) } @@ -152,8 +157,21 @@ impl<'a> Package<'a> { let (mut wb, mut links, names) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; if let Some(links) = links.as_mut() { self.index_tables(&wb, links)?; + let (by_part, infos) = self.read_binary_external_links(&wb)?; + // A reference that could not be read keeps its place, so these match unless + // the cap was reached. + if infos.len() == links.external_count() { + for (k, info) in infos.into_iter().enumerate() { + if let Some(info) = info { + links.set_external(k, info); + } + } + } else { + self.warn("XLSB: the external links could not be matched to their parts; formulas through them keep their saved results"); + } + self.binary_external = Some(by_part); } - // Names after tables: a name's formula may use a structured reference. + // Both table and external metadata must precede defined-name decoding. xlsb::read_names(&mut wb, names, links.as_mut(), &self.limits, &self.budget, &mut self.warnings); self.binary_links = Some(links); return Ok(wb); @@ -444,6 +462,99 @@ impl<'a> Package<'a> { Ok(root.map(|r| craft_drawingml::theme::read_theme(&mut craft_drawingml::part::NoSource, &r))) } + /// The workbook's external links, one entry per [`Workbook::external_references`], so a + /// formula's `[n]` is entry `n - 1`: the part's name and its link, `None` (with a warning) + /// for a part that is missing or does not read. + /// For a binary workbook these are the links read with its workbook part. + pub fn external_links(&mut self, workbook: &Workbook) -> Result)>, Error> { + let rels = self.workbook_rels()?; + let mut out = Vec::with_capacity(workbook.external_references.len()); + for id in &workbook.external_references { + let Some(rel) = rels.by_id(id).filter(|r| !r.external) else { + self.warn(format!("external link {id}: the relationship is missing")); + out.push((String::new(), None)); + continue; + }; + let part = rel.target.clone(); + // The caller may reorder or replace the public relationship IDs. Reuse the + // decoded part, not its former position, without charging its binary budget again. + if let Some(link) = self.binary_external.as_ref().and_then(|read| read.get(&part)) { + out.push((part, link.clone())); + continue; + } + let link = match self.external_link(&part) { + Ok(link) => link, + Err(Error::TooLarge(m)) => return Err(Error::TooLarge(m)), + Err(e) => { + self.warn(format!("skipped {part}: {e}")); + None + } + }; + if self.binary.is_some() { + self.binary_external.get_or_insert_with(Default::default).insert(part.clone(), link.clone()); + } + out.push((part, link)); + } + Ok(out) + } + + /// One external link part, `None` when it is missing. + fn external_link(&mut self, part: &str) -> Result, Error> { + let rels = self.opc.rels(part)?; + if let Some(types) = &self.binary { + xlsb::check_type(types, part, xlsb::EXTERNAL_LINK)?; + let Some(bytes) = self.opc.read(part)? else { return Ok(None) }; + return Ok(Some(xlsb::external_link(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?.0)); + } + Ok(self.optional_xml(part)?.map(|root| ExternalLink::read(&root, &rels))) + } + + /// Reads each of a binary workbook's external link parts once: the unique links by part name + /// and the formula metadata in reference order. A part that is missing or does not read is + /// `None`, with a warning: formulas through it keep their saved results. + #[allow(clippy::type_complexity)] + fn read_binary_external_links( + &mut self, + wb: &Workbook, + ) -> Result<(std::collections::BTreeMap>, Vec>), Error> { + let rels = self.workbook_rels()?; + let mut by_part: std::collections::BTreeMap> = Default::default(); + let mut infos_by_part: std::collections::BTreeMap> = Default::default(); + let mut infos = Vec::with_capacity(wb.external_references.len()); + for id in &wb.external_references { + let Some(rel) = rels.by_id(id).filter(|r| !r.external) else { + self.warn(format!("external link {id}: the relationship is missing")); + infos.push(None); + continue; + }; + let part = rel.target.clone(); + if let Some(info) = infos_by_part.get(&part) { + infos.push(info.clone()); + continue; + } + let read = (|| { + if let Some(types) = &self.binary { + xlsb::check_type(types, &part, xlsb::EXTERNAL_LINK)?; + } + let bytes = self.required(&part)?; + let part_rels = self.opc.rels(&part)?; + xlsb::external_link(&bytes, &part_rels, &self.limits, &self.budget, &mut self.warnings) + })(); + let (link, info) = match read { + Ok((link, info)) => (Some(link), Some(info)), + Err(Error::TooLarge(m)) => return Err(Error::TooLarge(m)), + Err(e) => { + self.warn(format!("skipped {part}: {e}; formulas through it keep their saved results")); + (None, None) + } + }; + by_part.insert(part.clone(), link); + infos_by_part.insert(part, info.clone()); + infos.push(info); + } + Ok((by_part, infos)) + } + /// A part of a binary workbook, checked against its content type. fn binary_part(&mut self, part: &str, content_type: &str) -> Result, Error> { if let Some(types) = &self.binary { diff --git a/crates/xlsx/src/workbook.rs b/crates/xlsx/src/workbook.rs index f3ef9bafb..7fd86afc2 100644 --- a/crates/xlsx/src/workbook.rs +++ b/crates/xlsx/src/workbook.rs @@ -107,8 +107,12 @@ pub struct Workbook { pub active_tab: Option, /// `pivotCaches`, in order. pub pivot_caches: Vec, + /// `externalReferences`: the relationship ids of the external link parts, in order. A + /// formula's `[1]` is the first ([`crate::Package::external_links`] reads them). A reference + /// without one is an empty id, so the ones after it keep their numbers. + pub external_references: Vec, /// The whole part, for everything not lifted out above (calculation settings, views, - /// protection, pivot caches, external references). Empty for a binary workbook. + /// protection). Empty for a binary workbook. pub root: El, } @@ -152,6 +156,9 @@ impl Workbook { .filter_map(|c| Some(PivotCacheEntry { cache_id: c.attr_u32("cacheId")?, rel_id: c.attr_or_plain("r:id")?.to_string() })) .collect(); } + if let Some(refs) = root.child("externalReferences") { + wb.external_references = refs.children("externalReference").map(|r| r.attr_or_plain("r:id").unwrap_or_default().to_string()).collect(); + } if let Some(views) = root.child("bookViews") { let view = views .children("workbookView") @@ -165,7 +172,8 @@ impl Workbook { /// The workbook part's root: `sheets` and `definedNames` regenerated from the fields, the /// date system set in `workbookPr` and the active tab in the view it was read from; - /// `pivotCaches` from [`Workbook::pivot_caches`]; everything else in [`Workbook::root`] as + /// `pivotCaches` from [`Workbook::pivot_caches`], `externalReferences` from + /// [`Workbook::external_references`]; everything else in [`Workbook::root`] as /// kept. Each sheet's `r:id` is written as [`SheetEntry::rel_id`] holds it. pub fn to_el(&self) -> El { let root = if self.root.name.is_empty() { El::new("workbook") } else { self.root.clone() }; @@ -221,6 +229,17 @@ impl Workbook { e }), ), + ( + "externalReferences", + (!self.external_references.is_empty()).then(|| { + let mut e = El::new("externalReferences"); + for id in &self.external_references { + let r = El::new("externalReference"); + e.push(if id.is_empty() { r } else { r.with_attr("r:id", id) }); + } + e + }), + ), ]; assemble(&root, WORKBOOK, owned) } diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index b45b48808..fa6d5d513 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -6,6 +6,7 @@ //! ([`styles`]). A record that does not parse fails the read. mod expr; +mod external; mod formula; mod ftab; mod styles; @@ -22,8 +23,9 @@ use crate::sheet::{Cell, CellFormula, CellValue, Column, FormulaKind, Row, Sheet use crate::strings::StringItem; use crate::workbook::{DefinedName, SheetEntry, SheetKind, Workbook}; use crate::{Error, Limits, Warnings}; -pub(crate) use formula::Links; +pub(crate) use external::{EXTERNAL_LINK, external_link}; use formula::{Book, Mode, Name, Xti}; +pub(crate) use formula::{ExternalInfo, Links}; pub(crate) use styles::styles; pub(crate) use table::{TABLE, index_table, table}; @@ -39,6 +41,8 @@ const MAX_SHEETS: usize = 1024; const MAX_BOOKS: usize = 65_536; /// Most merged ranges in one worksheet. const MAX_MERGES: usize = 100_000; +/// External link references read at most. +const MAX_EXTERNAL_LINKS: usize = 65_536; /// Table parts one worksheet lists at most. const MAX_TABLE_PARTS: usize = 65_536; /// Most column records in one worksheet: one per column. @@ -325,6 +329,19 @@ pub(crate) fn workbook( return Ok((wb, links, Names { pending, sheets: bundle_sheets })); } 39 | 355 | 357 | 358 | 362 | 667 => { + // BrtSupBookSrc: an external link part, by its relationship id, in the order a + // formula's `[1]` counts. + // One that can't be read keeps its place, empty, so later links keep their numbers. + if id == 355 && wb.external_references.len() < MAX_EXTERNAL_LINKS { + let mut b = Bytes::new(payload); + match b.text(255).and_then(|rel| b.finish().map(|()| rel)) { + Ok(rel) => wb.external_references.push(rel), + Err(_) => { + warnings.warn("XLSB: an external link reference could not be read"); + wb.external_references.push(String::new()); + } + } + } if let Some(l) = links.as_mut() && link_record(id, payload, l, &mut pending).is_err() { @@ -614,7 +631,10 @@ fn link_record(id: u16, payload: &[u8], links: &mut Links, pending: &mut Vec Book::Addin, }); } - 355 => links.books.push(Book::External), + 355 => { + links.books.push(Book::External(links.external.len())); + links.external.push(None); + } 362 => { // [MS-XLSB] 2.4.672: cXti "MUST be less than 65536" (PtgRef3d's ixti is 16 bits). let count = b.u32()?; diff --git a/crates/xlsx/src/xlsb/expr.rs b/crates/xlsx/src/xlsb/expr.rs index 7d51551d9..990467553 100644 --- a/crates/xlsx/src/xlsb/expr.rs +++ b/crates/xlsx/src/xlsb/expr.rs @@ -35,6 +35,9 @@ pub(crate) enum SheetSel { Named(String), /// 3-D span `Sheet1:Sheet3`. Span(String, String), + /// A sheet, or a span of sheets, of the external link numbered `[n]`: `[1]Data!`, + /// `'[1]Other Sheet'!`, `'[1]A:C'!` (Excel quotes an external span whatever its names). + External(usize, String, Option), } #[derive(Clone, Debug, PartialEq, Eq)] @@ -122,6 +125,9 @@ pub(crate) enum Expr { Ref(Reference), /// A defined name. Name(String), + /// Text the decoder spelled itself, written as is (a name in another workbook, + /// `[1]!ExtName`). + Verbatim(String), /// Spaces and line breaks typed before and after an expression (`PtgAttrSpace`), which /// `.xlsx` formula text keeps. Spaced(String, Box, String), @@ -161,6 +167,10 @@ fn push_reference(s: &mut String, r: &Reference) { let _ = write!(s, "{joined}!"); } } + SheetSel::External(n, a, b) => { + s.push_str(&external_sheet(*n, a, b.as_deref())); + s.push('!'); + } } let dollar = |abs: bool| if abs { "$" } else { "" }; match &r.kind { @@ -184,6 +194,19 @@ fn push_reference(s: &mut String, r: &Reference) { } } +/// `[n]` and a sheet or span of an external link, quoted as Excel quotes it, without the `!`. +/// After `[n]`, a sheet that reads as a cell, an R1C1 reference or `TRUE` needs no quotes +/// (`[1]A1!A1`, `[1]C!A1`); one starting with a digit or holding other characters does +/// (`'[1]2023'!A1`, `'[1]a b'!A1`), and a span always does. +pub(crate) fn external_sheet(n: usize, a: &str, b: Option<&str>) -> String { + let plain = |s: &str| s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '.'); + match b { + None if plain(a) => format!("[{n}]{a}"), + None => format!("'[{n}]{}'", a.replace('\'', "''")), + Some(b) => format!("'[{n}]{}:{}'", a.replace('\'', "''"), b.replace('\'', "''")), + } +} + /// Removes trailing zeros (and a trailing point) from a decimal string. fn trim_decimal(s: &str) -> String { if s.contains('.') { @@ -320,6 +343,7 @@ fn write_expr(s: &mut String, e: &Expr) { s.push('}'); } Expr::Ref(r) => push_reference(s, r), + Expr::Verbatim(t) => s.push_str(t), Expr::Name(n) => match sheet_split(n) { // A sheet-qualified name holds the bare sheet name (`My Sheet!Total`): quote it so it parses back. Some((sheet, name)) => { diff --git a/crates/xlsx/src/xlsb/external.rs b/crates/xlsx/src/xlsb/external.rs new file mode 100644 index 000000000..33080366a --- /dev/null +++ b/crates/xlsx/src/xlsb/external.rs @@ -0,0 +1,224 @@ +//! External link parts ([MS-XLSB] 2.1.7.25, `externalLinkN.bin`) into the [`ExternalLink`] an +//! `externalLinkN.xml` reads as, and what formulas need of them to spell `[1]Sheet!A1`. + +use craft_opc::Rels; +use craft_sheet::{CellRef, MAX_COLS, MAX_ROWS, Value, push_col}; + +use super::formula::{ExternalInfo, ExternalNameInfo}; +use super::{Budget, Bytes, Records, error, invalid}; +use crate::external::{ExternalBook, ExternalLink, ExternalName, ExternalSheetData}; +use crate::{Error, Limits, Warnings}; + +/// The content type of an external link part. +pub(crate) const EXTERNAL_LINK: &str = "application/vnd.ms-excel.externalLink"; + +/// Sheet names and names one external link holds at most ([MS-XLSB] 2.4.827: fewer than 65,535 +/// sheets). +const MAX_ITEMS: usize = 65_535; + +/// A sheet as `refersTo` writes it: always quoted, `'` doubled. +fn quoted(name: &str) -> String { + format!("'{}'", name.replace('\'', "''")) +} + +/// One end of a reference in an external name (`RgceLocSmall`'s column: 14 bits, then the +/// column-relative and row-relative flags). +fn cell(row: u16, col: u16) -> Result { + let c = u32::from(col & 0x3FFF); + if c >= MAX_COLS { + return Err(invalid("external name outside the grid")); + } + let mut s = String::new(); + if col & 0x4000 == 0 { + s.push('$'); + } + push_col(&mut s, c); + if col & 0x8000 == 0 { + s.push('$'); + } + s.push_str(&(u32::from(row) + 1).to_string()); + Ok(s) +} + +/// `BrtSupNameFmla`'s value ([MS-XLSB] 2.4.818) as `refersTo`: an `ExtPtgRef3D` or +/// `ExtPtgArea3D` (`='Data'!$A$1:$A$3`, a span `='A:C'!$A$1`), or `#REF!` for the error forms, as +/// Excel writes them. `None` when the other workbook doesn't define the name (no value). +fn refers_to(val: &[u8], sheets: &[String]) -> Result, Error> { + let mut b = Bytes::new(val); + if val.is_empty() { + return Ok(None); + } + let ptg = b.u8()?; + if matches!(ptg, 0x1C | 0x3C | 0x3D) { + return Ok(Some("#REF!".into())); + } + let (first, last) = (usize::from(b.u16()?), usize::from(b.u16()?)); + let sheet = |i: usize| sheets.get(i).ok_or_else(|| invalid("external name on a missing sheet")); + let tabs = if first == last { quoted(sheet(first)?) } else { quoted(&format!("{}:{}", sheet(first)?, sheet(last)?)) }; + let area = match ptg { + 0x3A => { + let (r, c) = (b.u16()?, b.u16()?); + cell(r, c)? + } + 0x3B => { + let (r0, r1, c0, c1) = (b.u16()?, b.u16()?, b.u16()?, b.u16()?); + format!("{}:{}", cell(r0, c0)?, cell(r1, c1)?) + } + _ => return Err(invalid("unknown external name formula")), + }; + b.finish()?; + Ok(Some(format!("={tabs}!{area}"))) +} + +/// An external link part: the link, and what formulas need of it. `rels` are the part's own +/// relationships (the other workbook's path). +pub(crate) fn external_link( + bytes: &[u8], + rels: &Rels, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, +) -> Result<(ExternalLink, ExternalInfo), Error> { + let mut records = Records::new(bytes, limits, budget); + let Some((360, payload)) = records.next(warnings)? else { return Err(invalid("missing external link begin record")) }; + // BrtBeginSupBook: the link's type, then its strings. + let mut b = Bytes::new(payload); + let sbt = b.u16()?; + let first = b.string(32_767, true)?; + b.string(32_767, true)?; + b.finish()?; + let dde = sbt != 0; + if sbt > 2 { + return Err(invalid("unknown external link type")); + } + let mut book = ExternalBook { + target: if dde { None } else { first.as_deref().and_then(|id| rels.by_id(id)).map(|r| r.target_raw.clone()) }, + ..ExternalBook::default() + }; + let mut info = ExternalInfo { dde, ..ExternalInfo::default() }; + let mut name: Option = None; + let mut table: Option = None; + let mut row: Option = None; + while let Some((id, payload)) = records.next(warnings)? { + let mut b = Bytes::new(payload); + match id { + // BrtSupTabs. + 359 => { + let count = b.u32()? as usize; + if count > MAX_ITEMS || !book.sheet_names.is_empty() { + return Err(invalid("invalid external sheet list")); + } + for _ in 0..count { + let s = b.text(31)?; + budget.text(s.len(), limits)?; + book.sheet_names.push(s); + } + b.finish()?; + } + // BrtSupNameStart. + 577 => { + if name.is_some() || info.names.len() >= MAX_ITEMS { + return Err(invalid("invalid external name")); + } + let text = b.text(255)?; + b.finish()?; + budget.text(text.len(), limits)?; + name = Some(ExternalName { name: text, ..ExternalName::default() }); + } + // BrtSupNameFmla. + 585 => { + let n = name.as_mut().ok_or_else(|| invalid("external name formula outside a name"))?; + let cb = b.u32()? as usize; + let val = b.take(cb)?; + b.finish()?; + n.refers_to = refers_to(val, &book.sheet_names)?; + } + // BrtSupNameBits: an external name's ExternalNameProperties (fBuiltIn, then iSheet, + // 1-based); a DDE or OLE item's properties. + 586 => { + let n = name.as_mut().ok_or_else(|| invalid("external name properties outside a name"))?; + b.u16()?; + let sheet = b.u32()?; + b.u8()?; + b.finish()?; + if !dde && sheet > 0 { + if sheet as usize > book.sheet_names.len() { + return Err(invalid("external name scoped to a missing sheet")); + } + n.sheet_id = Some(sheet - 1); + } + } + // BrtSupNameEnd. + 587 => { + let n = name.take().ok_or_else(|| invalid("external name end without a name"))?; + info.names.push(ExternalNameInfo { name: n.name.clone(), sheet: n.sheet_id.map(|s| s as usize) }); + if !dde { + book.defined_names.push(n); + } + } + // BrtExternTableStart: a sheet's cached cells. + 363 => { + if table.is_some() { + return Err(invalid("nested external cell cache")); + } + let sheet_id = b.u32()?; + let flags = b.u8()?; + b.finish()?; + if sheet_id as usize >= book.sheet_names.len() { + return Err(invalid("external cell cache for a missing sheet")); + } + table = Some(ExternalSheetData { sheet_id, refresh_error: flags & 1 != 0, cells: vec![] }); + row = None; + } + // BrtExternRowHdr. + 366 => { + let r = b.u32()?; + b.finish()?; + if r >= MAX_ROWS { + return Err(invalid("external cell outside the grid")); + } + row = Some(r); + } + // External cells: blank, Boolean, error, number, string. + 367..=371 => { + let t = table.as_mut().ok_or_else(|| invalid("external cell outside its cache"))?; + let r = row.ok_or_else(|| invalid("external cell outside a row"))?; + let c = b.u32()?; + if c >= MAX_COLS { + return Err(invalid("external cell outside the grid")); + } + let value = match id { + 367 => Value::Empty, + 369 => Value::Bool(b.u8()? != 0), + 370 => Value::Error(error(b.u8()?)?), + 368 => Value::number(b.f64()?), + _ => { + let s = b.text(32_767)?; + budget.text(s.len(), limits)?; + Value::Text(s.into()) + } + }; + b.finish()?; + budget.cell(limits)?; + t.cells.push((CellRef::new(r, c), value)); + } + // BrtExternTableEnd. + 364 => { + b.finish()?; + book.sheet_data.push(table.take().ok_or_else(|| invalid("external cell cache end without a cache"))?); + } + // BrtEndSupBook. + 588 => { + if name.is_some() || table.is_some() { + return Err(invalid("incomplete external link")); + } + records.end(payload, warnings)?; + info.sheets = book.sheet_names.clone(); + let link = if dde { ExternalLink::Other } else { ExternalLink::Book(book) }; + return Ok((link, info)); + } + _ => {} + } + } + Err(invalid("missing external link end record")) +} diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs index 40d461db1..43e77dfd2 100644 --- a/crates/xlsx/src/xlsb/formula.rs +++ b/crates/xlsx/src/xlsb/formula.rs @@ -14,9 +14,9 @@ use std::collections::HashMap; use std::sync::Arc; -use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS}; +use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS, quote_sheet}; -use super::expr::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, UnOp}; +use super::expr::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, UnOp, external_sheet}; use super::ftab::function; /// Formula token bytes decoded at most (a cell formula holds at most 16,384). @@ -127,8 +127,26 @@ pub(super) enum Book { Same, /// `BrtSupAddin`: add-in functions. Addin, - /// `BrtSupBookSrc`: another workbook, DDE or OLE. Never followed. - External, + /// `BrtSupBookSrc`: another workbook, DDE or OLE, by its place among them: `.xlsx`'s `[1]` + /// is the first. + External(usize), +} + +/// What formulas need of an external link part: the other workbook's sheets, and its names +/// (or DDE and OLE items) in record order, which `PtgNameX` indexes from 1. +#[derive(Clone, Debug, Default)] +pub(crate) struct ExternalInfo { + pub sheets: Vec, + pub names: Vec, + /// A DDE or OLE link: its names are items (`[2]!'R1C1'`). + pub dde: bool, +} + +/// A name in another workbook, and the sheet it is scoped to. +#[derive(Clone, Debug)] +pub(crate) struct ExternalNameInfo { + pub name: String, + pub sheet: Option, } /// Xti ([MS-XLSB] 2.5.173): a supporting link and a range of its sheets. @@ -171,6 +189,9 @@ pub(crate) struct Links { pub(super) names: Vec, pub(super) books: Vec, pub(super) xti: Vec, + /// Each external link part, by its place among the `BrtSupBookSrc`s: `None` when it could + /// not be read, and formulas through it keep their saved results. + pub(super) external: Vec>, /// Every table by its `idList`, which `PtgList` names: `None` for an id two tables share. pub(super) tables: HashMap>, } @@ -188,6 +209,58 @@ pub(super) fn is_param(name: &str) -> bool { } impl Links { + /// How many `BrtSupBookSrc`s the workbook has. + pub(crate) fn external_count(&self) -> usize { + self.external.len() + } + + /// Sets what formulas need of external link `k`, the `k`-th `BrtSupBookSrc`. + pub(crate) fn set_external(&mut self, k: usize, info: ExternalInfo) { + if let Some(slot) = self.external.get_mut(k) { + *slot = Some(info); + } + } + + /// External link `k` as formulas read it. + fn external(&self, k: usize) -> Result<&ExternalInfo, Unsupported> { + self.external.get(k).and_then(Option::as_ref).ok_or(Unsupported("references to other workbooks whose link could not be read")) + } + + /// The sheets of external link `k` a 3-D reference names: `[1]Data`, `'[1]A:C'`. + fn external_sheets(&self, k: usize, x: &Xti) -> Result { + let link = self.external(k)?; + if link.dde { + return Err(Unsupported("references through DDE or OLE links")); + } + let sheet = + |i: i32| usize::try_from(i).ok().and_then(|i| link.sheets.get(i)).ok_or(Unsupported("references to missing sheets of other workbooks")); + let (a, b) = (sheet(x.first)?, sheet(x.last)?); + Ok(SheetSel::External(k + 1, a.clone(), (x.first != x.last).then(|| b.clone()))) + } + + /// `PtgNameX` through external link `k`: `[1]!ExtName`, `[1]Data!Local` for a name scoped to a + /// sheet, `[2]!'R1C1'` for a DDE item. + fn external_name(&self, k: usize, x: &Xti, index: u32) -> Result { + let link = self.external(k)?; + let n = usize::try_from(index).ok().and_then(|i| i.checked_sub(1)).and_then(|i| link.names.get(i)); + let n = n.ok_or(Unsupported("reference to a missing name in another workbook"))?; + // -1: a deleted sheet of the other workbook, unlike -2, the whole workbook. + if x.first == -1 || x.last == -1 { + return Err(Unsupported("references to deleted sheets of other workbooks")); + } + if link.dde { + return Ok(format!("[{}]!{}", k + 1, quote_sheet(&n.name))); + } + let sheet = usize::try_from(x.first) + .ok() + .or(n.sheet) + .map(|i| link.sheets.get(i).ok_or(Unsupported("references to missing sheets of other workbooks"))); + Ok(match sheet { + Some(s) => format!("{}!{}", external_sheet(k + 1, s?, None), n.name), + None => format!("[{}]!{}", k + 1, n.name), + }) + } + /// `PtgName`'s and `PtgNameX`'s name: a 1-based index into every `BrtName`. A cell formula /// using a defined name the reader doesn't give would calculate to `#NAME?`, so it keeps its /// saved result instead. @@ -205,7 +278,7 @@ impl Links { let x = self.xti.get(usize::from(ixti)).ok_or(Unsupported("reference to a missing sheet link"))?; match usize::try_from(x.book).ok().and_then(|b| self.books.get(b)) { Some(Book::This) => Ok(x), - Some(Book::External) => Err(Unsupported("references to other workbooks (external links)")), + Some(Book::External(_)) => Err(Unsupported("references to other workbooks (external links)")), Some(_) => Err(Unsupported("references through add-in or same-sheet links")), None => Err(Unsupported("reference to a missing workbook link")), } @@ -213,7 +286,11 @@ impl Links { /// The sheets a 3-D reference names, or `None` for a deleted sheet (the reference is `#REF!`). fn sheet_sel(&self, ixti: u16) -> Result, Unsupported> { - let x = self.this_book(ixti)?; + let x = self.xti.get(usize::from(ixti)).ok_or(Unsupported("reference to a missing sheet link"))?; + if let Some(Book::External(k)) = usize::try_from(x.book).ok().and_then(|b| self.books.get(b)) { + return self.external_sheets(*k, x).map(Some); + } + self.this_book(ixti)?; // -1: "the first sheet in the reference cannot be found" (a deleted sheet). if x.first == -1 || x.last == -1 { return Ok(None); @@ -344,6 +421,11 @@ fn reference(sheet: Option, kind: RefKind) -> Expr { } } +/// Sheet link `ixti`. +fn xti(links: &Links, ixti: u16) -> Result<&Xti, Unsupported> { + links.xti.get(usize::from(ixti)).ok_or(Unsupported("reference to a missing sheet link")) +} + /// Decodes a formula's `rgce` (tokens) with its `rgcb` (extra data for array constants and /// cached areas). Returns the expression, with names in their file spelling, or why it can't be /// represented. A shared formula's tokens are decoded once for each of its cells @@ -564,17 +646,24 @@ pub(super) fn decode_using(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode, push(&mut stack, kids, Expr::Error(CellError::Ref))?; } 0x39 => { - // PtgNameX: a name through a supporting link. Through this workbook's own link - // it is a sheet-scoped name used from another sheet, which `.xlsx` spells - // `'Other Sheet'!Local`: Excel's files show it, [MS-XLSB] doesn't say. + // Local names retain dependency tracking; external names use their link number. let ixti = t.u16()?; let index = t.u32()?; - links.this_book(ixti)?; - let name = links.name(index, mode)?; - used.extend(usize::try_from(index).ok().and_then(|i| i.checked_sub(1))); - let sheet = name.scope.and_then(|s| links.sheets.get(usize::try_from(s).ok()?).cloned().flatten()); - let sheet = sheet.ok_or(Unsupported("names in other workbooks or on other sheets"))?; - push(&mut stack, kids, Expr::Name(format!("{sheet}!{}", name.text)))?; + let x = xti(links, ixti)?; + match usize::try_from(x.book).ok().and_then(|b| links.books.get(b)) { + Some(Book::External(k)) => { + let text = links.external_name(*k, x, index)?; + push(&mut stack, kids, Expr::Verbatim(text))?; + } + _ => { + links.this_book(ixti)?; + let name = links.name(index, mode)?; + used.extend(usize::try_from(index).ok().and_then(|i| i.checked_sub(1))); + let sheet = name.scope.and_then(|s| links.sheets.get(usize::try_from(s).ok()?).cloned().flatten()); + let sheet = sheet.ok_or(Unsupported("names in other workbooks or on other sheets"))?; + push(&mut stack, kids, Expr::Name(format!("{sheet}!{}", name.text)))?; + } + } } 0x3A => { let ixti = t.u16()?; @@ -661,6 +750,7 @@ fn list(t: &mut Bytes<'_>, links: &Links) -> Result { return Err(Unsupported("structured references to deleted tables or to tables in other workbooks")); } // The table's sheet link: a table is always in this workbook, on one of its sheets. + links.this_book(ixti)?; links.sheet_sel(ixti)?; let table = links.tables.get(&index).and_then(Option::as_ref).ok_or(Unsupported("structured references to tables the reader could not read"))?; let rows: &[&str] = match (bits >> 2) & 0x1F { diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index ef1464dd4..757389817 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1043,7 +1043,7 @@ fn defined_names_are_read_as_their_xlsx_spelling() { for why in ["defined names whose formula could not be read", "other workbooks", "names in other workbooks or on other sheets"] { assert!(warned(&book, why), "{why}: {:?}", book.warnings); } - for why in ["(references to other workbooks (external links))", "(names of sheets the reader skips)"] { + for why in ["(references to other workbooks whose link could not be read)", "(names of sheets the reader skips)"] { assert!(book.warnings.iter().any(|w| w.contains("defined names were left out") && w.contains(why)), "{why}: {:?}", book.warnings); } } @@ -2013,6 +2013,215 @@ fn a_spent_formula_allowance_skips_decoding() { assert!(!warned(&wb, "unknown formula token"), "{:?}", wb.warnings); } +// External links ([MS-XLSB] 2.1.7.25): external link parts assembled from the specification's +// records, and the `externalLinkN.xml` Excel writes for the same links. + +const LINK_TYPE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink"; +const LINK_PATH: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath"; + +/// `BrtSupNameStart`, `BrtSupNameFmla` (`val`), `BrtSupNameBits` (`iSheet`, 1-based), `BrtSupNameEnd`. +fn ext_name(name: &str, val: &[u8], sheet: u32) -> Vec { + let bits = [&0u16.to_le_bytes()[..], &sheet.to_le_bytes(), &[0]].concat(); + [record(577, &wide(name)), record(585, &[&(val.len() as u32).to_le_bytes()[..], val].concat()), record(586, &bits), record(587, &[])].concat() +} + +/// An external cell: `BrtExternCellReal` (368), `BrtExternCellString` (371), `BrtExternCellBool` +/// (369), `BrtExternCellError` (370) or `BrtExternCellBlank` (367). +fn ext_cell(id: u16, col: u32, value: &[u8]) -> Vec { + record(id, &[&col.to_le_bytes()[..], value].concat()) +} + +/// A link to `Src One.xlsx` (relationship rId1) with sheets Data and Other Sheet, the names +/// ExtName (workbook-level) and Local (scoped to Data), and cached cells. +fn workbook_link() -> Vec { + let area = [&[0x3Bu8][..], &[0, 0, 0, 0], &[0, 0, 2, 0, 0, 0, 0, 0]].concat(); + let cell = [&[0x3Au8][..], &[0, 0, 0, 0], &[0, 0, 1, 0]].concat(); + [ + record(360, &[&0u16.to_le_bytes()[..], &wide("rId1"), &u32::MAX.to_le_bytes()].concat()), + record(359, &[&2u32.to_le_bytes()[..], &wide("Data"), &wide("Other Sheet")].concat()), + ext_name("ExtName", &area, 0), + ext_name("Local", &cell, 1), + record(363, &[0, 0, 0, 0, 0]), + record(366, &0u32.to_le_bytes()), + ext_cell(368, 0, &1f64.to_le_bytes()), + ext_cell(371, 1, &wide("text")), + record(366, &1u32.to_le_bytes()), + ext_cell(369, 0, &[1]), + ext_cell(370, 1, &[0x07]), + ext_cell(367, 2, &[]), + record(364, &[]), + record(363, &[1, 0, 0, 0, 1]), + record(364, &[]), + record(588, &[]), + ] + .concat() +} + +/// A DDE link (`sbt` 1) to Excel with one item, `R1C1`. +fn dde_link() -> Vec { + [ + record(360, &[&1u16.to_le_bytes()[..], &wide("Excel"), &wide("topic")].concat()), + record(577, &wide("R1C1")), + record(586, &[2, 0, 0, 0, 0, 0, 1]), + record(587, &[]), + record(588, &[]), + ] + .concat() +} + +const LINK_XML: &str = r#"1text1#DIV/0!"#; +const DDE_XML: &str = r#""#; + +/// The link part's own relationships: the other workbook. +fn link_rels() -> String { + format!( + r#""# + ) +} + +/// `.xlsx` with the two links, read through `Package::external_links`. +fn xml_links() -> Vec> { + let types = r#""#; + let root = r#""#; + let book = r#""#; + let rels = format!( + r#""# + ); + let link_rels = link_rels(); + let bytes = zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", root.as_bytes()), + ("xl/workbook.xml", book.as_bytes()), + ("xl/_rels/workbook.xml.rels", rels.as_bytes()), + ("xl/externalLinks/one.xml", LINK_XML.as_bytes()), + ("xl/externalLinks/_rels/one.xml.rels", link_rels.as_bytes()), + ("xl/externalLinks/two.xml", DDE_XML.as_bytes()), + ]) + .unwrap(); + let mut p = Package::open(&bytes, &Limits::default()).unwrap(); + let wb = p.workbook().unwrap(); + assert_eq!(wb.external_references, ["x1", "x2"]); + // Written back from the field, in order. + let written = wb.to_el(); + let refs = written.child("externalReferences").map(|e| e.children("externalReference").filter_map(|r| r.attr("r:id")).collect::>()); + assert_eq!(refs, Some(vec!["x1", "x2"])); + p.external_links(&wb).unwrap().into_iter().map(|(_, l)| l).collect() +} + +/// `book(false)` with this workbook and the two links as supporting links (BrtSupSelf, then +/// BrtSupBookSrc x1 and x2), and sheet links: Data here; the link's Data, Other Sheet, +/// Data:Other Sheet and the whole workbook; the DDE link; a deleted sheet of the link. +fn book_with_external_links() -> Vec { + let plain = book(false); + let end = record(132, &[]); + let mut xti = 7u32.to_le_bytes().to_vec(); + for (book, first, last) in [(0u32, 0i32, 0i32), (1, 0, 0), (1, 1, 1), (1, 0, 1), (1, -2, -2), (2, -2, -2), (1, -1, -1)] { + xti.extend([book.to_le_bytes(), first.to_le_bytes(), last.to_le_bytes()].concat()); + } + let links = [record(353, &[]), record(357, &[]), record(355, &wide("x1")), record(355, &wide("x2")), record(362, &xti), record(354, &[])]; + [&plain[..plain.len() - end.len()], &links.concat(), &end].concat() +} + +/// A binary package with the two links (`one` as `link`, `two` as the DDE link). +fn external_package(data: &[u8], link: &[u8]) -> Vec { + external_package_with(&book_with_external_links(), data, link) +} + +/// [`external_package`] with another workbook part. +fn external_package_with(book: &[u8], data: &[u8], link: &[u8]) -> Vec { + let rels = RELS.replace( + "", + &format!(r#""#), + ); + let types = TYPES.replace( + "", + r#""#, + ); + let (one, two, strings, link_rels, dde) = (worksheet(data, &[]), worksheet(&[], &[]), sst(), link_rels(), dde_link()); + zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT.as_bytes()), + ("records/book.bin", book), + ("records/_rels/book.bin.rels", rels.as_bytes()), + ("data/one.bin", &one), + ("data/two.bin", &two), + ("text/strings.bin", &strings), + ("links/one.bin", link), + ("links/_rels/one.bin.rels", link_rels.as_bytes()), + ("links/two.bin", &dde), + ]) + .unwrap() +} + +fn binary_links(bytes: &[u8]) -> (Vec>, Vec) { + let mut p = Package::open(bytes, &Limits::default()).unwrap(); + let wb = p.workbook().unwrap(); + assert_eq!(wb.external_references, ["x1", "x2"]); + let links = p.external_links(&wb).unwrap().into_iter().map(|(_, l)| l).collect(); + (links, p.warnings().to_vec()) +} + +#[test] +fn external_links_are_read_as_their_xlsx_spelling() { + let ref3d = |ixti: u16, col: u16| [&[0x5Au8][..], &ixti.to_le_bytes(), &loc(0, col)].concat(); + let name_x = |ixti: u16, index: u32| [&[0x39u8][..], &ixti.to_le_bytes(), &index.to_le_bytes()].concat(); + let cells = [ + ref3d(1, 0), + ref3d(2, REL), + ref3d(3, REL), + name_x(4, 1), + name_x(4, 2), + name_x(5, 1), + // Kept as their saved results: a deleted sheet of the other workbook, a name it doesn't + // have, a name through a deleted sheet. + ref3d(6, 0), + name_x(4, 9), + name_x(6, 1), + ]; + let mut data = row(0); + for (i, rgce) in cells.iter().enumerate() { + data.extend(formula_cell(i as u32 + 1, rgce, &[])); + } + let bytes = external_package(&data, &workbook_link()); + let (links, _) = binary_links(&bytes); + assert_eq!(links, xml_links()); + let wb = read(&bytes).unwrap(); + let got: Vec<_> = (1..=9).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + let want = [ + Some("[1]Data!$A$1"), + Some("'[1]Other Sheet'!A1"), + Some("'[1]Data:Other Sheet'!A1"), + Some("[1]!ExtName"), + Some("[1]Data!Local"), + Some("[2]!'R1C1'"), + None, + None, + None, + ]; + assert_eq!(got, want); + for why in ["missing sheets of other workbooks", "missing name in another workbook", "deleted sheets of other workbooks"] { + assert!(warned(&wb, why), "{why}: {:?}", wb.warnings); + } +} + +#[test] +fn an_unreadable_external_link_keeps_its_formulas_as_values() { + // A truncated link part: its entry is `None`, with a warning, and formulas through it keep + // their saved results; the DDE link after it keeps its number. + let mut link = workbook_link(); + link.truncate(30); + let data = + [row(0), formula_cell(1, &[&[0x5Au8][..], &1u16.to_le_bytes(), &loc(0, 0)].concat(), &[]), formula_cell(2, &[0x39, 5, 0, 1, 0, 0, 0], &[])] + .concat(); + let bytes = external_package(&data, &link); + let (links, warnings) = binary_links(&bytes); + assert_eq!(links, [None, Some(craft_xlsx::ExternalLink::Other)]); + assert!(warnings.iter().any(|w| w.contains("skipped links/one.bin")), "{warnings:?}"); + let wb = read(&bytes).unwrap(); + assert_eq!([1, 2].map(|c| wb.sheets[0].formula(CellRef::new(0, c))), [None, Some("[2]!'R1C1'")]); + assert!(warned(&wb, "other workbooks whose link could not be read"), "{:?}", wb.warnings); +} + #[test] fn a_name_using_a_left_out_name_is_left_out_too() { // 14 Early = Later (a later name), 15 Alias = External (left out: another workbook), @@ -2063,6 +2272,96 @@ fn module_sheets_and_supporting_links_are_bounded() { assert!(wb.warnings.iter().any(|w| w.contains("sheet links or names could not be read")), "{:?}", wb.warnings); } +#[test] +fn external_links_are_read_once_and_keep_their_numbers() { + // The link's five cached cells fit a five-cell allowance: read once with the workbook part, + // not charged again when the links are asked for. + let bytes = external_package(&row(0), &workbook_link()); + let limits = Limits { binary_cells: 5, ..Limits::default() }; + let mut p = Package::open(&bytes, &limits).unwrap(); + let wb = p.workbook().unwrap(); + let links = p.external_links(&wb).unwrap(); + assert!(matches!(&links[0].1, Some(craft_xlsx::ExternalLink::Book(b)) if b.sheet_data[0].cells.len() == 5)); + // A first link whose relationship id can't be read keeps its place, empty: the DDE link is + // still `[2]`. + let book = book_with_external_links(); + let at = book.windows(record(355, &wide("x1")).len()).position(|w| w == record(355, &wide("x1"))).unwrap(); + let book = [&book[..at], &record(355, &[1, 0])[..], &book[at + record(355, &wide("x1")).len()..]].concat(); + let data = [row(0), formula_cell(1, &[0x39, 5, 0, 1, 0, 0, 0], &[])].concat(); + let bytes = external_package_with(&book, &data, &workbook_link()); + let mut p = Package::open(&bytes, &Limits::default()).unwrap(); + let wb = p.workbook().unwrap(); + assert_eq!(wb.external_references, ["", "x2"]); + assert_eq!(p.external_links(&wb).unwrap().into_iter().map(|(_, l)| l).collect::>(), [None, Some(craft_xlsx::ExternalLink::Other)]); + let read = read(&bytes).unwrap(); + assert_eq!(read.sheets[0].formula(CellRef::new(0, 1)), Some("[2]!'R1C1'")); +} + +#[test] +fn duplicate_external_links_share_budget_and_enforce_cache_cap() { + let rels = RELS.replace( + "", + &format!(r#""#), + ); + let types = TYPES.replace("", r#""#); + let mut ptg_ref = vec![0x3A, 1, 0]; + ptg_ref.extend(0u32.to_le_bytes()); + ptg_ref.extend(0u16.to_le_bytes()); + let mut ptg_ref2 = vec![0x3A, 5, 0]; + ptg_ref2.extend(0u32.to_le_bytes()); + ptg_ref2.extend(0u16.to_le_bytes()); + // Adjust xti 5 to point to book 2 (x2), sheet 0..0. + let plain = book(false); + let end = record(132, &[]); + let mut xti = 7u32.to_le_bytes().to_vec(); + for (bk, first, last) in [(0u32, 0i32, 0i32), (1, 0, 0), (1, 1, 1), (1, 0, 1), (1, -2, -2), (2, 0, 0), (1, -1, -1)] { + xti.extend([bk.to_le_bytes(), first.to_le_bytes(), last.to_le_bytes()].concat()); + } + let links_rec = [record(353, &[]), record(357, &[]), record(355, &wide("x1")), record(355, &wide("x2")), record(362, &xti), record(354, &[])]; + let bk = [&plain[..plain.len() - end.len()], &links_rec.concat(), &end].concat(); + let data = [row(0), formula_cell(0, &ptg_ref, &[]), formula_cell(1, &ptg_ref2, &[])].concat(); + let (one, two, strings, lrels, link) = (worksheet(&data, &[]), worksheet(&[], &[]), sst(), link_rels(), workbook_link()); + let bytes = zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT.as_bytes()), + ("records/book.bin", &bk), + ("records/_rels/book.bin.rels", rels.as_bytes()), + ("data/one.bin", &one), + ("data/two.bin", &two), + ("text/strings.bin", &strings), + ("links/one.bin", &link), + ("links/_rels/one.bin.rels", lrels.as_bytes()), + ]) + .unwrap(); + + // Five cached cells fit a 5-cell budget even when referenced by two link entries. + let limits = Limits { binary_cells: 5, ..Limits::default() }; + let mut p = Package::open(&bytes, &limits).unwrap(); + let wb = p.workbook().unwrap(); + let ext = p.external_links(&wb).unwrap(); + assert_eq!(ext.len(), 2); + assert!(matches!(&ext[0].1, Some(craft_xlsx::ExternalLink::Book(b)) if b.sheet_data[0].cells.len() == 5)); + assert_eq!(ext[0].1, ext[1].1); + + // Tightening the budget below the 5 cached cells fails with TooLarge. + let too_small = Limits { binary_cells: 4, ..Limits::default() }; + let mut p2 = Package::open(&bytes, &too_small).unwrap(); + assert!(matches!(p2.workbook(), Err(Error::TooLarge(_)))); +} + +#[test] +fn an_external_reference_without_an_id_keeps_its_place() { + let types = r#""#; + let root = r#""#; + let book = r#""#; + let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", book.as_bytes())]).unwrap(); + let wb = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap(); + assert_eq!(wb.external_references, ["", "x2"]); + let written = wb.to_el(); + let refs: Vec<_> = written.child("externalReferences").unwrap().children("externalReference").map(|r| r.attr("r:id")).collect(); + assert_eq!(refs, [None, Some("x2")]); +} + #[test] fn empty_ordinary_names_and_their_dependants_keep_cached_values() { // Forward and transitive references to an empty ordinary name must not become dangling @@ -2134,3 +2433,107 @@ fn scoped_names_do_not_rebind_shadowed_workbook_names() { assert!(book.warnings.iter().any(|w| w.contains("workbook names shadowed by local names")), "{:?}", book.warnings); assert!(book.warnings.iter().any(|w| w.contains("names using a name that was left out")), "{:?}", book.warnings); } + +#[test] +fn external_metadata_precedes_defined_name_finalization() { + // Name 1 uses an external name; 2 is a forward alias to 3, whose formula uses + // an external cell. Both metadata and ordinary dependency propagation must survive. + let local = |i: u32| [&[0x23u8][..], &i.to_le_bytes()].concat(); + let names = [ + brt_name(0, 0, WORKBOOK, "Ext", &[0x39, 4, 0, 1, 0, 0, 0], None), + brt_name(0, 0, WORKBOOK, "Forward", &local(3), None), + brt_name(0, 0, WORKBOOK, "Cell", &ref3d_name(1, 0, 0), None), + brt_name(0, 0, 0, "Scoped", &local(1), None), + ] + .concat(); + let plain = book_with_external_links(); + let end = record(132, &[]); + let book = [&plain[..plain.len() - end.len()], &names, &end].concat(); + let data = [row(0), formula_cell(1, &local(1), &[]), formula_cell(2, &local(2), &[]), formula_cell(3, &[0x39, 0, 0, 4, 0, 0, 0], &[])].concat(); + let bytes = external_package_with(&book, &data, &workbook_link()); + let wb = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap(); + let xml = r#"[1]!ExtNameCell[1]Data!$A$1Ext"#; + assert_eq!(wb.defined_names, xml_names(xml)); + let valid = read(&bytes).unwrap(); + assert_eq!(valid.sheets[0].formula(CellRef::new(0, 1)), Some("Ext")); + assert_eq!(valid.sheets[0].formula(CellRef::new(0, 2)), Some("Forward")); + assert_eq!(valid.sheets[0].formula(CellRef::new(0, 3)), Some("Data!Scoped")); + + // A truncated external link must still omit dependent names and keep cell caches. + let missing = external_package_with(&book, &data, &[0x80]); + let wb = Package::open(&missing, &Limits::default()).unwrap().workbook().unwrap(); + assert!(wb.defined_names.is_empty()); + let missing = read(&missing).unwrap(); + for col in 1..=3 { + assert_eq!(missing.sheets[0].formula(CellRef::new(0, col)), None); + assert_eq!(missing.sheets[0].value(CellRef::new(0, col)), Value::Number(0.0)); + } +} + +#[test] +fn external_sheet_link_cannot_select_a_same_id_local_table() { + let data = [ + row(0), + formula_cell(1, &ptg_list(0, 1, 1, 1, 1), &[]), + // External link, but deliberately without the external-table flag. + formula_cell(2, &ptg_list(1, 1, 1, 1, 1), &[]), + ] + .concat(); + let rels = RELS.replace("", &format!(r#""#)); + let types = TYPES.replace("", r#""#); + let sheet_rels = r#""#; + let parts = [record(660, &1u32.to_le_bytes()), record(661, &wide("t1")), record(662, &[])].concat(); + let (book, one, two, strings, link, lr, dde, table) = ( + book_with_external_links(), + worksheet(&data, &parts), + worksheet(&[], &[]), + sst(), + workbook_link(), + link_rels(), + dde_link(), + sales(&sales_filters()), + ); + let bytes = zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT.as_bytes()), + ("records/book.bin", &book), + ("records/_rels/book.bin.rels", rels.as_bytes()), + ("data/one.bin", &one), + ("data/_rels/one.bin.rels", sheet_rels.as_bytes()), + ("data/two.bin", &two), + ("text/strings.bin", &strings), + ("links/one.bin", &link), + ("links/_rels/one.bin.rels", lr.as_bytes()), + ("links/two.bin", &dde), + ("tables/t1.bin", &table), + ]) + .unwrap(); + let read = read(&bytes).unwrap(); + assert_eq!(read.sheets[0].formula(CellRef::new(0, 1)), Some("Sales[Val]")); + assert_eq!(read.sheets[0].formula(CellRef::new(0, 2)), None); + assert_eq!(read.sheets[0].value(CellRef::new(0, 2)), Value::Number(0.0)); +} + +#[test] +fn external_links_follow_changed_reference_ids_without_recharging() { + use craft_xlsx::ExternalLink; + let bytes = external_package(&row(0), &workbook_link()); + let limits = Limits { binary_cells: 5, ..Limits::default() }; + let mut p = Package::open(&bytes, &limits).unwrap(); + let mut wb = p.workbook().unwrap(); + let original = p.external_links(&wb).unwrap(); + assert_eq!(original[0].0, "links/one.bin"); + assert!(matches!(original[0].1, Some(ExternalLink::Book(_)))); + assert_eq!(original[1], ("links/two.bin".into(), Some(ExternalLink::Other))); + wb.external_references.swap(0, 1); + let reversed = vec![original[1].clone(), original[0].clone()]; + assert_eq!(p.external_links(&wb).unwrap(), reversed); + assert_eq!(p.external_links(&wb).unwrap(), reversed); + wb.external_references[0] = "missing".into(); + assert_eq!(p.external_links(&wb).unwrap(), vec![(String::new(), None), original[0].clone()]); + assert!(p.warnings().iter().any(|w| w.contains("external link missing: the relationship is missing"))); + wb.external_references = vec!["x1".into()]; + assert_eq!(p.external_links(&wb).unwrap(), vec![original[0].clone()]); + wb.external_references = vec!["x1".into(), "x1".into(), "x2".into()]; + assert_eq!(p.external_links(&wb).unwrap(), vec![original[0].clone(), original[0].clone(), original[1].clone()]); +}