mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 10:48:15 +01:00
Merge remote-tracking branch 'origin/main' into n1751-merge
# Conflicts: # crates/odf/src/text/package.rs
This commit is contained in:
48 files changed
+2167
-92
No files matched your search
@@ -110,3 +110,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper
|
||||
## Non-seeking WAV primitives
|
||||
|
||||
`crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes.
|
||||
|
||||
## GIMP palette reader
|
||||
|
||||
`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes.
|
||||
Generated
+4
@@ -2592,6 +2592,10 @@ dependencies = [
|
||||
"zip 9.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-palette"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-pcraft-bundle"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -11,6 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/craft-libs"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-palette = { path = "crates/palette" }
|
||||
craft-shx = { path = "crates/shx" }
|
||||
craft-http-url = { path = "crates/http-url" }
|
||||
craft-usd = { path = "crates/usd" }
|
||||
|
||||
@@ -12,6 +12,9 @@ pub const MAX_PART: u64 = 256 * 1024 * 1024;
|
||||
pub const MAX_TOTAL: u64 = 512 * 1024 * 1024;
|
||||
/// Most zip entries we look at.
|
||||
pub const MAX_ENTRIES: usize = 20_000;
|
||||
// ZIP names have at most u16::MAX raw bytes. CP437/lossy UTF-8 decoding can
|
||||
// expand each byte to three UTF-8 bytes. Bound from_parts lookup copies too.
|
||||
const MAX_SCAN_NAME: usize = 3 * u16::MAX as usize;
|
||||
|
||||
/// Relationship type suffixes (after `.../relationships/`).
|
||||
pub mod rt {
|
||||
@@ -270,6 +273,61 @@ impl Package {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read only XML attributes, once per canonical package part. This never invokes
|
||||
/// an altChunk importer or fetches additional data. Non-XML extensions are valid OPC
|
||||
/// targets too. Errors end a lenient part exactly as the normal XML reader does;
|
||||
/// the subsequent strict main-document parse remains authoritative.
|
||||
pub(crate) fn file_orders(&self) -> Result<craft_wordmodel::para::FileOrders, DocxError> {
|
||||
use craft_wordmodel::para::FileOrderScan;
|
||||
let mut bytes = 0u64;
|
||||
for (i, name) in self.opc.names().enumerate() {
|
||||
if name.len() > MAX_SCAN_NAME {
|
||||
return Err(DocxError::Limit("stacking-order source part name is too long".into()));
|
||||
}
|
||||
if i >= MAX_ENTRIES {
|
||||
return Err(DocxError::Limit("too many stacking-order source parts".into()));
|
||||
}
|
||||
bytes = bytes
|
||||
.checked_add(self.opc.get(name).map_or(0, |b| b.len() as u64))
|
||||
.ok_or_else(|| DocxError::Limit("stacking-order source size overflow".into()))?;
|
||||
if bytes > FileOrderScan::MAX_SOURCE_BYTES {
|
||||
return Err(DocxError::Limit("stacking-order source exceeds 2 GiB".into()));
|
||||
}
|
||||
}
|
||||
let mut scan = FileOrderScan::new(bytes).map_err(DocxError::Limit)?;
|
||||
let limits = craft_xml::Limits {
|
||||
max_input: 2 << 30,
|
||||
max_depth: xml::MAX_DEPTH + 1,
|
||||
max_nodes: 2 * xml::MAX_ELEMENTS,
|
||||
max_elements: xml::MAX_ELEMENTS,
|
||||
max_attrs: xml::MAX_ATTRS,
|
||||
max_attrs_total: 2 * xml::MAX_ELEMENTS,
|
||||
};
|
||||
let opts = craft_xml::Options::default().with_limits(limits);
|
||||
for name in self.opc.names() {
|
||||
let Some(bytes) = self.opc.get(name) else { continue };
|
||||
let text = craft_xml::to_utf8(bytes);
|
||||
// Attribute names cannot contain entity references. This only skips parts
|
||||
// that cannot possibly supply an order, including ordinary binary media.
|
||||
if !text.windows(b"relativeHeight".len()).any(|w| w == b"relativeHeight") {
|
||||
continue;
|
||||
}
|
||||
let mut events = opts.events(&text);
|
||||
while let Ok(Some(ev)) = events.next() {
|
||||
if let craft_xml::Event::Start { attrs, .. } = ev {
|
||||
for (name, value) in attrs {
|
||||
if name.rsplit(':').next() == Some("relativeHeight")
|
||||
&& let Ok(raw) = value.trim().parse::<u32>()
|
||||
{
|
||||
scan.observe(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
scan.finish().map_err(DocxError::Limit)
|
||||
}
|
||||
|
||||
/// Relationships of `part` (from `dir/_rels/name.rels`). Internal targets name the part as
|
||||
/// stored, so a part reached under several spellings is kept, cached and written once.
|
||||
pub fn rels(&self, part: &str) -> Rels {
|
||||
@@ -391,3 +449,39 @@ mod tests {
|
||||
assert!(junk.parts.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod file_order_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_order_scan_bounds_decoded_part_names_before_lookup() {
|
||||
let at_limit = "n".repeat(MAX_SCAN_NAME);
|
||||
assert!(Package::from_parts(BTreeMap::from([(at_limit, Vec::new())])).file_orders().is_ok());
|
||||
let too_long = "n".repeat(MAX_SCAN_NAME + 1);
|
||||
assert!(Package::from_parts(BTreeMap::from([(too_long, Vec::new())])).file_orders().is_err());
|
||||
}
|
||||
|
||||
fn scan(xml: &str) -> craft_wordmodel::para::FileOrders {
|
||||
Package::from_parts(BTreeMap::from([("odd.part".into(), xml.as_bytes().to_vec())])).file_orders().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_order_scan_matches_lenient_attributes_entities_and_parser_limits() {
|
||||
let malformed = r#"<r><x alien:relativeHeight="4294967295"></wrong><x relativeHeight="4294967294"/></r>"#;
|
||||
let tree = xml::parse(malformed.as_bytes()).unwrap();
|
||||
assert_eq!(tree.find("?:x").or_else(|| tree.find("x")).unwrap().attr("relativeHeight"), Some("4294967295"));
|
||||
let map = scan(malformed);
|
||||
assert_eq!((map.model_order(Some(u32::MAX - 1)), map.model_order(Some(u32::MAX))), (u32::MAX - 1, u32::MAX));
|
||||
let custom = r#"<!DOCTYPE r [<!ENTITY rank "4294967295">]><r relativeHeight="&rank;"/>"#;
|
||||
assert_ne!(xml::parse(custom.as_bytes()).unwrap().attr("relativeHeight"), Some("4294967295"));
|
||||
assert_eq!(scan(custom).model_order(Some(u32::MAX - 1)), u32::MAX);
|
||||
let too_many =
|
||||
format!(r#"<r {} relativeHeight="4294967295"/>"#, (0..xml::MAX_ATTRS).map(|i| format!(r#"a{i}="x""#)).collect::<Vec<_>>().join(" "));
|
||||
assert!(xml::parse(too_many.as_bytes()).is_err());
|
||||
assert_eq!(scan(&too_many).model_order(Some(u32::MAX - 1)), u32::MAX);
|
||||
let too_deep = format!(r#"{}<r relativeHeight="4294967295"/>{}"#, "<r>".repeat(xml::MAX_DEPTH + 1), "</r>".repeat(xml::MAX_DEPTH + 1));
|
||||
assert!(xml::parse(too_deep.as_bytes()).is_err());
|
||||
assert_eq!(scan(&too_deep).model_order(Some(u32::MAX - 1)), u32::MAX);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ const MAX_TEMPLATE_PATH: usize = 32 * 1024;
|
||||
|
||||
pub(crate) struct Reader<'p> {
|
||||
pkg: &'p Package,
|
||||
file_orders: craft_wordmodel::para::FileOrders,
|
||||
pub doc: Document,
|
||||
pub pc: PropCtx,
|
||||
revs: HashMap<(u8, String, String, Option<String>), u32>,
|
||||
@@ -167,7 +168,9 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize,
|
||||
let rels = pkg.rels(&main);
|
||||
let mut doc = Document::new();
|
||||
doc.body.clear();
|
||||
let file_orders = pkg.file_orders()?;
|
||||
let mut r = Reader {
|
||||
file_orders,
|
||||
pkg,
|
||||
doc,
|
||||
pc: PropCtx::default(),
|
||||
|
||||
@@ -12,7 +12,7 @@ impl Reader<'_> {
|
||||
/// text and drawing ids are carried into the object. Returns `None` when the frame or payload
|
||||
/// cannot be read. Ink written by WordCraft keeps its tool's caps rather than an outline cap.
|
||||
pub(super) fn read_drawing(&mut self, sc: &mut StoryCtx, d: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let Frame { c, anchored, w, h, alt, mut float } = drawing_frame(d)?;
|
||||
let Frame { c, anchored, w, h, alt, mut float } = drawing_frame(d, self.file_orders)?;
|
||||
let gd = c.child("a:graphic").and_then(|g| g.child("a:graphicData"))?;
|
||||
// Checked by URI before the blip search: a diagram's data can hold a blip further down.
|
||||
let uri = gd.attr("uri").unwrap_or("");
|
||||
@@ -195,7 +195,7 @@ impl Reader<'_> {
|
||||
if fallback.find("a:graphic").is_some() || !fallback.els().all(|e| RUN_CONTENT.contains(&e.name.as_str())) {
|
||||
return None;
|
||||
}
|
||||
let Frame { c, w, h, alt, mut float, .. } = drawing_frame(choice.child("w:drawing")?)?;
|
||||
let Frame { c, w, h, alt, mut float, .. } = drawing_frame(choice.child("w:drawing")?, self.file_orders)?;
|
||||
let part = c
|
||||
.child("a:graphic")
|
||||
.and_then(|g| g.child("a:graphicData"))
|
||||
@@ -627,7 +627,7 @@ struct Frame<'a> {
|
||||
float: Float,
|
||||
}
|
||||
|
||||
fn drawing_frame(d: &El) -> Option<Frame<'_>> {
|
||||
fn drawing_frame(d: &El, file_orders: craft_wordmodel::para::FileOrders) -> Option<Frame<'_>> {
|
||||
let (c, anchored) = match d.child("wp:inline") {
|
||||
Some(c) => (c, false),
|
||||
None => (d.child("wp:anchor")?, true),
|
||||
@@ -636,7 +636,7 @@ fn drawing_frame(d: &El) -> Option<Frame<'_>> {
|
||||
let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
|
||||
let (w, h) = (dim("cx"), dim("cy"));
|
||||
let (alt, meta) = nv_alt(c.child("wp:docPr"));
|
||||
let mut float = if anchored { anchor_float(c) } else { Float::default() };
|
||||
let mut float = if anchored { anchor_float(c, file_orders) } else { Float::default() };
|
||||
float.alt = meta;
|
||||
float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden"));
|
||||
if let Some(e) = c.child("wp:effectExtent") {
|
||||
@@ -670,10 +670,11 @@ fn nv_alt(p: Option<&El>) -> (String, AltText) {
|
||||
(descr, AltText { text: String::new(), title, decorative })
|
||||
}
|
||||
|
||||
fn anchor_float(c: &El) -> Float {
|
||||
fn anchor_float(c: &El, orders: craft_wordmodel::para::FileOrders) -> Float {
|
||||
// `relativeHeight`: the stacking order Word draws floating objects in (higher on top), which
|
||||
// need not be their order in the file.
|
||||
let z = c.attr("relativeHeight").and_then(|v| v.trim().parse::<u32>().ok()).unwrap_or(0);
|
||||
// need not be their order in the file. Kept one more (see `Float::z`): 0, the lowest a file
|
||||
// can give, isn't the 0 of an object without one, which stacks above them all.
|
||||
let z = orders.model_order(c.attr("relativeHeight").and_then(|v| v.trim().parse::<u32>().ok()));
|
||||
let mut f = Float { wrap: Wrap::Square, z, ..Float::default() };
|
||||
let behind = on_off_attr(c, "behindDoc");
|
||||
// Word wraps a position relative to the page's size (`wp14:pctPosVOffset`) in
|
||||
|
||||
@@ -83,6 +83,26 @@ impl PartRels {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where Word's stacking orders (`relativeHeight`) start for objects made in Word.
|
||||
const FIRST_Z: u32 = 251_658_240;
|
||||
|
||||
/// The `relativeHeight` the objects of `doc` that have none count up from, and the `relativeHeight`
|
||||
/// each stored order is written as when it isn't its own (wordcraft#2638). A stored order
|
||||
/// ([`craft_wordmodel::para::Float::z`]) is one more than the file's, and the new objects go above
|
||||
/// every stored one. When the stored orders leave no room for them below `u32::MAX` (a file using
|
||||
/// values that high; `u32::MAX` itself would read back as the order below it), the stored ones are
|
||||
/// numbered again from [`FIRST_Z`] in their order, so no two objects share an order and none goes
|
||||
/// out of range.
|
||||
pub(crate) fn stacking(doc: &Document) -> (u32, BTreeMap<u32, u32>) {
|
||||
let (orders, unset) = doc.stacking_orders();
|
||||
let top = orders.last().map_or(0, |z| z.saturating_sub(1)).max(FIRST_Z);
|
||||
if u32::try_from(unset).ok().and_then(|n| top.checked_add(n)).is_some_and(|last| last < u32::MAX) {
|
||||
return (top, BTreeMap::new());
|
||||
}
|
||||
let zmap: BTreeMap<u32, u32> = orders.iter().zip(FIRST_Z..=u32::MAX).map(|(&z, to)| (z, to)).collect();
|
||||
(zmap.values().last().copied().unwrap_or(FIRST_Z), zmap)
|
||||
}
|
||||
|
||||
pub(crate) struct Writer<'d> {
|
||||
doc: &'d Document,
|
||||
/// Numbered display equations written so far (automatic numbers are written as text).
|
||||
@@ -96,7 +116,14 @@ pub(crate) struct Writer<'d> {
|
||||
docpr: u32,
|
||||
/// Shapes' own drawing ids written so far (connectors refer to them).
|
||||
shape_ids: std::collections::HashSet<u32>,
|
||||
/// The last stacking order (`relativeHeight`) given to an object that had none.
|
||||
z: u32,
|
||||
/// Stored stacking orders written as other `relativeHeight`s (see [`stacking`]); empty: each
|
||||
/// as its own.
|
||||
zmap: BTreeMap<u32, u32>,
|
||||
/// The `relativeHeight` the last `wp:anchor` was written with, which a shape's VML fallback
|
||||
/// gives as its `z-index`.
|
||||
anchor_z: u32,
|
||||
/// Note part id → file note id, in first-reference order.
|
||||
footnotes: Vec<u32>,
|
||||
endnotes: Vec<u32>,
|
||||
|
||||
@@ -342,7 +342,16 @@ impl super::Writer<'_> {
|
||||
/// the object's current size and position into its own markup (a chart or diagram's frame is
|
||||
/// written by the caller). `None` when it can't be written back (its parts are gone).
|
||||
pub(super) fn embedded_xml(&mut self, src: &Embedded, rels: &mut PartRels, resize: Option<(f32, f32, &Float, &str)>) -> Option<String> {
|
||||
self.embedded_tree(src, rels, resize).map(|root| root.to_xml())
|
||||
let mut root = self.embedded_tree(src, rels, resize)?;
|
||||
// read_object prefers a direct VML preview. Its signed z-index is not modeled, so a
|
||||
// coexisting retained DrawingML frame cannot safely be assigned the model's order.
|
||||
let vml_preview = root.els().any(|e| e.name.starts_with("v:") && e.local() != "shapetype");
|
||||
if let Some((_, _, float, _)) = resize
|
||||
&& !vml_preview
|
||||
{
|
||||
self.retained_anchor_order(&mut root, float, &mut None, 0);
|
||||
}
|
||||
Some(root.to_xml())
|
||||
}
|
||||
|
||||
/// The same bounded preservation operation, retaining the parsed tree for a caller that
|
||||
@@ -481,6 +490,27 @@ impl super::Writer<'_> {
|
||||
/// Write an OLE object's size (and position, when floating), rotation and flips into its VML
|
||||
/// shape and DrawingML picture, with the effect extent covering the rotated bounds as for
|
||||
/// other drawings, its alt text into both, and give its drawing a fresh `wp:docPr` id.
|
||||
/// Retained DrawingML frames of one OLE object share one allocated order.
|
||||
/// This does not normalize VML z-index: its signed order is not represented by the reader.
|
||||
/// Stop at each outer anchor or inline frame: nested drawings have their own placement.
|
||||
fn retained_anchor_order(&mut self, e: &mut El, float: &Float, order: &mut Option<u32>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
if e.name == "wp:inline" {
|
||||
return;
|
||||
}
|
||||
if e.name == "wp:anchor" {
|
||||
let z = *order.get_or_insert_with(|| self.drawing_order(float));
|
||||
set_attr(e, "relativeHeight", &z.to_string());
|
||||
return;
|
||||
}
|
||||
for child in &mut e.kids {
|
||||
if let xml::Node::El(child) = child {
|
||||
self.retained_anchor_order(child, float, order, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn resize_object(&mut self, e: &mut El, w: f32, h: f32, float: &Float, alt: &str, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
|
||||
@@ -32,7 +32,9 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
// Fresh drawing ids start past the shapes' own (connectors refer to those).
|
||||
docpr: doc.next_shape_id().saturating_sub(1),
|
||||
shape_ids: std::collections::HashSet::new(),
|
||||
z: 251_658_240,
|
||||
z: 0,
|
||||
zmap: BTreeMap::new(),
|
||||
anchor_z: 0,
|
||||
footnotes: Vec::new(),
|
||||
endnotes: Vec::new(),
|
||||
hf: Vec::new(),
|
||||
@@ -58,6 +60,7 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
.flat_map(|(n, c)| c.iter().enumerate().map(move |(seq, id)| (*id, (n as u32 + 1, seq as u32))))
|
||||
.collect(),
|
||||
};
|
||||
(wr.z, wr.zmap) = super::stacking(doc);
|
||||
wr.assign_media();
|
||||
wr.embeds.reserve_media(wr.media_files.values());
|
||||
let mut entries: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
|
||||
@@ -263,6 +263,17 @@ impl Writer<'_> {
|
||||
w.close("w:drawing");
|
||||
}
|
||||
|
||||
/// One order for an anchored object, shared by generated and retained drawings.
|
||||
pub(in crate::write) fn drawing_order(&mut self, float: &Float) -> u32 {
|
||||
let z = if float.z > 0 {
|
||||
self.zmap.get(&float.z).copied().unwrap_or(float.z.saturating_sub(1))
|
||||
} else {
|
||||
self.z = self.z.saturating_add(1);
|
||||
self.z
|
||||
};
|
||||
self.anchor_z = z;
|
||||
z
|
||||
}
|
||||
pub(super) fn drawing_open(&mut self, w: &mut W, info: DrawingInfo<'_>) {
|
||||
let DrawingInfo { float, size: (iw, ih), docpr, name, alt, link } = info;
|
||||
let (cx, cy) = (emu(iw.max(0.0)), emu(ih.max(0.0)));
|
||||
@@ -271,9 +282,9 @@ impl Writer<'_> {
|
||||
} else {
|
||||
let d = emu(float.dist.clamp(0.0, 1584.0));
|
||||
let (dt, db) = (emu(float.dist_top.clamp(0.0, 1584.0)), emu(float.dist_bottom.clamp(0.0, 1584.0)));
|
||||
// The stacking order read from the file is kept; objects without one stack in
|
||||
// document order above it.
|
||||
self.z = if float.z > 0 { float.z } else { self.z.saturating_add(1) };
|
||||
// A stacking order read from a file is kept (one less: see `Float::z`); objects made
|
||||
// here go above those.
|
||||
let z = self.drawing_order(float);
|
||||
let behind = if float.wrap == Wrap::BehindText { "1" } else { "0" };
|
||||
w.open(
|
||||
"wp:anchor",
|
||||
@@ -283,7 +294,7 @@ impl Writer<'_> {
|
||||
("distL", &d),
|
||||
("distR", &d),
|
||||
("simplePos", "0"),
|
||||
("relativeHeight", &self.z.to_string()),
|
||||
("relativeHeight", &z.to_string()),
|
||||
("behindDoc", behind),
|
||||
("locked", "0"),
|
||||
("layoutInCell", if float.outside_cell { "0" } else { "1" }),
|
||||
|
||||
@@ -398,8 +398,9 @@ impl Writer<'_> {
|
||||
}
|
||||
let float = &float;
|
||||
self.drawing_open(w, DrawingInfo { float, size: (*sw, *sh), docpr: &docpr, name: &name, alt: o.alt_text(), link: link.as_deref() });
|
||||
// This shape's stacking order: floating objects in its text box move `self.z` on.
|
||||
let z = self.z;
|
||||
// This shape's stacking order, as its anchor gave it: floating objects in its text box
|
||||
// write anchors of their own.
|
||||
let z = self.anchor_z;
|
||||
w.empty("wp:cNvGraphicFramePr", &[]);
|
||||
w.open("a:graphic", &[]);
|
||||
w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]);
|
||||
|
||||
@@ -1282,10 +1282,11 @@ fn anchor_stacking_order_is_read_and_kept() {
|
||||
paras(d)[0].objects.iter().filter_map(|o| if let InlineObject::Shape { float, .. } = o { Some(float.z) } else { None }).collect()
|
||||
};
|
||||
let d = read_body(&body);
|
||||
assert_eq!(zs(&d), [251660288, 251657214, 0]);
|
||||
// Kept one more than the file's (`Float::z`), so a file's 0 isn't "none".
|
||||
assert_eq!(zs(&d), [251660289, 251657215, 0]);
|
||||
let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap();
|
||||
let z = zs(&again);
|
||||
assert_eq!(&z[..2], &[251660288, 251657214]);
|
||||
assert_eq!(&z[..2], &[251660289, 251657215]);
|
||||
assert!(z[2] > 0, "an object without one gets an order on saving: {z:?}");
|
||||
}
|
||||
|
||||
@@ -2697,6 +2698,100 @@ fn anchored_wsp(name: &str, cx: u32, cy: u32, sppr: &str, style: &str, extra: &s
|
||||
)
|
||||
}
|
||||
|
||||
/// wordcraft#2638: Word stacks floating objects by `relativeHeight`, not by their order in the text (a
|
||||
/// shape sent to back, then copied with the shape over it, comes first in the text but stays
|
||||
/// behind). The order is read and kept on save, and an object made here is saved above them.
|
||||
#[test]
|
||||
fn floating_objects_keep_their_stacking_order() {
|
||||
let shape = |name: &str, z: u32| {
|
||||
anchored_wsp(name, 127000, 127000, r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let body = format!("<w:p>{}{}</w:p>", shape("Canopy", 251662336), shape("Trunk", 251661312));
|
||||
let mut d = read_body(&body);
|
||||
let stacking = |d: &Document| paras(d)[0].objects.iter().map(|o| o.frame().map(|(_, _, f)| f.z)).collect::<Vec<_>>();
|
||||
assert_eq!(stacking(&d), [Some(251662337), Some(251661313)]);
|
||||
let mut made = paras(&d)[0].objects[0].clone();
|
||||
if let InlineObject::Shape { float, .. } = &mut made {
|
||||
float.z = 0;
|
||||
}
|
||||
let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut) else { panic!("a paragraph") };
|
||||
p.insert_object(0, made, &Default::default()).unwrap();
|
||||
let files = unzip(&craft_docx::write(&d).unwrap());
|
||||
let written = attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight");
|
||||
assert_eq!(written, ["251662337", "251662336", "251661312"]);
|
||||
let back = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(stacking(&back), [Some(251662338), Some(251662337), Some(251661313)]);
|
||||
}
|
||||
|
||||
/// wordcraft#2638: a file whose stacking orders reach `u32::MAX` leaves no room above them for an object
|
||||
/// made here. The stored orders are then numbered again, in their order, so the new object still
|
||||
/// goes over all of them and no two objects share an order (it was written as `u32::MAX` too).
|
||||
#[test]
|
||||
fn stacking_orders_at_the_top_of_the_range_are_numbered_again() {
|
||||
let shape = |name: &str, z: u32| {
|
||||
anchored_wsp(name, 127000, 127000, r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let body = format!("<w:p>{}{}</w:p>", shape("Top", u32::MAX), shape("Low", 7));
|
||||
let mut d = read_body(&body);
|
||||
let stacking = |d: &Document| paras(d)[0].objects.iter().map(|o| o.frame().map(|(_, _, f)| f.z)).collect::<Vec<_>>();
|
||||
assert_eq!(stacking(&d), [Some(u32::MAX), Some(8)]);
|
||||
let mut made = paras(&d)[0].objects[0].clone();
|
||||
if let InlineObject::Shape { float, .. } = &mut made {
|
||||
float.z = 0;
|
||||
}
|
||||
let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut) else { panic!("a paragraph") };
|
||||
p.insert_object(0, made, &Default::default()).unwrap();
|
||||
let back = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap();
|
||||
let z: Vec<u32> = stacking(&back).into_iter().map(|z| z.expect("every anchor has an order")).collect();
|
||||
assert!(z[0] > z[1] && z[1] > z[2], "new over Top over Low, all different: {z:?}");
|
||||
// The note separators are saved with the document: an order there counts too.
|
||||
let mut d = read_body(&format!("<w:p>{}</w:p>", shape("Low", 7)));
|
||||
let mut sep = read_body(&format!("<w:p>{}</w:p>", shape("Separator", u32::MAX)));
|
||||
d.footnote_separators.separator = Some(std::mem::take(&mut sep.body));
|
||||
let (orders, unset) = d.stacking_orders();
|
||||
assert_eq!((orders.last().copied(), unset), (Some(u32::MAX), 0), "the separator's order is seen");
|
||||
let mut made = paras(&d)[0].objects[0].clone();
|
||||
if let InlineObject::Shape { float, .. } = &mut made {
|
||||
float.z = 0;
|
||||
}
|
||||
let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut) else { panic!("a paragraph") };
|
||||
p.insert_object(0, made, &Default::default()).unwrap();
|
||||
let files = unzip(&craft_docx::write(&d).unwrap());
|
||||
let body: Vec<u64> = attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect();
|
||||
let seps: Vec<u64> = attr_values(&text(&files, "word/footnotes.xml"), "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect();
|
||||
assert_eq!(seps.len(), 1, "the separator's shape is saved");
|
||||
assert!(body[0] > seps[0] && seps[0] > body[1], "new over the separator's over Low: {body:?} {seps:?}");
|
||||
// So does one in a building block of the glossary, saved with the same numbering (wordcraft#2638 review).
|
||||
let mut d = read_body(&format!("<w:p>{}</w:p>", shape("Low", 7)));
|
||||
let entry = read_body(&format!("<w:p>{}</w:p>", shape("Entry", u32::MAX)));
|
||||
d.glossary.push(craft_wordmodel::BuildingBlock { name: "Entry".into(), blocks: entry.body, ..Default::default() });
|
||||
assert_eq!(d.stacking_orders().0.last().copied(), Some(u32::MAX), "the glossary's order is seen");
|
||||
// With room above, the stored orders are written as they are.
|
||||
let room = read_body(&format!("<w:p>{}</w:p>", shape("Top", u32::MAX - 5)));
|
||||
let back = craft_docx::read(&craft_docx::write(&room).unwrap()).unwrap();
|
||||
assert_eq!(stacking(&back), [Some(u32::MAX - 4)]);
|
||||
}
|
||||
|
||||
/// wordcraft#2638 (review): `relativeHeight="0"`, the lowest a file can give, is a stacking order like
|
||||
/// any other: under a shape with 1, not taken for an object without one (made here, which goes
|
||||
/// over everything), and saved back as 0.
|
||||
#[test]
|
||||
fn a_stacking_order_of_zero_stays_the_lowest() {
|
||||
let shape = |name: &str, z: u32| {
|
||||
anchored_wsp(name, 127000, 127000, r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let d = read_body(&format!("<w:p>{}{}</w:p>", shape("Bottom", 0), shape("Top", 1)));
|
||||
let floats: Vec<_> = paras(&d)[0].objects.iter().filter_map(|o| o.frame().map(|(_, _, f)| f.clone())).collect();
|
||||
assert_eq!(floats.iter().map(|f| f.z).collect::<Vec<_>>(), [1, 2]);
|
||||
assert!(floats[0].stack() < floats[1].stack(), "0 stacks under 1");
|
||||
assert!(floats[1].stack() < craft_wordmodel::para::Float::default().stack(), "an object made here goes over both");
|
||||
let files = unzip(&craft_docx::write(&d).unwrap());
|
||||
assert_eq!(attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight"), ["0", "1"]);
|
||||
}
|
||||
|
||||
/// #611: diagrams drawn with Word's shapes were mostly missing. Connectors and boxes take their
|
||||
/// outline and fill from the theme through their style references, or name preset and scheme
|
||||
/// colours; all of these are read, with line widths and arrowheads.
|
||||
@@ -4911,3 +5006,170 @@ fn vml_horizontal_rules_are_read_and_kept() {
|
||||
let d = read_body(&body);
|
||||
assert_eq!(rules(&d).iter().map(|r| r.0).collect::<Vec<_>>(), [None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_raw_orders_share_one_map_across_parts_without_replaying_chunks() {
|
||||
let shape = |name: &str, z: &str| {
|
||||
anchored_wsp(name, 127000, 127000, r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let doc = format!(
|
||||
r#"<w:document {W_NS}><w:body><w:p>{}{}{}</w:p><w:altChunk r:id="chunk"/><w:sectPr><w:headerReference w:type="default" r:id="header"/></w:sectPr></w:body></w:document>"#,
|
||||
shape("zero", "0"),
|
||||
shape("lower", "4294967292"),
|
||||
shape("high", "4294967294")
|
||||
);
|
||||
let header = format!(
|
||||
r#"<w:hdr {W_NS}><w:p>{}{}</w:p></w:hdr>"#,
|
||||
shape("maximum", "4294967295").replace("relativeHeight", "alien:relativeHeight"),
|
||||
shape("equal", "4294967295")
|
||||
)
|
||||
.replace("xmlns:wp=", "xmlns:position=")
|
||||
.replace("wp:", "position:");
|
||||
let header: Vec<u8> = [vec![0xff, 0xfe], header.encode_utf16().flat_map(u16::to_le_bytes).collect()].concat();
|
||||
let ignored = format!(r#"<w:hdr {W_NS}><w:p>{}</w:p></w:hdr>"#, shape("wrong-case duplicate", "4294967293"));
|
||||
let rel = rels(&[("header", "header", "header.part"), ("chunk", "aFChunk", "chunk.txt")]);
|
||||
let bytes = zip(&[
|
||||
("_rels/.rels", ROOT_RELS.as_bytes()),
|
||||
("word/document.xml", doc.as_bytes()),
|
||||
("word/_rels/document.xml.rels", rel.as_bytes()),
|
||||
("word/header.part", &header),
|
||||
("WORD/HEADER.PART", ignored.as_bytes()),
|
||||
("word/chunk.txt", b"external chunk"),
|
||||
]);
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let importer = |_: &craft_docx::AltChunk| {
|
||||
calls.set(calls.get() + 1);
|
||||
Some(Document::from_text("Imported once"))
|
||||
};
|
||||
let mut d = craft_docx::read_with(&bytes, &craft_docx::ReadOptions { chunks: Some(&importer), ..Default::default() }).unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
let orders = |d: &Document| {
|
||||
let body: Vec<u32> = paras(d).iter().flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect();
|
||||
let header = &d.parts[&d.last_section.headers.default.unwrap()];
|
||||
let header: Vec<u32> =
|
||||
header.blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect();
|
||||
(body, header)
|
||||
};
|
||||
let expected = (vec![1, u32::MAX - 2, u32::MAX - 1], vec![u32::MAX, u32::MAX]);
|
||||
assert_eq!(orders(&d), expected);
|
||||
for _ in 0..2 {
|
||||
d = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(orders(&d), expected);
|
||||
}
|
||||
assert_eq!(calls.get(), 1);
|
||||
let malformed = doc.replace("</w:body>", "");
|
||||
assert!(craft_docx::read(&zip(&[("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", malformed.as_bytes())])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_drawingml_ole_uses_the_shared_stacking_map() {
|
||||
let source = r##"<w:p><w:r><w:object w:dxaOrig="1440" w:dyaOrig="720"><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="914400" cy="457200"/><wp:docPr id="7" name="Object 7"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:nvPicPr><pic:cNvPr id="0" name=""/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rId8"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm flipH="1"><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing><o:OLEObject Type="Embed" ProgID="Package" DrawAspect="Content" ObjectID="_1000000002" r:id="rId9"/></w:object></w:r></w:p>"##;
|
||||
let picture = "\u{89}PNG stand-in";
|
||||
let ole = "\u{d0}\u{cf} opaque OLE storage";
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/vnd.openxmlformats-officedocument.oleObject"/></Types>"#;
|
||||
for raw in [u32::MAX - 2, u32::MAX] {
|
||||
let object = source
|
||||
.replace("<wp:inline ", &format!("<wp:anchor relativeHeight=\"{raw}\" behindDoc=\"0\" odd=\"retain & this\" "))
|
||||
.replace("</wp:inline>", "</wp:anchor>");
|
||||
let shape = anchored_wsp("Other", 127000, 127000, r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, r#"relativeHeight="4294967294""#);
|
||||
let body = format!("{object}<w:p>{shape}</w:p>");
|
||||
let mut d = craft_docx::read(&docx(
|
||||
&body,
|
||||
&[("rId8", "image", "media/image1.png"), ("rId9", "oleObject", "embeddings/oleObject1.bin")],
|
||||
&[("[Content_Types].xml", types), ("word/media/image1.png", picture), ("word/embeddings/oleObject1.bin", ole)],
|
||||
))
|
||||
.unwrap();
|
||||
assert!(matches!(paras(&d)[0].objects[0], InlineObject::Image { ole: Some(_), .. }));
|
||||
let mut made = paras(&d)[0].objects[0].clone();
|
||||
made.float_mut().unwrap().z = 0;
|
||||
let mut p = Paragraph::new();
|
||||
p.insert_object(0, made, &Default::default()).unwrap();
|
||||
d.body.push(craft_wordmodel::para_block(p));
|
||||
for _ in 0..3 {
|
||||
let out = craft_docx::write(&d).unwrap();
|
||||
let files = unzip(&out);
|
||||
let xml = text(&files, "word/document.xml");
|
||||
assert_eq!(attr_values(&xml, "wp:anchor", "odd"), ["retain & this", "retain & this"]);
|
||||
assert_eq!(attr_values(&xml, "o:OLEObject", "ProgID"), ["Package", "Package"]);
|
||||
let z: Vec<u32> = attr_values(&xml, "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect();
|
||||
assert_eq!(z.len(), 3);
|
||||
assert!(z[2] > z[0] && z[2] > z[1], "{z:?}");
|
||||
assert_eq!(z[0] < z[1], raw < u32::MAX - 1, "{z:?}");
|
||||
d = craft_docx::read(&out).unwrap();
|
||||
assert!(matches!(paras(&d)[0].objects[0], InlineObject::Image { ole: Some(_), .. }));
|
||||
}
|
||||
}
|
||||
// An inline OLE frame may retain an opaque nested drawing. Its child's rank is not the
|
||||
// outer object's rank, and the inline frame must not allocate an anchored rank at all.
|
||||
let nested = source.replace("</wp:inline>", r#"<a:extLst><wp:anchor relativeHeight="17" odd="nested"/></a:extLst></wp:inline>"#);
|
||||
let mut d = craft_docx::read(&docx(
|
||||
&nested,
|
||||
&[("rId8", "image", "media/image1.png"), ("rId9", "oleObject", "embeddings/oleObject1.bin")],
|
||||
&[("[Content_Types].xml", types), ("word/media/image1.png", picture), ("word/embeddings/oleObject1.bin", ole)],
|
||||
))
|
||||
.unwrap();
|
||||
for _ in 0..3 {
|
||||
let out = craft_docx::write(&d).unwrap();
|
||||
let files = unzip(&out);
|
||||
let xml = text(&files, "word/document.xml");
|
||||
assert_eq!(attr_values(&xml, "wp:anchor", "relativeHeight"), ["17"], "{xml}");
|
||||
assert_eq!(attr_values(&xml, "wp:anchor", "odd"), ["nested"]);
|
||||
assert!(attr_values(&xml, "wp:inline", "relativeHeight").is_empty());
|
||||
d = craft_docx::read(&out).unwrap();
|
||||
assert!(matches!(paras(&d)[0].objects[0], InlineObject::Image { ole: Some(_), .. }));
|
||||
}
|
||||
// A direct VML preview wins in read_object, even when DrawingML is retained beside it.
|
||||
// Its signed z-index is not a modeled stacking rank. Preserve both representations rather
|
||||
// than assigning a fresh DrawingML rank from the VML-derived model's unset z.
|
||||
for signed in [-17, 17] {
|
||||
let vml = format!(
|
||||
r#"<v:shape style="position:absolute;width:72pt;height:36pt;z-index:{signed}" odd="vml"><v:imagedata r:id="rId8"/></v:shape><w:drawing>"#
|
||||
);
|
||||
let mixed =
|
||||
source.replace("<w:drawing>", &vml).replace("<wp:inline ", r#"<wp:anchor relativeHeight="21" "#).replace("</wp:inline>", "</wp:anchor>");
|
||||
let mut d = craft_docx::read(&docx(
|
||||
&mixed,
|
||||
&[("rId8", "image", "media/image1.png"), ("rId9", "oleObject", "embeddings/oleObject1.bin")],
|
||||
&[("[Content_Types].xml", types), ("word/media/image1.png", picture), ("word/embeddings/oleObject1.bin", ole)],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(paras(&d)[0].objects[0].frame().unwrap().2.z, 0);
|
||||
for _ in 0..3 {
|
||||
let out = craft_docx::write(&d).unwrap();
|
||||
let files = unzip(&out);
|
||||
let xml = text(&files, "word/document.xml");
|
||||
assert_eq!(attr_values(&xml, "wp:anchor", "relativeHeight"), ["21"]);
|
||||
assert_eq!(attr_values(&xml, "v:shape", "odd"), ["vml"]);
|
||||
let styles = attr_values(&xml, "v:shape", "style");
|
||||
assert_eq!(styles.len(), 1);
|
||||
assert!(styles[0].split(';').any(|p| p == format!("z-index:{signed}")));
|
||||
d = craft_docx::read(&out).unwrap();
|
||||
assert_eq!(paras(&d)[0].objects[0].frame().unwrap().2.z, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_chart_with_text_fallback_uses_the_package_order_map() {
|
||||
// Both callers need the package map. MAX alone would still saturate to MAX without it;
|
||||
// placing MAX-1 on each representation in turn catches a missing map at either caller.
|
||||
for (chart_raw, shape_raw) in [(u32::MAX, u32::MAX - 1), (u32::MAX - 1, u32::MAX)] {
|
||||
let mut files = unzip(&chartex_text_fallback_docx("<w:t>Chart not available.</w:t>"));
|
||||
let shape = anchored_wsp("Other", 127000, 127000, r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{shape_raw}""#));
|
||||
let xml = text(&files, "word/document.xml")
|
||||
.replace("<wp:inline ", &format!(r#"<wp:anchor relativeHeight="{chart_raw}" "#))
|
||||
.replace("</wp:inline>", "</wp:anchor>")
|
||||
.replace("</w:body>", &format!("<w:p>{shape}</w:p></w:body>"));
|
||||
files.insert("word/document.xml".to_string(), xml.into_bytes());
|
||||
let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect();
|
||||
let d = craft_docx::read(&zip(&entries)).unwrap();
|
||||
let g = graphics(&d);
|
||||
let [InlineObject::Graphic { float, .. }] = g.as_slice() else { panic!("chart placeholder missing") };
|
||||
assert_eq!(float.z, chart_raw);
|
||||
let other = paras(&d).iter().flat_map(|p| &p.objects).find(|o| matches!(o, InlineObject::Shape { .. })).unwrap();
|
||||
assert_eq!(other.frame().unwrap().2.z, shape_raw);
|
||||
}
|
||||
}
|
||||
@@ -23,18 +23,14 @@ fn paras(doc: &Document) -> Vec<&Paragraph> {
|
||||
doc.body.iter().filter_map(|b| b.as_para()).collect()
|
||||
}
|
||||
|
||||
/// `doc` with the stacking order of its body's floating objects cleared: saving gives objects
|
||||
/// without one an order (`relativeHeight`), so tests about other properties compare without it.
|
||||
/// `doc` without the stacking order a save gives objects made in the app (`relativeHeight`,
|
||||
/// read back as `Float::z`), to compare them with the objects as made.
|
||||
fn unstacked(mut doc: Document) -> Document {
|
||||
for b in &mut doc.body {
|
||||
if let Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
for o in &mut p.objects {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.z = 0;
|
||||
}
|
||||
}
|
||||
doc.objects_mut(&|_| true, &mut |o| {
|
||||
if let Some(f) = o.float_mut() {
|
||||
f.z = 0;
|
||||
}
|
||||
}
|
||||
});
|
||||
doc
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +107,8 @@ fn the_fallback_keeps_order_visibility_and_direction() {
|
||||
// is copied into the outer one's text, so it comes after it).
|
||||
let tb = xml.find(r#"<v:textbox style="layout-flow:vertical;mso-layout-flow-alt:bottom-to-top">"#).expect("the outer box's text, turned");
|
||||
let rect = &xml[xml[..tb].rfind("<v:rect ").expect("its v:rect")..tb];
|
||||
assert!(rect.contains("z-index:10;"), "{rect}");
|
||||
// Its anchor's `relativeHeight`: the stored order, one less (see `Float::z`).
|
||||
assert!(rect.contains("z-index:9;"), "{rect}");
|
||||
assert!(rect.contains("visibility:hidden"), "{rect}");
|
||||
}
|
||||
|
||||
@@ -134,7 +135,8 @@ fn behind_text_shapes_keep_their_order() {
|
||||
.collect();
|
||||
got.sort_unstable();
|
||||
let low = -(1i64 << 31);
|
||||
assert_eq!(got, vec![low + 10, low + 20, -1], "{xml}");
|
||||
// The anchors' `relativeHeight`s (one less than `z`), the top one past `i32::MAX` kept at -1.
|
||||
assert_eq!(got, vec![low + 9, low + 19, -1], "{xml}");
|
||||
}
|
||||
|
||||
/// A shape VML has no simple form for stays a bare `wps:wsp`: guarded without a fallback, an old
|
||||
|
||||
@@ -432,10 +432,11 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize
|
||||
}
|
||||
}
|
||||
|
||||
/// The placement a flow keeps for a drawing: when it floats, or turns or mirrors it in line.
|
||||
/// Keep placement, transforms, and explicit stacking metadata even for inline drawings.
|
||||
/// Presence alone does not imply anchoring: the retained Float keeps its original wrap.
|
||||
fn kept_float(f: &craft_wordmodel::para::Float) -> Option<Box<craft_wordmodel::para::Float>> {
|
||||
let turned = f.rot.is_finite() && f.rot.rem_euclid(360.0) > 0.001 && f.rot.rem_euclid(360.0) < 359.999;
|
||||
(f.wrap != craft_wordmodel::para::Wrap::Inline || turned || f.flip_h || f.flip_v).then(|| Box::new(f.clone()))
|
||||
(f.wrap != craft_wordmodel::para::Wrap::Inline || turned || f.flip_h || f.flip_v || f.z != 0).then(|| Box::new(f.clone()))
|
||||
}
|
||||
|
||||
fn flow_comment(doc: &Document, c: &craft_wordmodel::Comment, parent: Option<u32>, opts: FlowOpts) -> FComment {
|
||||
@@ -1282,3 +1283,18 @@ impl ListCounter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod stacking_tests {
|
||||
#[test]
|
||||
fn explicit_inline_stacking_preserves_wrap_without_creating_an_anchor() {
|
||||
use craft_wordmodel::para::{Float, Wrap};
|
||||
let f = Float { z: u32::MAX, ..Float::default() };
|
||||
assert_eq!(f.wrap, Wrap::Inline);
|
||||
let kept = super::kept_float(&f).unwrap();
|
||||
assert_eq!(kept.wrap, Wrap::Inline);
|
||||
assert_eq!(kept.z, u32::MAX);
|
||||
assert_eq!(kept.rot, f.rot);
|
||||
assert!(super::kept_float(&Float::default()).is_none());
|
||||
}
|
||||
}
|
||||
@@ -170,8 +170,9 @@ pub struct Img {
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
pub alt: String,
|
||||
/// How a floating picture is placed and wrapped, for formats that keep it (ODT); `None`: in
|
||||
/// line with the text.
|
||||
/// Placement and drawing metadata for formats that keep it (ODT). `None` is inline;
|
||||
/// `Some` may also be inline, retaining rotation, mirroring or explicit stacking order.
|
||||
/// The Float wrap, not the Option, determines anchoring.
|
||||
pub float: Option<Box<craft_wordmodel::para::Float>>,
|
||||
/// The embedded object this picture shows, kept whole (ODT only; see [`OdfObject`]).
|
||||
pub object: Option<Arc<OdfObject>>,
|
||||
|
||||
@@ -40,7 +40,29 @@ impl Bezier {
|
||||
|
||||
/// The path as `{c, v, i, o}`, coordinates rounded to six decimals.
|
||||
pub fn to_json(&self) -> Json {
|
||||
let pts = |v: &[[f64; 2]]| v.iter().map(|[x, y]| json!([round6(*x), round6(*y)])).collect::<Vec<_>>();
|
||||
self.to_json_with(|v| json!(round6(v)))
|
||||
}
|
||||
|
||||
/// Writes the path with a caller-owned numeric representation (for example,
|
||||
/// three-decimal compact exports). Geometry and tangent lengths are unchanged.
|
||||
/// The callback is applied to every coordinate; callers own finite-value policy.
|
||||
pub fn to_json_with(&self, number: impl Fn(f64) -> Json) -> Json {
|
||||
let pts = |v: &[[f64; 2]]| v.iter().map(|[x, y]| Json::Array(vec![number(*x), number(*y)])).collect::<Vec<_>>();
|
||||
json!({"c": self.closed, "v": pts(&self.vertices), "i": pts(&self.in_tangents), "o": pts(&self.out_tangents)})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod policy_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn caller_number_policy_is_applied_without_prior_rounding() {
|
||||
let p = Bezier { closed: true, vertices: vec![[1.23456, 1e303]], in_tangents: vec![[0.0, -2.0]], out_tangents: vec![] };
|
||||
let raw = p.to_json_with(|v| json!(v));
|
||||
assert_eq!(raw, json!({"c": true, "v": [[1.23456, 1e303]], "i": [[0.0, -2.0]], "o": []}));
|
||||
let zero = p.to_json_with(|_| json!(0));
|
||||
assert_eq!(zero, json!({"c": true, "v": [[0, 0]], "i": [[0, 0]], "o": []}));
|
||||
assert_eq!(Bezier::default().to_json(), json!({"c": false, "v": [], "i": [], "o": []}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// One character walker, with explicit output policies: ordinary Markdown keeps line
|
||||
// structure; extracted text flattens it and strips unrepresentable/control characters.
|
||||
pub(crate) fn escape(s: &str, extracted: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if extracted && !matches!(c, '\t' | '\n' | '\r') && (c.is_ascii_control() || matches!(c, '\u{FFFE}' | '\u{FFFF}')) {
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'\n' | '\r' | '\t' if extracted => out.push(' '),
|
||||
'\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '|' | '&' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'#' | '!' if extracted => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\u{000C}' | '\u{000E}' => {}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -7,18 +7,7 @@ use super::{Align, Arc, Cell, Document, FBlock, FTable, Fmt, Inline, Kind, model
|
||||
|
||||
/// Escape text for Markdown (inline context).
|
||||
pub fn escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() + 8);
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '|' | '&' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\u{000C}' | '\u{000E}' => {}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::escaping::escape(s, false)
|
||||
}
|
||||
|
||||
/// Escape what would start a block at the beginning of a line. Leading spaces are kept, but at
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Markdown export for extracted text: one line per paragraph, conservative markup escaping,
|
||||
//! styled runs, pipe tables and explicit page separators. Unlike [`crate::export`], this mode
|
||||
//! does not infer a word-processing document or normalize its block structure. Callers keep
|
||||
//! layout/reading-order detection and bound the amount of supplied text and table data.
|
||||
// Extracted from PDFCraft's Markdown writer (Adrian), including the empty-run correction
|
||||
// by jonathanwxh-cell. The source remains shared here rather than copied into app adapters.
|
||||
|
||||
const MAX_HEADING: u8 = 6;
|
||||
/// Largest span represented by a table cell, matching the supported pipe-table grid.
|
||||
pub const MAX_SPAN: usize = 63;
|
||||
|
||||
fn md_text(s: &str) -> String {
|
||||
crate::escaping::escape(s, true)
|
||||
}
|
||||
|
||||
/// A table cell supplied by the caller's existing model, without a second table allocation.
|
||||
pub trait TableCell {
|
||||
fn text(&self) -> &str;
|
||||
fn bold(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn italic(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn span(&self) -> usize {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/// `line` with its start escaped where Markdown would read a list item there (`- `, `+ `,
|
||||
/// `1. `, `1) `); the other block markers (`#`, `>`) are escaped by [`md_text`] already.
|
||||
fn block_start(line: String) -> String {
|
||||
let digits = line.bytes().take_while(u8::is_ascii_digit).count();
|
||||
match line.as_bytes().get(digits) {
|
||||
Some(b'.' | b')') if digits > 0 => format!("{}\\{}", line.get(..digits).unwrap_or_default(), line.get(digits..).unwrap_or_default()),
|
||||
Some(b'-' | b'+') if digits == 0 => format!("\\{line}"),
|
||||
_ => line,
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` (already escaped) in bold and/or italic, its outer spaces kept outside. `open` and
|
||||
/// `close` say whether `*` markers would be read as emphasis on that side (see [`marks`]);
|
||||
/// where they would not, as in `foo` + bold `.` + `bar`, the run is wrapped in HTML tags, which
|
||||
/// CommonMark takes inline. The text's own outer spaces count as a side that marks.
|
||||
pub fn emphasis(text: &str, bold: bool, italic: bool, open: bool, close: bool) -> String {
|
||||
let core = text.trim();
|
||||
if core.is_empty() || !(bold || italic) {
|
||||
return text.to_string();
|
||||
}
|
||||
let lead = text.get(..text.len().saturating_sub(text.trim_start().len())).unwrap_or_default();
|
||||
let trail = text.get(text.trim_end().len()..).unwrap_or_default();
|
||||
let markers = (open || !lead.is_empty()) && (close || !trail.is_empty());
|
||||
let (before, after) = match (markers, bold, italic) {
|
||||
(true, true, true) => ("***", "***"),
|
||||
(true, true, false) => ("**", "**"),
|
||||
(true, false, _) => ("*", "*"),
|
||||
(false, true, true) => ("<strong><em>", "</em></strong>"),
|
||||
(false, true, false) => ("<strong>", "</strong>"),
|
||||
(false, false, _) => ("<em>", "</em>"),
|
||||
};
|
||||
format!("{lead}{before}{core}{after}{trail}")
|
||||
}
|
||||
|
||||
/// A paragraph's runs (text, bold, italic) as one line of Markdown. Neighbouring runs in the
|
||||
/// same style are joined first, so two bold runs never meet as `****`.
|
||||
pub fn paragraph(runs: &[(&str, bool, bool)]) -> String {
|
||||
let mut merged: Vec<(String, bool, bool)> = Vec::new();
|
||||
for &(text, bold, italic) in runs {
|
||||
let text = md_text(text);
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match merged.last_mut() {
|
||||
Some(last) if last.1 == bold && last.2 == italic => last.0.push_str(&text),
|
||||
_ => merged.push((text, bold, italic)),
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for (k, (text, bold, italic)) in merged.iter().enumerate() {
|
||||
let core = text.trim();
|
||||
let open = marks(core.chars().next(), out.chars().last());
|
||||
// Markers of a styled neighbour right next to these would join them into one run.
|
||||
let close = match merged.get(k.saturating_add(1)) {
|
||||
Some((next, b, i)) if (*b || *i) && !next.starts_with(char::is_whitespace) => false,
|
||||
next => marks(core.chars().last(), next.and_then(|(n, ..)| n.chars().next())),
|
||||
};
|
||||
out.push_str(&emphasis(text, *bold, *italic, open, close));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a `*` marker between the text's `edge` character and the `outside` one is read as
|
||||
/// emphasis (CommonMark's flanking rules for `*`): always next to a space or the line's edge,
|
||||
/// never next to another `*`, and otherwise unless the text's edge is punctuation while the
|
||||
/// outside is a letter or digit.
|
||||
fn marks(edge: Option<char>, outside: Option<char>) -> bool {
|
||||
match (edge, outside) {
|
||||
(_, None) => true,
|
||||
(_, Some(o)) if o.is_whitespace() => true,
|
||||
(_, Some('*')) => false,
|
||||
(Some(e), Some(o)) => e.is_alphanumeric() || o.is_ascii_punctuation(),
|
||||
(None, Some(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn cell(c: &impl TableCell) -> String {
|
||||
emphasis(&md_text(c.text()), c.bold(), c.italic(), true, true)
|
||||
}
|
||||
|
||||
/// Incremental block writer. Input text is escaped; no caller-provided markup is trusted.
|
||||
#[derive(Default)]
|
||||
pub struct Writer {
|
||||
blocks: Vec<String>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// Create an empty extracted-text document.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Append a paragraph or heading (levels above six are clamped). Heading weight comes
|
||||
/// from its heading marker; callers may still supply italic runs.
|
||||
pub fn paragraph(&mut self, runs: &[(&str, bool, bool)], level: u8) {
|
||||
let text = paragraph(runs);
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.blocks.push(match level {
|
||||
0 => block_start(text.to_string()),
|
||||
l => format!("{} {text}", "#".repeat(usize::from(l.min(MAX_HEADING)))),
|
||||
});
|
||||
}
|
||||
|
||||
/// Append a pipe table with the first row as its header. Short rows are padded to the
|
||||
/// widest row, and each span is clamped to 1..=MAX_SPAN. Callers bound input rows/cells.
|
||||
pub fn table<C: TableCell>(&mut self, rows: &[Vec<C>]) {
|
||||
let span = |c: &C| c.span().clamp(1, MAX_SPAN);
|
||||
let width = rows.iter().map(|r| r.iter().map(span).fold(0usize, usize::saturating_add)).max().unwrap_or(0);
|
||||
if width == 0 {
|
||||
return;
|
||||
}
|
||||
let mut lines = Vec::with_capacity(rows.len().saturating_add(1));
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let mut cells: Vec<String> = Vec::with_capacity(width);
|
||||
for c in row {
|
||||
cells.push(cell(c));
|
||||
cells.extend(std::iter::repeat_n(String::new(), span(c).saturating_sub(1)));
|
||||
}
|
||||
cells.resize(width, String::new());
|
||||
lines.push(format!("| {} |", cells.join(" | ")));
|
||||
if i == 0 {
|
||||
lines.push(format!("|{}", " --- |".repeat(width)));
|
||||
}
|
||||
}
|
||||
self.blocks.push(lines.join("\n"));
|
||||
}
|
||||
|
||||
/// Append a thematic break, including consecutive and leading page separators.
|
||||
pub fn page_break(&mut self) {
|
||||
self.blocks.push("---".into());
|
||||
}
|
||||
|
||||
/// Join blocks with blank lines and finish with a newline (also for an empty document).
|
||||
pub fn finish(self) -> String {
|
||||
let mut out = self.blocks.join("\n\n");
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::paragraph;
|
||||
|
||||
#[test]
|
||||
fn empty_or_control_run_does_not_split_styled_runs() {
|
||||
assert_eq!(paragraph(&[("hello", true, false), ("", false, false), ("world", true, false)]), "**helloworld**");
|
||||
assert_eq!(paragraph(&[("hello", true, false), ("\u{1}", false, false), ("world", true, false)]), "**helloworld**");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_styled_run_does_not_affect_neighbor_emphasis() {
|
||||
assert_eq!(paragraph(&[("x", true, false), ("", false, true)]), "**x**");
|
||||
assert_eq!(paragraph(&[("foo", false, false), (".", true, false), ("", true, true), ("bar", false, false)]), "foo<strong>.</strong>bar");
|
||||
// Empty/control runs between differently styled runs still look ahead to the next non-empty run.
|
||||
assert_eq!(paragraph(&[("bold", true, false), ("", false, false), ("italic", false, true)]), "<strong>bold</strong>*italic*");
|
||||
assert_eq!(paragraph(&[("bold", true, false), ("\u{1}", false, false), (" italic", false, true)]), "**bold** *italic*");
|
||||
// Leading empty/control runs do not affect the opening delimiter.
|
||||
assert_eq!(paragraph(&[("", false, true), ("\u{1}", true, false), ("lead", true, false)]), "**lead**");
|
||||
// All-empty/control paragraphs produce empty output.
|
||||
assert_eq!(paragraph(&[("", true, false), ("\u{1}", false, true), ("\u{7f}", false, false)]), "");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod writer_tests {
|
||||
use super::*;
|
||||
|
||||
struct Cell(&'static str, usize);
|
||||
impl TableCell for Cell {
|
||||
fn text(&self) -> &str {
|
||||
self.0
|
||||
}
|
||||
fn span(&self) -> usize {
|
||||
self.1
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_block_spacing_heading_clamp_and_table_spans() {
|
||||
let mut w = Writer::new();
|
||||
w.page_break();
|
||||
w.paragraph(&[("12. item\nnext", false, false)], 0);
|
||||
w.paragraph(&[("Title", false, true)], 255);
|
||||
w.table(&[vec![Cell("A|B", 2)], vec![Cell("C", 0)]]);
|
||||
w.page_break();
|
||||
assert_eq!(w.finish(), "---\n\n12\\. item next\n\n###### *Title*\n\n| A\\|B | |\n| --- | --- |\n| C | |\n\n---\n");
|
||||
assert_eq!(Writer::new().finish(), "\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_filter_and_literal_punctuation_stay_explicit() {
|
||||
assert_eq!(paragraph(&[("\0\u{7f}\u{fffe}\u{ffff}\n\r\t#!&", false, false)]), " \\#\\!\\&");
|
||||
// Ordinary export retains its existing newline/control policy and #/! behavior.
|
||||
assert_eq!(crate::escaping::escape("\0\n#!\u{c}\u{e}&", false), "\0\n#!\\&");
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,9 @@ use craft_wordmodel::{Align, Document};
|
||||
use craft_flow::{self as model, Cell, FBlock, FTable, Fmt, Inline, Kind, ListInfo, Para, make_img};
|
||||
|
||||
mod blocks;
|
||||
mod escaping;
|
||||
mod export;
|
||||
pub mod extracted;
|
||||
mod inlines;
|
||||
|
||||
pub use craft_flow::MAX_TABLE_CELLS;
|
||||
|
||||
@@ -1268,6 +1268,7 @@ impl Body<'_> {
|
||||
self.group = Some(OpenGroup {
|
||||
anchor: get(a, "text:anchor-type").map(String::from),
|
||||
page: get(a, "text:anchor-page-number").map(String::from),
|
||||
z: crate::text::frames::z_of(a),
|
||||
style: get(a, "draw:style-name").map(String::from),
|
||||
members: Vec::new(),
|
||||
});
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(in crate::text) struct OpenGroup {
|
||||
pub(in crate::text) anchor: Option<String>,
|
||||
/// Its `text:anchor-page-number`.
|
||||
pub(in crate::text) page: Option<String>,
|
||||
pub(in crate::text) z: u32,
|
||||
pub(in crate::text) style: Option<String>,
|
||||
pub(in crate::text) members: Vec<model::Member>,
|
||||
}
|
||||
@@ -103,8 +104,9 @@ impl Body<'_> {
|
||||
f.flip_v ^= v;
|
||||
}
|
||||
// Kept when it floats, or turns or mirrors the object in line.
|
||||
let float = float
|
||||
.filter(|f| f.wrap != craft_wordmodel::para::Wrap::Inline || crate::text::frames::turned(f) || f.flip_h || f.flip_v || f.y != 0.0);
|
||||
let float = float.filter(|f| {
|
||||
f.wrap != craft_wordmodel::para::Wrap::Inline || crate::text::frames::turned(f) || f.flip_h || f.flip_v || f.y != 0.0 || f.z != 0
|
||||
});
|
||||
if let Some(blocks) = &boxed
|
||||
&& self.take_watermark(blocks)
|
||||
{
|
||||
@@ -353,7 +355,8 @@ impl Body<'_> {
|
||||
let mut float =
|
||||
crate::text::frames::float_of(g.anchor.as_deref(), Some(&crate::text::writer::pt(x0)), Some(&crate::text::writer::pt(y0)), &graphic);
|
||||
float.page = crate::text::frames::page_of(g.anchor.as_deref(), g.page.as_deref(), &graphic);
|
||||
let float = (float.wrap != craft_wordmodel::para::Wrap::Inline).then(|| Box::new(float));
|
||||
float.z = g.z;
|
||||
let float = (float.wrap != craft_wordmodel::para::Wrap::Inline || float.z != 0).then(|| Box::new(float));
|
||||
let fit = |v: f32| if v.is_finite() { v.clamp(1.0, MAX_LEN) } else { 1.0 };
|
||||
self.push_inline(Inline::Group { w: fit(x1 - x0), h: fit(y1 - y0), float, members });
|
||||
}
|
||||
|
||||
@@ -443,9 +443,59 @@ pub(super) fn z_of(a: &Attrs) -> u32 {
|
||||
get(a, "draw:z-index").and_then(|v| v.trim().parse::<u32>().ok()).map_or(0, |z| z.saturating_add(1))
|
||||
}
|
||||
|
||||
/// `float`'s place in the stacking order as `draw:z-index` (see [`z_of`]): 0 when unknown.
|
||||
pub(crate) fn z_index(float: Option<&Float>) -> u32 {
|
||||
float.map_or(0, |f| f.z.saturating_sub(1))
|
||||
/// Raw export orders. The package writer normalizes their upper boundary once,
|
||||
/// after adding all retained markup, leaving room for one-more model orders.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct Stacking {
|
||||
unset: u32,
|
||||
}
|
||||
|
||||
/// A stored order stays below every unset order; equal stored orders remain equal.
|
||||
pub(crate) fn z_index(float: Option<&Float>, stacking: Stacking) -> u32 {
|
||||
match float.map(|f| f.z) {
|
||||
Some(z) if z > 0 => z - 1,
|
||||
_ => stacking.unset,
|
||||
}
|
||||
}
|
||||
|
||||
/// Include group members and inline frames too: the ODF writer emits their orders.
|
||||
pub(crate) fn stacking(doc: &craft_wordmodel::Document) -> Result<Stacking, String> {
|
||||
use craft_wordmodel::para::{GroupChild, InlineObject};
|
||||
use std::collections::BTreeSet;
|
||||
fn members(children: &[GroupChild], depth: usize, orders: &mut BTreeSet<u32>) {
|
||||
for c in children {
|
||||
if let Some((_, _, f)) = c.obj.frame()
|
||||
&& f.z > 0
|
||||
{
|
||||
orders.insert(f.z);
|
||||
}
|
||||
if let InlineObject::Group { children, .. } = &c.obj
|
||||
&& depth < craft_flow::MAX_GROUP_DEPTH
|
||||
{
|
||||
members(children, depth + 1, orders);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mut orders, _) = doc.stacking_orders();
|
||||
for blocks in std::iter::once(&doc.body).chain(doc.parts.values().map(|p| &p.blocks)) {
|
||||
for b in blocks {
|
||||
craft_wordmodel::walk::each_para(b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
if let Some((_, _, f)) = o.frame()
|
||||
&& f.z > 0
|
||||
{
|
||||
orders.insert(f.z);
|
||||
}
|
||||
if let InlineObject::Group { children, .. } = o {
|
||||
members(children, 0, &mut orders);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// Final content/styles normalization includes retained XML, not just modeled frames.
|
||||
// Keep the distinct raw MAX slot here; the package writer removes an unused slot once.
|
||||
Ok(Stacking { unset: orders.last().copied().unwrap_or(0) })
|
||||
}
|
||||
|
||||
/// How far a frame `h` points tall in line with the text is raised from standing on the
|
||||
@@ -656,3 +706,37 @@ pub(super) fn frame_of(f: &Float, w: f32, h: f32) -> (&'static str, String, Stri
|
||||
}
|
||||
(anchor, props, xy)
|
||||
}
|
||||
|
||||
/// Scan the same already-inflated content/style streams as the body and header readers.
|
||||
/// The existing event parser supplies the same entity, malformed-input and 128-attribute
|
||||
/// truncation behavior; no picture fetch or embedded-object callback is invoked.
|
||||
pub(super) fn read_orders(content: &[u8], styles: Option<&[u8]>) -> Result<craft_wordmodel::para::FileOrders, String> {
|
||||
use craft_wordmodel::para::FileOrderScan;
|
||||
let bytes = (content.len() as u64).checked_add(styles.map_or(0, |s| s.len() as u64)).ok_or("stacking-order source size overflow")?;
|
||||
let mut scan = FileOrderScan::new(bytes)?;
|
||||
for xml in std::iter::once(content).chain(styles) {
|
||||
super::xml::events(xml, |ev| {
|
||||
if let super::xml::Ev::Start(_, attrs) = ev
|
||||
&& let Some(raw) = get(&attrs, "draw:z-index").and_then(|s| s.trim().parse::<u32>().ok())
|
||||
{
|
||||
scan.observe(raw);
|
||||
}
|
||||
});
|
||||
}
|
||||
scan.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod file_order_tests {
|
||||
#[test]
|
||||
fn file_order_scan_uses_the_existing_odf_attribute_and_entity_rules() {
|
||||
let ignored = format!(r#"<r {} draw:z-index="4294967295"/>"#, (0..128).map(|i| format!(r#"a{i}="x""#)).collect::<Vec<_>>().join(" "));
|
||||
let map = super::read_orders(ignored.as_bytes(), None).unwrap();
|
||||
assert_eq!(map.model_order(Some(u32::MAX - 1)), u32::MAX);
|
||||
let custom = br#"<!DOCTYPE r [<!ENTITY rank "4294967295">]><r draw:z-index="&rank;"/>"#;
|
||||
assert_eq!(super::read_orders(custom, None).unwrap().model_order(Some(u32::MAX - 1)), u32::MAX);
|
||||
let numeric = br#"<r draw:z-index="4294967295"><x draw:z-index="4294967294"/></r>"#;
|
||||
let map = super::read_orders(numeric, None).unwrap();
|
||||
assert_eq!((map.model_order(Some(u32::MAX - 1)), map.model_order(Some(u32::MAX))), (u32::MAX - 1, u32::MAX));
|
||||
}
|
||||
}
|
||||
@@ -875,6 +875,12 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result<Parsed, String> {
|
||||
None if styles_xml.is_some() => EMPTY_CONTENT.as_bytes().to_vec(),
|
||||
None => return Err("ODT: content.xml is missing".into()),
|
||||
};
|
||||
let file_orders = super::frames::read_orders(&content, styles_xml.as_deref())?;
|
||||
// Normalize source values before both model parsing and retained-markup capture.
|
||||
// Rewriting values only keeps unknown XML and the model on the same order scale.
|
||||
let content = super::xml::remap_orders(&content, |raw| file_orders.file_order(raw))?;
|
||||
let styles_normalized = styles_xml.as_deref().map(|xml| super::xml::remap_orders(xml, |raw| file_orders.file_order(raw))).transpose()?;
|
||||
let styles_xml = styles_normalized;
|
||||
let mut styles = Styles::default();
|
||||
let mut pages = Pages::default();
|
||||
if let Some(s) = &styles_xml {
|
||||
@@ -931,6 +937,7 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result<Parsed, String> {
|
||||
styles_xml.as_deref().map(|x| page_parts::read(x, &styles, &mut pages, &mut fetch, objects, &mut spaces_left)).unwrap_or_default();
|
||||
first_pages(&mut pages);
|
||||
let mut body = Body::new(&styles, &pages, &mut fetch);
|
||||
|
||||
(body.entries, body.manifest) = (objects.0, Some(objects.1));
|
||||
body.raw = &content;
|
||||
body.markup = &content;
|
||||
|
||||
@@ -1098,6 +1098,7 @@ fn export_as(doc: &Document, mime: &str) -> Result<Vec<u8>, String> {
|
||||
// Paragraphs kept as read name their own automatic styles: WordCraft's take another prefix.
|
||||
let kept = doc.kept.of("odt");
|
||||
let mut w = if kept.is_some() { Writer::with_prefix(KEPT_PREFIX) } else { Writer::default() };
|
||||
w.stacking = super::frames::stacking(doc)?;
|
||||
w.note_numbers = Some([false, true].map(|endnote| {
|
||||
let o = doc.note_options(&doc.last_section, endnote);
|
||||
(o.num_fmt, o.num_start)
|
||||
@@ -1229,6 +1230,7 @@ fn export_as(doc: &Document, mime: &str) -> Result<Vec<u8>, String> {
|
||||
// Headers' and footers' new pictures and objects skip the kept files' names too.
|
||||
hw.reserved = std::sync::Arc::clone(&w.reserved);
|
||||
hw.read_names = std::sync::Arc::clone(&w.read_names);
|
||||
hw.stacking = w.stacking;
|
||||
hw.accents = accents;
|
||||
hw.variables.clone_from(&w.variables);
|
||||
let parts: Vec<PageParts> = pages.iter().map(|(_, sec)| page_parts(doc, sec, &mut hw)).collect();
|
||||
@@ -1318,10 +1320,16 @@ fn export_as(doc: &Document, mime: &str) -> Result<Vec<u8>, String> {
|
||||
None => styles,
|
||||
};
|
||||
let (content, styles) = with_kept_defs(content, styles, &w.kept_used, &w.kept_defs);
|
||||
// Choose the gap from everything actually written, including unknown retained
|
||||
// drawings and master pages. Remapping modeled frames alone can alias an order
|
||||
// present only in retained XML. Values are spliced without reserializing XML.
|
||||
let orders = super::frames::read_orders(content.as_bytes(), Some(styles.as_bytes()))?;
|
||||
let content = super::xml::remap_orders(content.as_bytes(), |raw| orders.file_order(raw))?;
|
||||
let styles = super::xml::remap_orders(styles.as_bytes(), |raw| orders.file_order(raw))?;
|
||||
// The manifest lists every file already: the writer adds the files only.
|
||||
for (name, data) in [
|
||||
("content.xml", content.as_bytes()),
|
||||
("styles.xml", styles.as_bytes()),
|
||||
("content.xml", content.as_ref()),
|
||||
("styles.xml", styles.as_ref()),
|
||||
("meta.xml", meta.as_bytes()),
|
||||
("settings.xml", settings_xml(doc).as_bytes()),
|
||||
] {
|
||||
|
||||
@@ -362,12 +362,65 @@ fn a_frame_keeps_its_place_in_the_stacking_order() {
|
||||
let saved = crate::text::tests::export_model(&d).unwrap();
|
||||
assert!(crate::text::tests::entry(&saved, "content.xml").contains(r#"draw:z-index="3""#));
|
||||
assert_eq!(float(&import(&saved).unwrap()).z, 4);
|
||||
// Unknown (inserted in WordCraft): at the bottom, in document order.
|
||||
// Unknown (inserted in WordCraft), with nothing else stored: 0.
|
||||
let d = open(r#"style:wrap="run-through""#, r#"text:anchor-type="paragraph""#);
|
||||
assert_eq!(float(&d).z, 0);
|
||||
assert!(crate::text::tests::entry(&crate::text::tests::export_model(&d).unwrap(), "content.xml").contains(r#"draw:z-index="0""#));
|
||||
}
|
||||
|
||||
/// An object without a stored order (made in WordCraft) stacks above every object that has one
|
||||
/// (`Float::z`), so it is written above them, not at the bottom.
|
||||
#[test]
|
||||
fn an_object_made_here_is_written_above_the_stored_orders() {
|
||||
let png = [b"\x89PNG\r\n\x1a\n".as_slice(), &[7u8; 64]].concat();
|
||||
let frame = |z: &str| {
|
||||
format!(
|
||||
r#"<draw:frame draw:style-name="fr1" svg:width="2in" svg:height="1in" text:anchor-type="paragraph"{z}><draw:image xlink:href="Pictures/a.png"/></draw:frame>"#
|
||||
)
|
||||
};
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS_T} {NS_D}><office:automatic-styles><style:style style:name="fr1" style:family="graphic"><style:graphic-properties style:wrap="run-through"/></style:style></office:automatic-styles><office:body><office:text><text:p>{}{}Text beside.</text:p></office:text></office:body></office:document-content>"#,
|
||||
frame(r#" draw:z-index="3""#),
|
||||
frame("")
|
||||
);
|
||||
let d = import(&zip_of(&[("content.xml", content.as_bytes()), ("Pictures/a.png", &png)])).unwrap();
|
||||
let zs: Vec<u32> = d.body[0]
|
||||
.as_para()
|
||||
.unwrap()
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| if let InlineObject::Image { float, .. } = o { Some(float.z) } else { None })
|
||||
.collect();
|
||||
assert_eq!(zs, [4, 0], "one stored, one made here");
|
||||
let content = crate::text::tests::entry(&crate::text::tests::export_model(&d).unwrap(), "content.xml");
|
||||
let z: Vec<&str> = content.split(r#"draw:z-index=""#).skip(1).filter_map(|s| s.split('"').next()).collect();
|
||||
assert_eq!(z, ["3", "4"], "{content}");
|
||||
}
|
||||
|
||||
/// A group's members are written with their own stacking orders, so a member without one (made
|
||||
/// in WordCraft) goes above a member's stored order too, not just above the floating objects'.
|
||||
#[test]
|
||||
fn an_object_made_here_is_written_above_the_group_members_stored_orders() {
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS_T} {NS_D}><office:body><office:text><text:p><draw:g text:anchor-type="paragraph"><draw:rect svg:width="1in" svg:height="1in" svg:x="0in" svg:y="0in"/><draw:ellipse svg:width="1in" svg:height="1in" svg:x="1in" svg:y="0in"/></draw:g>Text beside.</text:p></office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap();
|
||||
// The group stored at the bottom, its first member stored above it, its second made here.
|
||||
d.objects_mut(&|o| matches!(o, InlineObject::Group { .. }), &mut |o| {
|
||||
let InlineObject::Group { float, children, .. } = o else { return };
|
||||
float.z = 1;
|
||||
let wrap = float.wrap;
|
||||
for (c, z) in children.iter_mut().zip([4, 0]) {
|
||||
if let Some(f) = c.obj.float_mut() {
|
||||
(f.wrap, f.z) = (wrap, z);
|
||||
}
|
||||
}
|
||||
});
|
||||
let content = crate::text::tests::entry(&crate::text::tests::export_model(&d).unwrap(), "content.xml");
|
||||
let z: Vec<&str> = content.split(r#"draw:z-index=""#).skip(1).filter_map(|s| s.split('"').next()).collect();
|
||||
assert_eq!(z, ["0", "3", "4"], "the group's, the stored member's, the member made here above it: {content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_anchored_to_a_page_stays_on_that_page() {
|
||||
// LibreOffice's page-anchored frames name their page. Written without it, a frame on page 3
|
||||
@@ -456,3 +509,141 @@ fn a_frame_offering_several_formats_shows_the_first_it_can_read() {
|
||||
let d = import(&zip_of(&[("content.xml", only.as_bytes()), ("Pictures/a.svm", &svm)])).unwrap();
|
||||
assert_eq!(pictures(&d), 0);
|
||||
}
|
||||
|
||||
/// Export must leave room for import's one-more encoding, including group members.
|
||||
#[test]
|
||||
fn extreme_stacking_orders_remain_distinct_after_repeated_roundtrips() {
|
||||
for (grouped, location) in [(false, 0), (true, 0), (false, 1), (true, 1), (false, 2), (true, 2), (false, 3)] {
|
||||
let shapes = r#"<draw:rect svg:width="1in" svg:height="1in"/>"#.repeat(5);
|
||||
let objects = if grouped {
|
||||
format!(r#"<draw:g text:anchor-type="paragraph">{shapes}</draw:g>"#)
|
||||
} else {
|
||||
shapes.replace("<draw:rect ", r#"<draw:rect text:anchor-type="paragraph" "#)
|
||||
};
|
||||
let objects = if location == 3 { objects.replacen(r#"text:anchor-type="paragraph""#, r#"text:anchor-type="as-char""#, 1) } else { objects };
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS_T} {NS_D}><office:body><office:text><text:p>{objects}</text:p></office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap();
|
||||
let zs = [1, u32::MAX - 1, u32::MAX, u32::MAX, 0];
|
||||
if grouped {
|
||||
d.objects_mut(&|o| matches!(o, InlineObject::Group { .. }), &mut |o| {
|
||||
let InlineObject::Group { float, children, .. } = o else { return };
|
||||
float.z = 1;
|
||||
for (child, z) in children.iter_mut().zip(zs) {
|
||||
child.obj.float_mut().unwrap().z = z;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
let mut orders = zs.into_iter();
|
||||
d.objects_mut(&|o| o.frame().is_some(), &mut |o| {
|
||||
let f = o.float_mut().unwrap();
|
||||
f.z = orders.next().unwrap();
|
||||
if location == 3 && f.wrap == Wrap::Inline {
|
||||
f.y = 6.0;
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut expected =
|
||||
vec!["0".to_string(), (u32::MAX - 3).to_string(), (u32::MAX - 2).to_string(), (u32::MAX - 2).to_string(), (u32::MAX - 1).to_string()];
|
||||
if grouped {
|
||||
expected.insert(0, "0".into());
|
||||
}
|
||||
if location == 1 || location == 2 {
|
||||
let blocks = std::mem::replace(&mut d.body, vec![craft_wordmodel::para_block(craft_wordmodel::Paragraph::new())]);
|
||||
let kind = if location == 1 { craft_wordmodel::PartKind::Header } else { craft_wordmodel::PartKind::Footer };
|
||||
d.parts.insert(1, craft_wordmodel::Part { kind, blocks, body: Default::default() });
|
||||
if location == 1 {
|
||||
d.last_section.headers.default = Some(1);
|
||||
} else {
|
||||
d.last_section.footers.default = Some(1);
|
||||
}
|
||||
}
|
||||
for pass in 0..3 {
|
||||
let bytes = crate::text::tests::export_model(&d).unwrap();
|
||||
let content = crate::text::tests::entry(&bytes, if location == 1 || location == 2 { "styles.xml" } else { "content.xml" });
|
||||
let actual: Vec<&str> = content.split(r#"draw:z-index=""#).skip(1).filter_map(|s| s.split('"').next()).collect();
|
||||
assert_eq!(actual, expected, "grouped={grouped}, location={location}, pass={pass}: {content}");
|
||||
if location == 3 {
|
||||
assert!(content.contains(r#"text:anchor-type="as-char""#), "inline must remain inline");
|
||||
assert!(content.contains(r#"svg:y="-78pt""#), "baseline raise must survive: {content}");
|
||||
}
|
||||
d = import(&bytes).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_raw_orders_are_normalized_once_across_body_and_headers() {
|
||||
let shape = |z: &str| format!(r#"<draw:rect text:anchor-type="paragraph" svg:width="1in" svg:height="1in" draw:z-index="{z}"/>"#);
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS_T} {NS_D}><office:body><office:text><text:p>{}{}</text:p></office:text></office:body></office:document-content>"#,
|
||||
shape("0"),
|
||||
shape("4294967294")
|
||||
);
|
||||
let styles = format!(
|
||||
r#"<office:document-styles {NS_T} {NS_D}><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21cm" fo:page-height="29.7cm"/></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"><style:header><text:p>{}{}</text:p></style:header></style:master-page></office:master-styles></office:document-styles>"#,
|
||||
shape("4294967295"),
|
||||
shape("4294967295")
|
||||
);
|
||||
let mut d = import(&zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes())])).unwrap();
|
||||
for _ in 0..3 {
|
||||
let body: Vec<u32> =
|
||||
d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect();
|
||||
let header = &d.parts[&d.last_section.headers.default.unwrap()];
|
||||
let head: Vec<u32> =
|
||||
header.blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect();
|
||||
assert_eq!(body, [1, u32::MAX - 1]);
|
||||
assert_eq!(head, [u32::MAX, u32::MAX]);
|
||||
d = import(&export(&d).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_stacking_markup_remaps_without_losing_unknown_attributes() {
|
||||
for raw in ["4294967294", "4294967295"] {
|
||||
let kept = format!(
|
||||
r#"<text:p strange="retain & a"><draw:rect text:anchor-type="paragraph" svg:width="1in" svg:height="1in" draw:z-index = '{raw}' strange="untouched"/></text:p>"#
|
||||
);
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS_T} {NS_D}><office:body><office:text>{kept}</office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap();
|
||||
let extra = format!(
|
||||
r#"<office:document-content {NS_T} {NS_D}><office:body><office:text><text:p><draw:rect text:anchor-type="paragraph" svg:width="1in" svg:height="1in"/></text:p></office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut added = import(&zip_of(&[("content.xml", extra.as_bytes())])).unwrap();
|
||||
added.objects_mut(&|o| o.frame().is_some(), &mut |o| o.float_mut().unwrap().z = 0);
|
||||
d.body.extend(added.body);
|
||||
for pass in 0..3 {
|
||||
let bytes = export(&d).unwrap();
|
||||
let xml = crate::text::tests::entry(&bytes, "content.xml");
|
||||
let expected = kept.replace(raw, "4294967293");
|
||||
assert!(xml.contains(&expected), "kept XML lost or order not remapped, {raw}, pass {pass}: {xml}");
|
||||
d = import(&bytes).unwrap();
|
||||
let orders: Vec<u32> =
|
||||
d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect();
|
||||
assert_eq!(orders, [u32::MAX - 1, u32::MAX], "{raw}, pass {pass}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_unknown_orders_participate_in_the_export_gap() {
|
||||
let kept = r#"<text:p strange="preserve"><alien draw:z-index='4294967293' keep="yes"/><draw:rect text:anchor-type="paragraph" svg:width="1in" svg:height="1in" draw:z-index="4294967294"/></text:p>"#;
|
||||
let content =
|
||||
format!(r#"<office:document-content {NS_T} {NS_D}><office:body><office:text>{kept}</office:text></office:body></office:document-content>"#);
|
||||
let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap();
|
||||
let mut extra = d.body[0].as_para().unwrap().clone();
|
||||
extra.objects[0].float_mut().unwrap().z = 0;
|
||||
d.body.push(craft_wordmodel::para_block(extra));
|
||||
for pass in 0..3 {
|
||||
let bytes = export(&d).unwrap();
|
||||
let xml = crate::text::tests::entry(&bytes, "content.xml");
|
||||
assert!(xml.contains("<alien draw:z-index='4294967292' keep=\"yes\"/>"), "pass {pass}: {xml}");
|
||||
d = import(&bytes).unwrap();
|
||||
let orders: Vec<u32> =
|
||||
d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect();
|
||||
assert_eq!(orders, [u32::MAX - 1, u32::MAX]);
|
||||
}
|
||||
}
|
||||
@@ -176,6 +176,8 @@ pub(super) struct Writer {
|
||||
pub(super) named_text: std::collections::BTreeSet<String>,
|
||||
/// Text boxes written so far (their frames' names).
|
||||
boxes: usize,
|
||||
/// Export stacking orders, also used by the header/footer writer.
|
||||
pub(super) stacking: super::frames::Stacking,
|
||||
/// Notes written so far (their ids), and footnotes and endnotes among them (their numbers).
|
||||
notes: usize,
|
||||
footnotes: u32,
|
||||
|
||||
@@ -200,7 +200,7 @@ impl Writer {
|
||||
// Always placed by a style (see `image_frame`).
|
||||
let (anchor, props, xy) = placement(place, c.w, c.h);
|
||||
let (anchor, style) = (anchor, format!(" draw:style-name=\"{}\"{xy}", self.graphic_style(props)));
|
||||
let z = place.z_index();
|
||||
let z = place.z_index(self.stacking);
|
||||
out.push_str(&format!(
|
||||
"<draw:frame draw:name=\"{}Chart{n}\"{style}{anchor} svg:width=\"{}\" svg:height=\"{}\" draw:z-index=\"{z}\">{inner}",
|
||||
self.prefix,
|
||||
|
||||
@@ -76,9 +76,10 @@ pub(in crate::text) enum Place<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Place<'a> {
|
||||
/// Its place in the stacking order (§19.231 `draw:z-index`, see `frames::z_of`).
|
||||
pub(in crate::text) fn z_index(self) -> u32 {
|
||||
crate::text::frames::z_index(self.float())
|
||||
/// Its place in the stacking order (§19.231 `draw:z-index`, see `frames::z_of`), `unset`
|
||||
/// without a stored one.
|
||||
pub(in crate::text) fn z_index(self, stacking: crate::text::frames::Stacking) -> u32 {
|
||||
crate::text::frames::z_index(self.float(), stacking)
|
||||
}
|
||||
|
||||
/// What turns or mirrors the object, and places it in the text.
|
||||
@@ -329,7 +330,7 @@ impl Writer {
|
||||
let (anchor, props, xy) = placement(place, img.w, img.h);
|
||||
let (anchor, style) =
|
||||
(anchor, format!(" draw:style-name=\"{}\"{xy}", self.graphic_style(format!("{}{props}{clip}", super::GRAPHICS_PARENT))));
|
||||
let z = place.z_index();
|
||||
let z = place.z_index(self.stacking);
|
||||
out.push_str(&format!(
|
||||
"<draw:frame draw:name=\"{}Image{n}\"{style}{anchor} svg:width=\"{}\" svg:height=\"{}\" draw:z-index=\"{z}\">{inner}",
|
||||
self.prefix,
|
||||
@@ -366,7 +367,8 @@ impl Writer {
|
||||
let (anchor, props, _) = placement(Place::Text(float.filter(|f| f.wrap != craft_wordmodel::para::Wrap::Inline)), size.0, size.1);
|
||||
let style = self.graphic_style(props);
|
||||
self.boxes += 1;
|
||||
out.push_str(&format!("<draw:g draw:name=\"{}Group{}\" draw:style-name=\"{style}\"{anchor} draw:z-index=\"0\">", self.prefix, self.boxes));
|
||||
let z = crate::text::frames::z_index(float, self.stacking);
|
||||
out.push_str(&format!("<draw:g draw:name=\"{}Group{}\" draw:style-name=\"{style}\"{anchor} draw:z-index=\"{z}\">", self.prefix, self.boxes));
|
||||
let at = Place::Text(float).origin();
|
||||
self.members(members, at, 0, out);
|
||||
out.push_str("</draw:g>");
|
||||
@@ -425,7 +427,7 @@ impl Writer {
|
||||
.and_then(|c| c.next.as_deref())
|
||||
.map(|n| format!(" draw:chain-next-name=\"{}{}\"", self.prefix, x(n)))
|
||||
.unwrap_or_default();
|
||||
let z = place.z_index();
|
||||
let z = place.z_index(self.stacking);
|
||||
out.push_str(&format!(
|
||||
"<draw:frame draw:name=\"{}\" draw:style-name=\"{style}\"{anchor} svg:width=\"{}\"{height}{xy} draw:z-index=\"{z}\"><draw:text-box{min}{next}>{body}</draw:text-box></draw:frame>",
|
||||
x(&name),
|
||||
@@ -528,7 +530,7 @@ impl Writer {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let conn = self.conn_attrs(kind, look);
|
||||
let z = place.z_index();
|
||||
let z = place.z_index(self.stacking);
|
||||
out.push_str(&format!(
|
||||
"<{element} draw:name=\"{}Shape{}\" draw:style-name=\"{style}\"{anchor}{at}{conn} draw:z-index=\"{z}\">{body}{geometry}</{element}>",
|
||||
self.prefix, self.boxes,
|
||||
|
||||
@@ -123,3 +123,141 @@ pub(super) fn holds_words(xml: &[u8], from: usize) -> bool {
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Rewrite only the first interpreted draw:z-index value in each start tag.
|
||||
/// Event spans exclude comments/CDATA and retain the reader's first-128-attribute
|
||||
/// policy. All bytes outside changed values (including unknown markup) survive.
|
||||
pub(super) fn remap_orders(xml: &[u8], map: impl Fn(u32) -> u32) -> Result<std::borrow::Cow<'_, [u8]>, String> {
|
||||
// Callers only remove one unused upper-order slot: unchanged MAX means identity.
|
||||
if map(u32::MAX) == u32::MAX {
|
||||
return Ok(std::borrow::Cow::Borrowed(xml));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut copied = 0;
|
||||
let mut error = None;
|
||||
events_at(xml, |ev, (start, end)| {
|
||||
if error.is_some() {
|
||||
return;
|
||||
}
|
||||
let Ev::Start(_, attrs) = ev else { return };
|
||||
let Some(raw) = get(&attrs, "draw:z-index").and_then(|s| s.trim().parse::<u32>().ok()) else { return };
|
||||
let mapped = map(raw);
|
||||
if mapped == raw {
|
||||
return;
|
||||
}
|
||||
let Some(tag) = xml.get(start..end) else { return };
|
||||
let Some(range) = order_value(tag) else {
|
||||
error = Some("ODT: cannot locate retained stacking attribute".to_string());
|
||||
return;
|
||||
};
|
||||
let from = start + range.start;
|
||||
let to = start + range.end;
|
||||
// Maps never increase a value; decimal replacement cannot exceed its source bytes.
|
||||
if out.is_empty() && out.try_reserve_exact(xml.len()).is_err() {
|
||||
error = Some("ODT: cannot allocate normalized stacking markup".to_string());
|
||||
return;
|
||||
}
|
||||
out.extend_from_slice(&xml[copied..from]);
|
||||
out.extend_from_slice(mapped.to_string().as_bytes());
|
||||
copied = to;
|
||||
});
|
||||
if let Some(error) = error {
|
||||
return Err(error);
|
||||
}
|
||||
if copied == 0 {
|
||||
return Ok(std::borrow::Cow::Borrowed(xml));
|
||||
}
|
||||
out.extend_from_slice(&xml[copied..]);
|
||||
Ok(std::borrow::Cow::Owned(out))
|
||||
}
|
||||
|
||||
/// Locate a quoted value in an already parsed start tag, not in arbitrary XML.
|
||||
/// Skip entire quoted values so attribute-looking text inside them is untouched.
|
||||
fn order_value(tag: &[u8]) -> Option<std::ops::Range<usize>> {
|
||||
let mut i = 1;
|
||||
while i < tag.len() && !tag[i].is_ascii_whitespace() && !matches!(tag[i], b'/' | b'>') {
|
||||
i += 1;
|
||||
}
|
||||
while i < tag.len() {
|
||||
while i < tag.len() && tag[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
let begin = i;
|
||||
while i < tag.len() && !tag[i].is_ascii_whitespace() && !matches!(tag[i], b'=' | b'/' | b'>') {
|
||||
i += 1;
|
||||
}
|
||||
let name = tag.get(begin..i)?;
|
||||
if name.is_empty() {
|
||||
// The lenient parser can recover after a stray delimiter before an attribute.
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
while i < tag.len() && tag[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
if tag.get(i) != Some(&b'=') {
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
while i < tag.len() && tag[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
let quote = *tag.get(i)?;
|
||||
if !matches!(quote, b'\'' | b'"') {
|
||||
while i < tag.len() && !tag[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
let from = i;
|
||||
while i < tag.len() && tag[i] != quote {
|
||||
i += 1;
|
||||
}
|
||||
if i == tag.len() {
|
||||
return None;
|
||||
}
|
||||
if name == b"draw:z-index" {
|
||||
return Some(from..i);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod order_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn order_remap_preserves_every_other_byte() {
|
||||
let xml = br#"<p a="draw:z-index='99'"><!-- draw:z-index="99" --><![CDATA[draw:z-index="99"]]><x q='&' draw:z-index = ' 99 ' weird="stay" draw:z-index="88"/><y draw:z-index="bad"/><z draw:z-index="0"/></p>"#;
|
||||
let expected = br#"<p a="draw:z-index='99'"><!-- draw:z-index="99" --><![CDATA[draw:z-index="99"]]><x q='&' draw:z-index = '98' weird="stay" draw:z-index="88"/><y draw:z-index="bad"/><z draw:z-index="0"/></p>"#;
|
||||
assert_eq!(remap_orders(xml, |n| n.saturating_sub(1)).unwrap().as_ref(), expected);
|
||||
assert!(matches!(remap_orders(xml, |n| n).unwrap(), std::borrow::Cow::Borrowed(_)));
|
||||
let late = format!("<x {} draw:z-index='99'/>", (0..128).map(|i| format!("a{i}='x'")).collect::<Vec<_>>().join(" "));
|
||||
assert_eq!(remap_orders(late.as_bytes(), |n| n - 1).unwrap().as_ref(), late.as_bytes());
|
||||
for broken in ["=bad", "x=bad", "x==bad", "x", "x='a' x", "x=\"bad\"", "'odd'", "/odd", "x='a>b'"] {
|
||||
let input = format!("<x {broken} draw:z-index='99'/>");
|
||||
let mut seen = false;
|
||||
events(input.as_bytes(), |e| {
|
||||
if let Ev::Start(_, a) = e {
|
||||
seen |= get(&a, "draw:z-index") == Some("99");
|
||||
}
|
||||
});
|
||||
if seen {
|
||||
let changed = remap_orders(input.as_bytes(), |n| n - 1).unwrap_or_else(|e| panic!("{input}: {e}"));
|
||||
let mut found = false;
|
||||
events(&changed, |e| {
|
||||
if let Ev::Start(_, a) = e {
|
||||
found |= get(&a, "draw:z-index") == Some("98");
|
||||
}
|
||||
});
|
||||
assert!(found, "{input}");
|
||||
}
|
||||
}
|
||||
// Lenient malformed attributes are skipped just as in the reader.
|
||||
let malformed = b"<x broken draw:z-index='99'/>";
|
||||
assert_eq!(remap_orders(malformed, |n| n - 1).unwrap().as_ref(), b"<x broken draw:z-index='98'/>");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "craft-palette"
|
||||
description = "Bounded, application-independent GIMP palette reading"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,97 @@
|
||||
//! GIMP palette (.gpl) reading with neutral RGB8 colours and names.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
/// Largest accepted palette, bounding all parsing allocations.
|
||||
pub const MAX_BYTES: usize = 1 << 20;
|
||||
/// Maximum colours returned; later rows are ignored.
|
||||
pub const MAX_COLORS: usize = 1024;
|
||||
/// A named RGB colour. Display-name sanitization belongs to the caller.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Color {
|
||||
/// Whitespace-normalized colour label; "Untitled" remains literal.
|
||||
pub name: String,
|
||||
/// Red, green and blue channels.
|
||||
pub rgb: [u8; 3],
|
||||
}
|
||||
/// A palette's title and colours, in file order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Palette {
|
||||
/// Last Name header before the colour limit; leading value whitespace is retained.
|
||||
pub name: String,
|
||||
/// Valid colour rows in file order.
|
||||
pub colors: Vec<Color>,
|
||||
}
|
||||
/// Reads GPL text, accepting BOM/CRLF, comments and metadata headers.
|
||||
/// Malformed colour rows are skipped. Missing magic, empty palettes and oversized
|
||||
/// input are errors. Columns and Channels headers are ignored for legacy compatibility.
|
||||
pub fn parse_gpl(text: &str) -> Result<Palette, String> {
|
||||
if text.len() > MAX_BYTES {
|
||||
return Err("the palette file is too large".into());
|
||||
}
|
||||
let mut lines = text.lines();
|
||||
let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim();
|
||||
if first != "GIMP Palette" {
|
||||
return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into());
|
||||
}
|
||||
let mut name = String::new();
|
||||
let mut out = Vec::new();
|
||||
for line in lines {
|
||||
let l = line.trim();
|
||||
if l.is_empty() || l.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = l.strip_prefix("Name:") {
|
||||
name = n.to_string();
|
||||
continue;
|
||||
}
|
||||
if l.starts_with("Columns:") || l.starts_with("Channels:") {
|
||||
continue;
|
||||
}
|
||||
let mut parts = l.split_whitespace();
|
||||
let channel = |s: Option<&str>| s.and_then(|v| v.parse::<u16>().ok()).filter(|v| *v <= 255).map(|v| v as u8);
|
||||
let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue };
|
||||
let rest: Vec<&str> = parts.collect();
|
||||
let label = rest.join(" ");
|
||||
out.push(Color { name: label, rgb: [r, g, b] });
|
||||
if out.len() >= MAX_COLORS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("the palette has no colours in it".into());
|
||||
}
|
||||
Ok(Palette { name, colors: out })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn metadata_rgb_names_and_legacy_rows() {
|
||||
let p = parse_gpl("\u{feff}GIMP Palette\r\nName: First\r\nName: Last\nColumns: 4\nChannels: RGB\n# comment\n255 0 128 Pink ink\n256 0 0 invalid\n-1 2 3 invalid\n1 2 3 Untitled\n4 5 6\n").unwrap();
|
||||
assert_eq!(p.name, " Last");
|
||||
assert_eq!(
|
||||
p.colors,
|
||||
vec![
|
||||
Color { name: "Pink ink".into(), rgb: [255, 0, 128] },
|
||||
Color { name: "Untitled".into(), rgb: [1, 2, 3] },
|
||||
Color { name: String::new(), rgb: [4, 5, 6] }
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_and_empty_input() {
|
||||
for text in ["", "not a palette", "GIMP Palette", "GIMP Palette\n256 0 0"] {
|
||||
assert!(parse_gpl(text).is_err());
|
||||
}
|
||||
assert!(parse_gpl(&"x".repeat(MAX_BYTES + 1)).is_err());
|
||||
let many = format!("GIMP Palette\n{}Name: ignored", "1 2 3 é\n".repeat(MAX_COLORS + 1));
|
||||
let p = parse_gpl(&many).unwrap();
|
||||
assert_eq!(p.colors.len(), MAX_COLORS);
|
||||
assert!(p.name.is_empty());
|
||||
assert_eq!(p.colors[0].name, "é");
|
||||
}
|
||||
}
|
||||
@@ -382,16 +382,43 @@ pub fn manifest(generated_by: &str, files: &[(&str, &str, Value)]) -> Value {
|
||||
serde_json::json!({"type": MANIFEST_TYPE, "version": 1, "generatedBy": generated_by, "refer": "penpot", "files": files, "relations": []})
|
||||
}
|
||||
|
||||
/// Incremental in-memory Penpot container writer. Members are compressed as they are added;
|
||||
/// the writer retains their names and archive output, not a second collection of payloads.
|
||||
/// Paths must be safe and distinct. Entries keep insertion order and use deflate level 3.
|
||||
/// If [`Writer::add`] fails, discard the writer: additions are not transactional, and a ZIP
|
||||
/// failure may leave a reserved member name or partially written output. Do not finish or reuse
|
||||
/// a writer after an error.
|
||||
#[derive(Default)]
|
||||
pub struct Writer {
|
||||
zip: craft_zip::Writer,
|
||||
seen: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Write one member immediately; the caller may release its serialized payload afterwards.
|
||||
/// On any error, discard this writer rather than retrying or calling [`Writer::finish`].
|
||||
pub fn add(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
|
||||
if path.is_empty() || !safe_name(path) || !self.seen.insert(path.to_owned()) {
|
||||
return Err(Error::Io(format!("unsafe or repeated member path: {}", path.chars().take(200).collect::<String>())));
|
||||
}
|
||||
self.zip.add(path, bytes, craft_zip::Compression::Level(3)).map_err(|e| Error::Io(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Result<Vec<u8>, Error> {
|
||||
self.zip.finish().map_err(|e| Error::Io(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A Penpot archive of `members` (path, bytes), deflated, in the order given. Paths must be safe
|
||||
/// and distinct, as [`Archive::open`] requires of what it reads.
|
||||
pub fn write_archive<'a>(members: impl IntoIterator<Item = (&'a str, &'a [u8])>) -> Result<Vec<u8>, Error> {
|
||||
let mut z = craft_zip::Writer::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut writer = Writer::new();
|
||||
for (path, bytes) in members {
|
||||
if path.is_empty() || !safe_name(path) || !seen.insert(path) {
|
||||
return Err(Error::Io(format!("unsafe or repeated member path: {}", path.chars().take(200).collect::<String>())));
|
||||
}
|
||||
z.add(path, bytes, craft_zip::Compression::Level(3)).map_err(|e| Error::Io(e.to_string()))?;
|
||||
writer.add(path, bytes)?;
|
||||
}
|
||||
z.finish().map_err(|e| Error::Io(e.to_string()))
|
||||
writer.finish()
|
||||
}
|
||||
@@ -438,3 +438,23 @@ fn an_archive_declaring_too_many_members_is_refused_before_it_is_indexed() {
|
||||
let bomb = craft_zip::zip64_entry_count_sample(MAX_ENTRIES as u64 + 1);
|
||||
assert_eq!(Archive::open(&bomb).err(), Some(Error::Corrupt("too many ZIP members".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_writer_keeps_members_and_rejects_ambiguous_paths() {
|
||||
let all = members();
|
||||
let mut writer = Writer::new();
|
||||
for (name, bytes) in &all {
|
||||
writer.add(name, bytes).unwrap();
|
||||
}
|
||||
let output = writer.finish().unwrap();
|
||||
assert_eq!(output, write_archive(all.iter().map(|(n, b)| (n.as_str(), b.as_slice()))).unwrap());
|
||||
let mut archive = Archive::open(&output).unwrap();
|
||||
assert_eq!(archive.names().first().map(String::as_str), Some("manifest.json"));
|
||||
assert_eq!(archive.page_shapes(FILE, PAGE).unwrap().len(), 2);
|
||||
for bad in ["../x", "/abs", "a/./b", "a\\b", "", "a\u{1}b"] {
|
||||
assert!(Writer::new().add(bad, b"x").is_err());
|
||||
}
|
||||
let mut duplicate = Writer::new();
|
||||
duplicate.add("a", b"first").unwrap();
|
||||
assert!(duplicate.add("a", b"second").is_err());
|
||||
}
|
||||
@@ -68,6 +68,15 @@ struct Bin<'a> {
|
||||
limits: Limits,
|
||||
}
|
||||
|
||||
/// Explicit legacy version-admission policy. Structural validation is never relaxed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BinaryOptions {
|
||||
/// Accept any eighth header byte after `bplist0`, matching historical inspection readers.
|
||||
/// This is not support for a new binary encoding: all objects still obey the bplist00
|
||||
/// grammar and bounds. The default accepts only the exact `bplist00` header.
|
||||
pub allow_unknown_minor_version: bool,
|
||||
}
|
||||
|
||||
/// Parse a `bplist00` binary property list.
|
||||
pub fn parse_binary(data: &[u8]) -> Result<Value, FormatError> {
|
||||
parse_binary_with_limits(data, Limits::default())
|
||||
@@ -75,19 +84,24 @@ pub fn parse_binary(data: &[u8]) -> Result<Value, FormatError> {
|
||||
|
||||
/// Parse a binary property list, with caller-selected input, object, expansion and nesting limits.
|
||||
pub fn parse_binary_with_limits(data: &[u8], limits: Limits) -> Result<Value, FormatError> {
|
||||
let (mut b, top) = reader(data, limits)?;
|
||||
parse_binary_with_options(data, limits, BinaryOptions::default())
|
||||
}
|
||||
|
||||
/// Parse with explicit version admission and the same structural/resource checks as the strict reader.
|
||||
pub fn parse_binary_with_options(data: &[u8], limits: Limits, options: BinaryOptions) -> Result<Value, FormatError> {
|
||||
let (mut b, top) = reader(data, limits, options)?;
|
||||
let mut stack = reserved(limits.max_depth.min(256))?;
|
||||
b.object(top, &mut stack)
|
||||
}
|
||||
|
||||
fn reader(data: &[u8], limits: Limits) -> Result<(Bin<'_>, usize), FormatError> {
|
||||
fn reader(data: &[u8], limits: Limits, options: BinaryOptions) -> Result<(Bin<'_>, usize), FormatError> {
|
||||
if data.len() > limits.max_input_bytes {
|
||||
return Err(FormatError::TooLarge("input bytes".into()));
|
||||
}
|
||||
if !data.starts_with(b"bplist") {
|
||||
return Err(FormatError::Malformed("not a binary plist".into()));
|
||||
}
|
||||
if !data.starts_with(b"bplist00") {
|
||||
if !data.starts_with(if options.allow_unknown_minor_version { b"bplist0".as_slice() } else { b"bplist00".as_slice() }) {
|
||||
return Err(FormatError::Unsupported("unknown binary plist version".into()));
|
||||
}
|
||||
let len = data.len();
|
||||
@@ -344,7 +358,7 @@ fn reserved_string(n: usize) -> Result<String, FormatError> {
|
||||
/// selected objects and resource exhaustion return errors. Unselected value graphs are not
|
||||
/// validated. This permits preference readers to ignore unrelated future object kinds.
|
||||
pub fn first_string_in_array(data: &[u8], key: &str, limits: Limits) -> Result<Option<String>, FormatError> {
|
||||
let (mut b, top) = reader(data, limits)?;
|
||||
let (mut b, top) = reader(data, limits, BinaryOptions::default())?;
|
||||
let (kind, n, start) = b.header(top)?;
|
||||
if kind != 0xd {
|
||||
return Ok(None);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
mod binary;
|
||||
mod bytes;
|
||||
mod xml;
|
||||
pub use binary::{DateValue, Value, first_string_in_array, parse_binary, parse_binary_with_limits};
|
||||
pub use binary::{BinaryOptions, DateValue, Value, first_string_in_array, parse_binary, parse_binary_with_limits, parse_binary_with_options};
|
||||
pub use xml::{XmlOptions, parse_xml, parse_xml_with_limits, parse_xml_with_options, parse_xml_with_token_limit};
|
||||
|
||||
/// Caller-selected resource limits. Zero values refuse the corresponding resource.
|
||||
|
||||
@@ -45,3 +45,26 @@ fn supported_maximum_widths_keep_their_values() {
|
||||
empty.extend_from_slice(&0u64.to_be_bytes());
|
||||
assert!(matches!(parse_binary(&single_object(&empty)), Ok(Value::Data(d)) if d.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minor_version_compatibility_is_explicit_and_keeps_bounds() {
|
||||
use craft_plist::{BinaryOptions, FormatError, Limits, parse_binary_with_options};
|
||||
let compat = BinaryOptions { allow_unknown_minor_version: true };
|
||||
for minor in [b'0', b'1', b'9', 0xff] {
|
||||
let mut data = single_object(&[0x00]);
|
||||
data[7] = minor;
|
||||
assert!(matches!(parse_binary_with_options(&data, Limits::default(), compat), Ok(Value::Null)));
|
||||
assert_eq!(parse_binary(&data).is_ok(), minor == b'0');
|
||||
let limited = Limits { max_nodes: 0, ..Limits::default() };
|
||||
assert!(matches!(parse_binary_with_options(&data, limited, compat), Err(FormatError::TooLarge(_))));
|
||||
data[6] = b'1';
|
||||
assert!(matches!(parse_binary_with_options(&data, Limits::default(), compat), Err(FormatError::Unsupported(_))));
|
||||
}
|
||||
let mut invalid = single_object(&[0x15]);
|
||||
invalid[7] = b'1';
|
||||
assert!(matches!(parse_binary_with_options(&invalid, Limits::default(), compat), Err(FormatError::Malformed(_))));
|
||||
let mut cycle = single_object(&[0xa1, 0]);
|
||||
cycle[7] = b'1';
|
||||
assert!(matches!(parse_binary_with_options(&cycle, Limits::default(), compat), Err(FormatError::Malformed(_))));
|
||||
assert!(parse_binary_with_options(b"bplist01", Limits::default(), compat).is_err());
|
||||
}
|
||||
@@ -225,13 +225,61 @@ pub mod packbits {
|
||||
decode_row(src, expected, out, true)
|
||||
}
|
||||
|
||||
/// Decodes a strict PackBits row directly into caller-owned storage, without allocating.
|
||||
///
|
||||
/// The output must be filled exactly: short input, truncated packets and packets that
|
||||
/// overflow the row are errors. Trailing bytes after the row is full are ignored, as by
|
||||
/// [`decode`]. An error may leave a decoded prefix in `out`; its remaining bytes are unchanged.
|
||||
pub fn decode_to_slice(src: &[u8], out: &mut [u8]) -> Result<()> {
|
||||
let mut offset: usize = 0;
|
||||
decode_packets(src, out.len(), false, |packet| {
|
||||
let len = packet.len();
|
||||
// The walker caps each packet by the remaining row, before exposing it here.
|
||||
let end = offset.checked_add(len).ok_or(PsdError::LimitExceeded("PackBits output offset overflow"))?;
|
||||
let dst = out.get_mut(offset..end).ok_or(PsdError::LimitExceeded("PackBits output slice overflow"))?;
|
||||
match packet {
|
||||
RowPacket::Literal(bytes) => dst.copy_from_slice(bytes),
|
||||
RowPacket::Fill(value, _) => dst.fill(value),
|
||||
}
|
||||
offset = end;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
enum RowPacket<'a> {
|
||||
Literal(&'a [u8]),
|
||||
Fill(u8, usize),
|
||||
}
|
||||
|
||||
impl RowPacket<'_> {
|
||||
fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::Literal(bytes) => bytes.len(),
|
||||
Self::Fill(_, len) => *len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_row(src: &[u8], expected: usize, out: &mut Vec<u8>, padded: bool) -> Result<()> {
|
||||
let target = out.len().checked_add(expected).ok_or(PsdError::LimitExceeded("PackBits output length overflows usize"))?;
|
||||
out.len().checked_add(expected).ok_or(PsdError::LimitExceeded("PackBits output length overflows usize"))?;
|
||||
decode_packets(src, expected, padded, |packet| {
|
||||
match packet {
|
||||
RowPacket::Literal(bytes) => out.extend_from_slice(bytes),
|
||||
RowPacket::Fill(value, len) => out.extend(std::iter::repeat_n(value, len)),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
// One packet walker serves strict Vec, strict slice and padded recovery decoding. It
|
||||
// validates the complete payload before clipping or emitting, preserving recovery errors.
|
||||
fn decode_packets(src: &[u8], expected: usize, padded: bool, mut emit: impl FnMut(RowPacket<'_>) -> Result<()>) -> Result<()> {
|
||||
let mut remaining = expected;
|
||||
let mut i = 0;
|
||||
while out.len() < target {
|
||||
while remaining > 0 {
|
||||
let Some(&h) = src.get(i) else {
|
||||
if padded {
|
||||
out.resize(target, 0);
|
||||
emit(RowPacket::Fill(0, remaining))?;
|
||||
break;
|
||||
}
|
||||
return Err(PsdError::Decompress("PackBits row ended early".into()));
|
||||
@@ -240,25 +288,28 @@ pub mod packbits {
|
||||
let h = h as i8;
|
||||
if h >= 0 {
|
||||
let len = h as usize + 1;
|
||||
let Some(lit) = src.get(i..i + len) else {
|
||||
let Some(lit) = i.checked_add(len).and_then(|end| src.get(i..end)) else {
|
||||
return Err(PsdError::Decompress("PackBits literal truncated".into()));
|
||||
};
|
||||
if !padded && len > target - out.len() {
|
||||
if !padded && len > remaining {
|
||||
return Err(PsdError::Decompress("PackBits literal overflows row".into()));
|
||||
}
|
||||
out.extend_from_slice(&lit[..len.min(target - out.len())]);
|
||||
let take = len.min(remaining);
|
||||
emit(RowPacket::Literal(&lit[..take]))?;
|
||||
remaining -= take;
|
||||
i += len;
|
||||
} else if h != -128 {
|
||||
let len = 1 - h as isize;
|
||||
let len = len as usize;
|
||||
let len = (1 - h as isize) as usize;
|
||||
let Some(&b) = src.get(i) else {
|
||||
return Err(PsdError::Decompress("PackBits run truncated".into()));
|
||||
};
|
||||
i += 1;
|
||||
if !padded && len > target - out.len() {
|
||||
if !padded && len > remaining {
|
||||
return Err(PsdError::Decompress("PackBits run overflows row".into()));
|
||||
}
|
||||
out.extend(std::iter::repeat_n(b, len.min(target - out.len())));
|
||||
let take = len.min(remaining);
|
||||
emit(RowPacket::Fill(b, take))?;
|
||||
remaining -= take;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -829,3 +829,44 @@ fn caller_scratch_prediction_rejects_invalid_inputs_before_mutation() {
|
||||
unpredict_with_scratch(&mut [], &empty, &mut []).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packbits_slice_matches_strict_rows_and_preserves_guards() {
|
||||
for (src, width) in [
|
||||
(vec![1, 10, 11, 128, 254, 7], 5),
|
||||
(vec![129, 9], 128),
|
||||
(vec![0, 4, 255], 1), // Ignore trailing malformed packets once full.
|
||||
(vec![], 0),
|
||||
(vec![128], 1),
|
||||
(vec![2, 1], 3),
|
||||
(vec![255], 2),
|
||||
(vec![255, 9], 1),
|
||||
(vec![1, 1, 2], 1),
|
||||
(vec![0, 8, 128], 2),
|
||||
] {
|
||||
let mut guarded = vec![0xA5; width + 2];
|
||||
let result = packbits::decode_to_slice(&src, &mut guarded[1..width + 1]);
|
||||
let reference = packbits::decode(&src, width);
|
||||
assert_eq!(result.is_ok(), reference.is_ok(), "{src:?}, width={width}");
|
||||
if let Ok(expected) = reference {
|
||||
assert_eq!(&guarded[1..width + 1], expected);
|
||||
}
|
||||
assert_eq!(guarded[0], 0xA5);
|
||||
assert_eq!(guarded[width + 1], 0xA5);
|
||||
}
|
||||
let mut out = [0xA5; 3];
|
||||
assert!(packbits::decode_to_slice(&[0, 8, 255], &mut out).is_err());
|
||||
assert_eq!(out, [8, 0xA5, 0xA5], "failure retains only completed packets");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packbits_slice_roundtrips_all_packet_lengths() {
|
||||
for len in 0..=256 {
|
||||
for bytes in [vec![42; len], (0..len).map(|i| i as u8).collect()] {
|
||||
let encoded = packbits::encode_vec(&bytes);
|
||||
let mut out = vec![0; len];
|
||||
packbits::decode_to_slice(&encoded, &mut out).unwrap();
|
||||
assert_eq!(out, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,5 +31,7 @@ pub mod svgz;
|
||||
pub mod tree;
|
||||
pub mod write;
|
||||
|
||||
/// Prefix-preserving kurbo path compatibility for legacy SVG importers.
|
||||
pub mod prefix_path;
|
||||
/// Compatibility CSS subset for simple SVG importers.
|
||||
pub mod simple_css;
|
||||
@@ -0,0 +1,480 @@
|
||||
//! SVG path data (SVG 1.1 §8.3 / SVG 2 §9.3): every command, implicit repeats, relative
|
||||
//! coordinates, smooth curves and elliptical arcs (converted to cubics through kurbo's `SvgArc`).
|
||||
//! Parsing stops at the first error, keeping what was read (as the specification asks).
|
||||
//!
|
||||
//! Compatibility API for importers requiring kurbo quadratics and cubic arc expansion,
|
||||
//! distinct from the strict neutral [`crate::path_data::parse_path`] API. Retains EffectCraft's
|
||||
//! malformed-prefix, close-path, finite-coordinate, radius-scaled tolerance and endpoint rules.
|
||||
//! Source: EffectCraft `pathdata.rs` at `05fc7f28352361f8f183da900ac5f4dfc9b69799`.
|
||||
//! Brandon Thomas authored the parser and post-Z termination fix; NetterSilver the arc
|
||||
//! tolerance/endpoint fixes; FredApps the finite-coordinate and element-budget safeguards.
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, SvgArc, Vec2};
|
||||
|
||||
/// Maximum path elements retained from one SVG path or point list.
|
||||
pub const MAX_PATH_ELEMENTS: usize = 100_000;
|
||||
|
||||
/// Tokenizer over numbers and command letters.
|
||||
struct Lex<'a> {
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Lex<'_> {
|
||||
fn skip_sep(&mut self) {
|
||||
while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == b',') {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn command(&mut self) -> Option<u8> {
|
||||
self.skip_sep();
|
||||
let c = *self.b.get(self.i)?;
|
||||
if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
|
||||
self.i += 1;
|
||||
Some(c)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn at_number(&mut self) -> bool {
|
||||
self.skip_sep();
|
||||
self.b.get(self.i).is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.'))
|
||||
}
|
||||
fn number(&mut self) -> Option<f64> {
|
||||
self.skip_sep();
|
||||
let start = self.i;
|
||||
let b = self.b;
|
||||
let mut i = self.i;
|
||||
if i < b.len() && matches!(b[i], b'-' | b'+') {
|
||||
i += 1;
|
||||
}
|
||||
let mut digits = false;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
if i < b.len() && b[i] == b'.' {
|
||||
i += 1;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
}
|
||||
if !digits {
|
||||
return None;
|
||||
}
|
||||
if i < b.len() && matches!(b[i], b'e' | b'E') {
|
||||
let mut j = i + 1;
|
||||
if j < b.len() && matches!(b[j], b'-' | b'+') {
|
||||
j += 1;
|
||||
}
|
||||
if j < b.len() && b[j].is_ascii_digit() {
|
||||
while j < b.len() && b[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
self.i = i;
|
||||
let number = std::str::from_utf8(&b[start..i]).ok()?.parse::<f64>().ok()?;
|
||||
number.is_finite().then_some(number)
|
||||
}
|
||||
/// Arc flags may be written without separators ("a1 1 0 00 1 1").
|
||||
fn flag(&mut self) -> Option<bool> {
|
||||
self.skip_sep();
|
||||
let c = *self.b.get(self.i)?;
|
||||
self.i += 1;
|
||||
match c {
|
||||
b'0' => Some(false),
|
||||
b'1' => Some(true),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum values retained from a points list (two coordinates per path element).
|
||||
pub const MAX_NUMBER_VALUES: usize = MAX_PATH_ELEMENTS * 2;
|
||||
|
||||
/// Parse a finite numeric prefix, retaining at most `min(max_values, MAX_NUMBER_VALUES)`.
|
||||
/// The flag reports a possible next number after the cap, not a malformed suffix.
|
||||
/// The caller must decide whether to refuse the document when the flag is set.
|
||||
pub fn numbers_bounded(s: &str, max_values: usize) -> (Vec<f64>, bool) {
|
||||
let max_values = max_values.min(MAX_NUMBER_VALUES);
|
||||
let mut l = Lex { b: s.as_bytes(), i: 0 };
|
||||
let mut v = vec![];
|
||||
while l.at_number() {
|
||||
if v.len() >= max_values {
|
||||
return (v, true);
|
||||
}
|
||||
match l.number() {
|
||||
Some(x) => v.push(x),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(v, false)
|
||||
}
|
||||
|
||||
/// Parse path data into a kurbo path, retaining at most [`MAX_PATH_ELEMENTS`] elements.
|
||||
/// Malformed or overlong input returns the prefix parsed before the problem.
|
||||
pub fn parse_path_data(d: &str) -> BezPath {
|
||||
parse_path_data_bounded(d, MAX_PATH_ELEMENTS).0
|
||||
}
|
||||
|
||||
/// Pen position and reflection state while parsing path commands.
|
||||
struct PathState {
|
||||
/// Current point.
|
||||
current: Point,
|
||||
/// Start of the current subpath.
|
||||
start: Point,
|
||||
/// Last cubic control point, for smooth curves.
|
||||
last_cubic: Option<Point>,
|
||||
/// Last quadratic control point, for smooth curves.
|
||||
last_quad: Option<Point>,
|
||||
/// Whether a subpath is open.
|
||||
open: bool,
|
||||
}
|
||||
|
||||
/// Cap on path elements and whether it has been hit.
|
||||
struct PathLimit {
|
||||
/// Maximum number of path elements.
|
||||
max_elements: usize,
|
||||
/// Set when the cap or a non-finite coordinate stopped output.
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
/// Parse at most `min(max_elements, MAX_PATH_ELEMENTS)` kurbo elements.
|
||||
/// The flag reports a reached cap with trailing input or a non-finite output coordinate.
|
||||
/// Malformed syntax alone returns the valid prefix without setting the flag. Importers
|
||||
/// should refuse the document on a true flag; [`parse_path_data`] intentionally keeps only
|
||||
/// the bounded prefix. Move/close commands and expanded arc cubics count toward the cap.
|
||||
pub fn parse_path_data_bounded(d: &str, max_elements: usize) -> (BezPath, bool) {
|
||||
let max_elements = max_elements.min(MAX_PATH_ELEMENTS);
|
||||
let mut l = Lex { b: d.as_bytes(), i: 0 };
|
||||
let mut p = BezPath::new();
|
||||
let mut state = PathState { current: Point::ZERO, start: Point::ZERO, last_cubic: None, last_quad: None, open: false };
|
||||
let mut limit = PathLimit { max_elements, exceeded: false };
|
||||
let mut cmd: Option<u8> = None;
|
||||
loop {
|
||||
if p.elements().len() >= limit.max_elements {
|
||||
l.skip_sep();
|
||||
limit.exceeded = l.i < l.b.len();
|
||||
break;
|
||||
}
|
||||
let c = match l.command() {
|
||||
Some(c) => c,
|
||||
None => match cmd {
|
||||
// Implicit repeat (a moveto repeats as lineto). Z takes no numbers, so a number
|
||||
// after it is an error: repeating Z would loop forever without consuming input.
|
||||
Some(c) if l.at_number() && !c.eq_ignore_ascii_case(&b'z') => match c {
|
||||
b'M' => b'L',
|
||||
b'm' => b'l',
|
||||
other => other,
|
||||
},
|
||||
_ => break,
|
||||
},
|
||||
};
|
||||
let rel = c.is_ascii_lowercase();
|
||||
let base = if rel { state.current.to_vec2() } else { Vec2::ZERO };
|
||||
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
|
||||
let ok = (|| -> Option<()> {
|
||||
match c.to_ascii_uppercase() {
|
||||
b'M' => {
|
||||
state.current = pt(&mut l)?;
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.start = state.current;
|
||||
state.open = true;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'Z' => {
|
||||
if state.open && !push_element(&mut p, PathEl::ClosePath, &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = state.start;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
_ if !state.open => {
|
||||
// A segment without a preceding moveto starts at the current point.
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) {
|
||||
return None;
|
||||
}
|
||||
state.open = true;
|
||||
return segment(&mut l, c, base, &mut p, &mut state, &mut limit);
|
||||
}
|
||||
_ => return segment(&mut l, c, base, &mut p, &mut state, &mut limit),
|
||||
}
|
||||
Some(())
|
||||
})();
|
||||
if ok.is_none() {
|
||||
break;
|
||||
}
|
||||
if limit.exceeded {
|
||||
break;
|
||||
}
|
||||
cmd = Some(c);
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
// After Z a new segment starts from the subpath start (an unused move is dropped
|
||||
// below).
|
||||
if !push_element(&mut p, PathEl::MoveTo(state.start), &mut limit) {
|
||||
break;
|
||||
}
|
||||
state.open = true;
|
||||
}
|
||||
}
|
||||
(strip_trailing_moves(p), limit.exceeded)
|
||||
}
|
||||
|
||||
/// Push an element if finite and under the cap; otherwise mark the limit exceeded and return false.
|
||||
fn push_element(p: &mut BezPath, element: PathEl, limit: &mut PathLimit) -> bool {
|
||||
let finite = match element {
|
||||
PathEl::MoveTo(point) | PathEl::LineTo(point) => point.x.is_finite() && point.y.is_finite(),
|
||||
PathEl::QuadTo(control, point) => [control.x, control.y, point.x, point.y].iter().all(|value| value.is_finite()),
|
||||
PathEl::CurveTo(first, second, point) => [first.x, first.y, second.x, second.y, point.x, point.y].iter().all(|value| value.is_finite()),
|
||||
PathEl::ClosePath => true,
|
||||
};
|
||||
if p.elements().len() >= limit.max_elements || !finite {
|
||||
limit.exceeded = true;
|
||||
return false;
|
||||
}
|
||||
p.push(element);
|
||||
true
|
||||
}
|
||||
|
||||
/// Parse one path command's arguments into `p`, returning `None` on malformed or over-limit input.
|
||||
fn segment(l: &mut Lex, c: u8, base: Vec2, p: &mut BezPath, state: &mut PathState, limit: &mut PathLimit) -> Option<()> {
|
||||
let num = |l: &mut Lex| l.number();
|
||||
let pt = |l: &mut Lex| -> Option<Point> { Some(Point::new(l.number()?, l.number()?) + base) };
|
||||
match c.to_ascii_uppercase() {
|
||||
b'L' => {
|
||||
let current = pt(l)?;
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'H' => {
|
||||
let x = num(l)? + base.x;
|
||||
let current = Point::new(x, state.current.y);
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'V' => {
|
||||
let y = num(l)? + base.y;
|
||||
let current = Point::new(state.current.x, y);
|
||||
if !push_element(p, PathEl::LineTo(current), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = current;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, e) = (pt(l)?, pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_cubic = Some(c2);
|
||||
state.last_quad = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = state.last_cubic.map_or(state.current, |c| state.current + (state.current - c));
|
||||
let (c2, e) = (pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_cubic = Some(c2);
|
||||
state.last_quad = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, e) = (pt(l)?, pt(l)?);
|
||||
if !push_element(p, PathEl::QuadTo(q, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_quad = Some(q);
|
||||
state.last_cubic = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'T' => {
|
||||
let q = state.last_quad.map_or(state.current, |c| state.current + (state.current - c));
|
||||
let e = pt(l)?;
|
||||
if !push_element(p, PathEl::QuadTo(q, e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.last_quad = Some(q);
|
||||
state.last_cubic = None;
|
||||
state.current = e;
|
||||
}
|
||||
b'A' => {
|
||||
let rx = num(l)?.abs();
|
||||
let ry = num(l)?.abs();
|
||||
let rot = num(l)?;
|
||||
let large = l.flag()?;
|
||||
let sweep = l.flag()?;
|
||||
let e = pt(l)?;
|
||||
let arc = SvgArc { from: state.current, to: e, radii: Vec2::new(rx, ry), x_rotation: rot.to_radians(), large_arc: large, sweep };
|
||||
let mut last_end = None;
|
||||
if let Some(a) = kurbo::Arc::from_svg_arc(&arc) {
|
||||
// Scale tolerance with the radius so the segment count stays bounded.
|
||||
let tol = 0.1_f64.max(a.radii.x.max(a.radii.y) * 1e-4);
|
||||
a.to_cubic_beziers(tol, |c1, c2, end| {
|
||||
if limit.exceeded {
|
||||
return;
|
||||
}
|
||||
if push_element(p, PathEl::CurveTo(c1, c2, end), limit) {
|
||||
last_end = Some(end);
|
||||
}
|
||||
});
|
||||
}
|
||||
if limit.exceeded {
|
||||
return None;
|
||||
}
|
||||
// Degenerate arcs (e.g. huge radii) may emit nothing or stop short of the end point.
|
||||
if last_end.is_none_or(|q| (q - e).hypot() > 1e-3 * (1.0 + e.to_vec2().hypot())) && !push_element(p, PathEl::LineTo(e), limit) {
|
||||
return None;
|
||||
}
|
||||
state.current = e;
|
||||
state.last_cubic = None;
|
||||
state.last_quad = None;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Drop move-tos that start no segment (from closepath bookkeeping).
|
||||
fn strip_trailing_moves(p: BezPath) -> BezPath {
|
||||
use kurbo::PathEl;
|
||||
let els = p.elements();
|
||||
let mut out = BezPath::new();
|
||||
for (i, e) in els.iter().enumerate() {
|
||||
if let PathEl::MoveTo(_) = e {
|
||||
let next_is_seg = els.get(i + 1).is_some_and(|n| !matches!(n, PathEl::MoveTo(_)));
|
||||
if !next_is_seg {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(*e);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::PathEl;
|
||||
|
||||
#[test]
|
||||
/// Huge arc radii stay bounded.
|
||||
fn huge_arc_radius_stays_bounded() {
|
||||
let p = parse_path_data("M0 0A1e36 1e36 0 1 1 1e30 0");
|
||||
assert!(p.elements().len() < 1000, "got {} elements", p.elements().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands() {
|
||||
let p = parse_path_data("M10,10 L20,10 h10 v10 H10 z m5 5 l1-1.5.5.5e1 C 0 0 1 1 2 2 s3 3 4 4 Q1 1 2 2 t3 3 A5 5 0 0 1 20 20 a5 5 0 1010 0");
|
||||
let els = p.elements();
|
||||
assert_eq!(els[0], PathEl::MoveTo(Point::new(10.0, 10.0)));
|
||||
assert_eq!(els[2], PathEl::LineTo(Point::new(30.0, 10.0)));
|
||||
assert_eq!(els[3], PathEl::LineTo(Point::new(30.0, 20.0)));
|
||||
assert!(els.iter().any(|e| matches!(e, PathEl::ClosePath)));
|
||||
// Relative move after Z is relative to the subpath start (10,10).
|
||||
assert!(els.contains(&PathEl::MoveTo(Point::new(15.0, 15.0))));
|
||||
// "l1-1.5.5.5e1": two implicit linetos (1,-1.5) then (.5,5).
|
||||
assert!(els.contains(&PathEl::LineTo(Point::new(16.0, 13.5))));
|
||||
assert!(els.contains(&PathEl::LineTo(Point::new(16.5, 18.5))));
|
||||
assert!(els.iter().filter(|e| matches!(e, PathEl::CurveTo(..))).count() >= 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_keep_prefix() {
|
||||
let p = parse_path_data("M0 0 L10 0 L10 x10 L0 10");
|
||||
assert_eq!(p.elements().len(), 2);
|
||||
assert!(parse_path_data("garbage").elements().is_empty());
|
||||
assert!(parse_path_data("").elements().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_after_close_stops_instead_of_looping() {
|
||||
// "Z9": Z was repeated implicitly without consuming the number, appending close-paths
|
||||
// until memory ran out.
|
||||
let p = parse_path_data("M0 0 L10 0 L10 10 Z9 C1 2 3 4 5 6");
|
||||
assert_eq!(p.elements().len(), 4);
|
||||
assert!(parse_path_data("M0 0 L10 0 z 9 9").elements().len() <= 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Huge-radius arcs still reach their end point.
|
||||
fn huge_radius_arc_still_reaches_end_point() {
|
||||
for d in ["M0 0 A1e20 1e20 0 0 1 10 0 L10 10", "M0 0 A1e20 1e20 0 1 1 10 0 L10 10", "M0 0 a1e20 1e20 0 0 1 10 0 L10 10"] {
|
||||
let p = parse_path_data(d);
|
||||
let reaches = p.elements().iter().any(|e| match e {
|
||||
PathEl::LineTo(q) | PathEl::CurveTo(_, _, q) => (q.x - 10.0).abs() < 1e-6 && q.y.abs() < 1e-6,
|
||||
_ => false,
|
||||
});
|
||||
assert!(reaches, "{d}: {:?}", p.elements());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_lists() {
|
||||
assert_eq!(numbers_bounded("0 0,100 50", 8).0, vec![0.0, 0.0, 100.0, 50.0]);
|
||||
assert_eq!(numbers_bounded("-1-2.5.5", 8).0, vec![-1.0, -2.5, 0.5]);
|
||||
assert_eq!(numbers_bounded("1e2,2E-1", 8).0, vec![100.0, 0.2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// The element cap stops expansion and reports truncation.
|
||||
fn path_element_limit_stops_expansion_and_reports_truncation() {
|
||||
let data = format!("M0 0{}", "h1".repeat(MAX_PATH_ELEMENTS + 1));
|
||||
let (path, exceeded) = parse_path_data_bounded(&data, 32);
|
||||
assert!(exceeded);
|
||||
assert!(path.elements().len() <= 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// The number list cap stops retaining values.
|
||||
fn number_list_limit_stops_retaining_values() {
|
||||
let (values, exceeded) = numbers_bounded("1 2 3 4", 3);
|
||||
assert_eq!(values, [1.0, 2.0, 3.0]);
|
||||
assert!(exceeded);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_boundary_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn huge_caller_budgets_remain_bounded() {
|
||||
let (path, limited) = parse_path_data_bounded(&format!("M0 0{}", "h1".repeat(MAX_PATH_ELEMENTS)), usize::MAX);
|
||||
assert!(limited);
|
||||
assert!(path.elements().len() <= MAX_PATH_ELEMENTS);
|
||||
let (values, limited) = numbers_bounded(&"1 ".repeat(MAX_NUMBER_VALUES + 1), usize::MAX);
|
||||
assert!(limited);
|
||||
assert_eq!(values.len(), MAX_NUMBER_VALUES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefix_and_non_finite_flags_stay_distinct() {
|
||||
let (path, limited) = parse_path_data_bounded("M0 0 L1 1 Lx", 20);
|
||||
assert!(!limited);
|
||||
assert_eq!(path.elements().len(), 2);
|
||||
let (path, limited) = parse_path_data_bounded("M1e308 0 l1e308 0", 20);
|
||||
assert!(limited);
|
||||
assert!(path.elements().is_empty());
|
||||
assert!(parse_path_data_bounded("M0 0", 0).1);
|
||||
assert!(!parse_path_data_bounded("", 0).1);
|
||||
}
|
||||
}
|
||||
@@ -725,6 +725,37 @@ impl Document {
|
||||
max.saturating_add(1).max(1)
|
||||
}
|
||||
|
||||
/// The stacking orders ([`para::Float::z`]) the floating objects of every story have, and how
|
||||
/// many floating objects have none (objects made in the app). Every story saved with the document
|
||||
/// counts: the body, the parts, the note separators and the glossary's building blocks (saved
|
||||
/// with the same numbering, so none of their orders is left out when it is renumbered).
|
||||
pub fn stacking_orders(&self) -> (std::collections::BTreeSet<u32>, usize) {
|
||||
let (mut orders, mut unset) = (std::collections::BTreeSet::new(), 0usize);
|
||||
let separators = [&self.footnote_separators, &self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
|
||||
.flatten();
|
||||
let stories = std::iter::once(&self.body)
|
||||
.chain(self.parts.values().map(|p| &p.blocks))
|
||||
.chain(separators)
|
||||
.chain(self.glossary.iter().map(|g| &g.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks {
|
||||
crate::walk::each_para(b, 0, &mut |p| {
|
||||
for (_, _, f) in p.objects.iter().filter_map(InlineObject::frame).filter(|(_, _, f)| f.wrap != para::Wrap::Inline) {
|
||||
match f.z {
|
||||
0 => unset = unset.saturating_add(1),
|
||||
z => {
|
||||
orders.insert(z);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
(orders, unset)
|
||||
}
|
||||
|
||||
/// Change every inline object in every story (paragraphs inside tables too), copying only
|
||||
/// the blocks whose paragraphs `wants` says have objects to change.
|
||||
pub fn objects_mut(&mut self, wants: &dyn Fn(&InlineObject) -> bool, f: &mut dyn FnMut(&mut InlineObject)) {
|
||||
|
||||
@@ -13,11 +13,13 @@ use crate::props::{CharProps, ParaProps};
|
||||
use crate::section::SectionProps;
|
||||
use crate::{DocError, Result};
|
||||
|
||||
mod file_orders;
|
||||
mod float;
|
||||
mod inline_kinds;
|
||||
mod inline_object;
|
||||
mod run;
|
||||
|
||||
pub use file_orders::{FileOrderScan, FileOrders};
|
||||
pub use float::{AltText, Anchor, Float, FloatAlign, MAX_ALT_TEXT, Wrap, WrapText, cap_alt};
|
||||
pub use inline_kinds::{NoteKind, PTabAlign, PTabBase, RubyAlign, ShapeKind, ruby_offset, ruby_raise};
|
||||
pub use inline_object::{CanvasStyle, GroupChild, InlineObject, MAX_GROUP_CHILDREN};
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Bounded conversion of unsigned file stacking orders to Float's zero-is-unset model.
|
||||
|
||||
/// A file-order mapping. Ordinary files retain their exact one-more encoding.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct FileOrders {
|
||||
gap: Option<u32>,
|
||||
}
|
||||
|
||||
impl FileOrders {
|
||||
/// A file order adjusted to leave room for its one-more model representation.
|
||||
pub fn file_order(self, raw: u32) -> u32 {
|
||||
raw - u32::from(self.gap.is_some_and(|gap| raw > gap))
|
||||
}
|
||||
|
||||
/// An absent order remains unset; a present file order remains present.
|
||||
pub fn model_order(self, raw: Option<u32>) -> u32 {
|
||||
raw.map_or(0, |raw| self.file_order(raw).saturating_add(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect every raw order before decoding any. No document or callback is replayed.
|
||||
///
|
||||
/// The upper window has more slots than the source can contain distinct ten-digit
|
||||
/// orders. Only this window can be shifted. XML callers must count all source bytes,
|
||||
/// decode attributes exactly as their reader does, and never expand custom entities.
|
||||
pub struct FileOrderScan {
|
||||
seen: Vec<u8>,
|
||||
slots: usize,
|
||||
}
|
||||
|
||||
impl FileOrderScan {
|
||||
/// Most source bytes scanned. This also caps the bitmap below 26 MiB.
|
||||
pub const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
|
||||
|
||||
/// Allocate fallibly; reject an unbounded source rather than truncating the scan.
|
||||
pub fn new(source_bytes: u64) -> Result<Self, String> {
|
||||
if source_bytes > Self::MAX_SOURCE_BYTES {
|
||||
return Err("stacking-order source exceeds 2 GiB".into());
|
||||
}
|
||||
let slots = (source_bytes / 10 + 1) as usize;
|
||||
let size = slots.div_ceil(8);
|
||||
let mut seen = Vec::new();
|
||||
seen.try_reserve_exact(size).map_err(|_| "stacking-order bitmap allocation failed")?;
|
||||
seen.resize(size, 0);
|
||||
Ok(Self { seen, slots })
|
||||
}
|
||||
|
||||
/// Observe a decoded unsigned order. Repeated values cost no extra memory.
|
||||
pub fn observe(&mut self, raw: u32) {
|
||||
let distance = (u32::MAX - raw) as usize;
|
||||
if distance < self.slots
|
||||
&& let Some(byte) = self.seen.get_mut(distance / 8)
|
||||
{
|
||||
*byte |= 1 << (distance % 8);
|
||||
}
|
||||
}
|
||||
|
||||
/// Finish after the complete source traversal, before constructing model floats.
|
||||
pub fn finish(self) -> Result<FileOrders, String> {
|
||||
if self.seen.first().is_none_or(|b| b & 1 == 0) {
|
||||
return Ok(FileOrders::default());
|
||||
}
|
||||
for (i, byte) in self.seen.into_iter().enumerate() {
|
||||
if byte == u8::MAX {
|
||||
continue;
|
||||
}
|
||||
let distance = i * 8 + (!byte).trailing_zeros() as usize;
|
||||
if distance < self.slots {
|
||||
return Ok(FileOrders { gap: Some(u32::MAX - distance as u32) });
|
||||
}
|
||||
}
|
||||
Err("stacking-order scan did not cover its source".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn upper_tail_is_injective_and_leaves_ordinary_orders_alone() {
|
||||
let raw = [0, 1, 251658240, u32::MAX - 2, u32::MAX - 1, u32::MAX, u32::MAX];
|
||||
let mut scan = FileOrderScan::new(raw.len() as u64 * 10).unwrap();
|
||||
for raw in raw {
|
||||
scan.observe(raw);
|
||||
}
|
||||
let map = scan.finish().unwrap();
|
||||
assert_eq!(raw.map(|raw| map.model_order(Some(raw))), [1, 2, 251658241, u32::MAX - 2, u32::MAX - 1, u32::MAX, u32::MAX]);
|
||||
assert_eq!(map.model_order(None), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_max_means_no_renumbering_and_source_limits_fail_closed() {
|
||||
let mut scan = FileOrderScan::new(100).unwrap();
|
||||
scan.observe(u32::MAX - 1);
|
||||
assert_eq!(scan.finish().unwrap().model_order(Some(u32::MAX - 1)), u32::MAX);
|
||||
assert!(FileOrderScan::new(FileOrderScan::MAX_SOURCE_BYTES + 1).is_err());
|
||||
let mut incomplete = FileOrderScan::new(0).unwrap();
|
||||
incomplete.observe(u32::MAX);
|
||||
assert!(incomplete.finish().is_err());
|
||||
}
|
||||
}
|
||||
@@ -182,8 +182,11 @@ pub struct Float {
|
||||
/// off, any VML shape in a header or footer): a picture watermark in a header that starts with a table.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub outside_cell: bool,
|
||||
/// Stacking order among floating objects (`wp:anchor/@relativeHeight`): higher is drawn on
|
||||
/// top. 0 = unknown, drawn in document order (objects inserted here, or from other formats).
|
||||
/// Stacking order among the floating objects of its layer, one more than the file's
|
||||
/// (`wp:anchor/@relativeHeight`, ODF's `draw:z-index`), so a file's lowest, 0, is 1: a higher
|
||||
/// one is drawn over a lower one, whatever their order in the text, as Word does. 0 = none
|
||||
/// (objects inserted by the app, or from other formats): stacks above every object that has
|
||||
/// one, in text order.
|
||||
#[serde(skip_serializing_if = "is_zero_u32")]
|
||||
pub z: u32,
|
||||
/// The page a drawing anchored to a page is on, from 1 (ODF's `text:anchor-page-number`,
|
||||
@@ -242,6 +245,12 @@ fn is_zero_u32(v: &u32) -> bool {
|
||||
}
|
||||
|
||||
impl Float {
|
||||
/// Where it stacks among the floating objects of its layer: see [`Float::z`]. None (0) is
|
||||
/// past every stored order, `u32::MAX` included.
|
||||
pub fn stack(&self) -> u64 {
|
||||
if self.z > 0 { u64::from(self.z) } else { u64::from(u32::MAX) + 1 }
|
||||
}
|
||||
|
||||
/// The rotation and flips, the angle normalised to `0..360` (a NaN angle is no rotation).
|
||||
pub fn spin(&self) -> crate::geom::Spin {
|
||||
crate::geom::Spin::new(self.rot, self.flip_h, self.flip_v)
|
||||
|
||||
@@ -1010,7 +1010,7 @@ const NAMES_XML: &str = r#"<workbook xmlns="http://schemas.openxmlformats.org/sp
|
||||
fn xml_names(xml: &str) -> Vec<craft_xlsx::DefinedName> {
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>"#;
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#;
|
||||
let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", xml.as_bytes())]);
|
||||
let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", xml.as_bytes())]).unwrap();
|
||||
Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names
|
||||
}
|
||||
|
||||
@@ -1146,7 +1146,8 @@ fn xml_sheet(xml: &str) -> (Vec<Row>, SheetPart) {
|
||||
("xl/workbook.xml", book.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
|
||||
("xl/sheet.xml", xml.as_bytes()),
|
||||
]);
|
||||
])
|
||||
.unwrap();
|
||||
let (rows, part, _) = sizes_of(&bytes).unwrap();
|
||||
(rows, part)
|
||||
}
|
||||
@@ -1256,6 +1257,7 @@ fn styled_file(styles: &[u8], types: &str) -> Vec<u8> {
|
||||
("data/two.bin", &worksheet(&[], &[])),
|
||||
("look/styles.bin", styles),
|
||||
])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The styles part of a package, and the warnings reading it gave.
|
||||
@@ -1440,7 +1442,8 @@ fn xml_styles(xml: &str) -> Styles {
|
||||
("xl/workbook.xml", br#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>"#),
|
||||
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
|
||||
("xl/styles.xml", xml.as_bytes()),
|
||||
]);
|
||||
])
|
||||
.unwrap();
|
||||
styles_of(&bytes).0.unwrap()
|
||||
}
|
||||
|
||||
@@ -1793,7 +1796,7 @@ fn book_with_tables(data: &[u8], tables: &[Vec<u8>]) -> Vec<u8> {
|
||||
("text/strings.bin", &strings),
|
||||
];
|
||||
entries.extend(names.iter().map(String::as_str).zip(tables.iter().map(Vec::as_slice)));
|
||||
zip(&entries)
|
||||
zip(&entries).unwrap()
|
||||
}
|
||||
|
||||
/// Sheet one's tables through `Package`, and its warnings.
|
||||
@@ -1834,7 +1837,8 @@ fn a_name_using_a_structured_reference_is_decoded_after_tables_are_indexed() {
|
||||
("data/two.bin", two.as_slice()),
|
||||
("text/strings.bin", strings.as_slice()),
|
||||
("tables/t1.bin", table.as_slice()),
|
||||
]);
|
||||
])
|
||||
.unwrap();
|
||||
let names = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names;
|
||||
assert_eq!(names.iter().find(|n| n.name == "Vals").map(|n| n.formula.as_str()), Some("Sales[Val]"));
|
||||
let wb = read(&bytes).unwrap();
|
||||
|
||||
@@ -90,6 +90,10 @@ mod tests {
|
||||
fn set_permissions(&self, file: &File, perms: Permissions) -> io::Result<()> {
|
||||
RealFs.set_permissions(file, perms)
|
||||
}
|
||||
#[cfg(unix)]
|
||||
fn set_group(&self, file: &File, gid: u32) -> io::Result<()> {
|
||||
RealFs.set_group(file, gid)
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(v: &Value) -> Vec<&str> {
|
||||
|
||||
Reference in new issue
Block a user