From e1d2f32e588c7343c1fe205dba455dc2a0460b3b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 22:42:25 -0500 Subject: [PATCH] export, xfdf: cut over portable HTML writer and XFDF/FDF grammar to craft-libs (#778) (#7914) * export, xfdf: cut over portable HTML writer and XFDF/FDF grammar to craft-libs (#778) * fix(xfdf): align craft-xml rev with craft-xfdf and deref standalone El * fix(xfdf): remove redundant deref on standalone(el, ns) * xfdf, export: update craft-libs pin and add XFDF annotation round-trip test * chore: align craft-xml rev with craft-xfdf * chore: repin craft-xml to craft-libs main * chore: repin craft-xml, craft-xfdf, craft-html to craft-libs main * test(xfdf): pass &str to import_comments in round-trip test * test(xfdf): bind dst.get(dst_ref) before as_dict * test(fonts): import pdfcraft_cos::Stream in embedding tests * test(xfdf): update newly added square annotation instead of widget[0] * test(xfdf): read newly imported annotation at Annots.last() in roundtrip test --- Cargo.lock | 87 ++++++--- Cargo.toml | 2 +- crates/export/Cargo.toml | 1 + crates/export/src/as_html.rs | 4 +- crates/export/src/html.rs | 145 -------------- crates/export/src/lib.rs | 7 +- crates/xfdf/Cargo.toml | 2 +- crates/xfdf/src/fdf.rs | 2 +- crates/xfdf/src/grammar.rs | 355 ----------------------------------- crates/xfdf/src/lib.rs | 5 +- crates/xfdf/src/tests.rs | 44 +++++ crates/xfdf/src/xfdf.rs | 4 +- 12 files changed, 114 insertions(+), 544 deletions(-) delete mode 100644 crates/export/src/html.rs delete mode 100644 crates/xfdf/src/grammar.rs diff --git a/Cargo.lock b/Cargo.lock index 69e74d98e2..e954ea5bf1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -966,6 +966,17 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chardetng" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53" +dependencies = [ + "cfg-if", + "encoding_rs", + "memchr", +] + [[package]] name = "chrono" version = "0.4.45" @@ -1213,6 +1224,11 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0" + [[package]] name = "craft-codepage" version = "0.1.0" @@ -1298,6 +1314,14 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +[[package]] +name = "craft-html" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0" +dependencies = [ + "craft-mime 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", +] + [[package]] name = "craft-html" version = "0.1.0" @@ -1380,7 +1404,7 @@ version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33#fbb3f47f7ae712192586984af11ca8f6c0f64d33" dependencies = [ "craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", - "craft-html", + "craft-html 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fbb3f47f7ae712192586984af11ca8f6c0f64d33)", ] @@ -1434,13 +1458,24 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0" +dependencies = [ + "chardetng", + "chrono", + "craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", + "encoding_rs", +] + [[package]] name = "craft-mime" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" dependencies = [ "chrono", - "craft-codepage", + "craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "encoding_rs", ] @@ -1588,7 +1623,7 @@ name = "craft-rtf" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3#b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" dependencies = [ - "craft-codepage", + "craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "craft-flow 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "craft-metafile", "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", @@ -1731,9 +1766,9 @@ dependencies = [ [[package]] name = "craft-xfdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72#e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72" +source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "thiserror 2.0.21", ] @@ -1747,6 +1782,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0#1546550b0d4b79b8156a1fefaac8b3b317a4aee0" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1767,25 +1812,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" -dependencies = [ - "quick-xml 0.41.0", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72#e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "craft-xml" version = "0.1.0" @@ -5059,12 +5085,13 @@ name = "pdfcraft-export" version = "0.21.1" dependencies = [ "craft-docx", + "craft-html 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "craft-markdown", - "craft-mime", + "craft-mime 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", "craft-pptx", "craft-rtf", "craft-wordmodel 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "flate2", "image", @@ -5217,7 +5244,7 @@ name = "pdfcraft-preflight" version = "0.21.1" dependencies = [ "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8503f24cb845268f47f97e829491114fe9ad1bfa)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "flate2", "pdfcraft-content", "pdfcraft-cos", @@ -5245,7 +5272,7 @@ name = "pdfcraft-redact" version = "0.21.1" dependencies = [ "aho-corasick", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "pdfcraft-annot", "pdfcraft-content", "pdfcraft-cos", @@ -5414,7 +5441,7 @@ dependencies = [ "base64 0.23.1", "craft-image-codecs", "craft-xfa", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "pdfcraft-cos", "pdfcraft-fonts", "sha2 0.11.1", @@ -5428,7 +5455,7 @@ dependencies = [ "base64 0.23.1", "craft-csv", "craft-xfdf", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1546550b0d4b79b8156a1fefaac8b3b317a4aee0)", "pdfcraft-annot", "pdfcraft-cos", "pdfcraft-forms", diff --git a/Cargo.toml b/Cargo.toml index fc6231cd16..38351973b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,7 +42,7 @@ craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0" # Shared Base64 encoder; use the existing RTF revision to reuse its codepage dependency. craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "b8eaa8e2f3561f9fa27fcf3b7f67ce915e93caa3" } craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } -craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } +craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "1546550b0d4b79b8156a1fefaac8b3b317a4aee0" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e2dc681a3" } diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index ade5308749..0aabc61702 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -16,6 +16,7 @@ craft-mime.workspace = true craft-rtf = { workspace = true, features = ["doc"] } craft-wordmodel.workspace = true craft-docx.workspace = true +craft-html = { git = "https://github.com/storytold/craft-libs", rev = "1546550b0d4b79b8156a1fefaac8b3b317a4aee0", version = "0.1.0", features = ["standalone"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } craft-pptx.workspace = true craft-xml.workspace = true diff --git a/crates/export/src/as_html.rs b/crates/export/src/as_html.rs index 3610309a26..4f13758681 100644 --- a/crates/export/src/as_html.rs +++ b/crates/export/src/as_html.rs @@ -1,10 +1,10 @@ use super::as_docx::{rgb8, room_for}; -use super::html::{self, HtmlBlock, HtmlCell, HtmlRun, HtmlTable}; use super::layout::{Image, Item, Page, items}; #[cfg(test)] use super::layout::{Run, Table}; +use craft_html::standalone::{self as html, HtmlBlock, HtmlCell, HtmlRun, HtmlTable}; -pub(crate) use super::html::allowed; +pub(crate) use craft_html::standalone::allowed; /// The longest language tag the exports write. BCP 47 sets no maximum (35 characters is only /// the least a protocol must hold), so this bounds only what a PDF's `/Lang` can put in a file. diff --git a/crates/export/src/html.rs b/crates/export/src/html.rs deleted file mode 100644 index e1d88c3796..0000000000 --- a/crates/export/src/html.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Portable standalone HTML document writer (no PDF layout, reading order, or export policy). - -pub(crate) use craft_mime::transfer::base64; - -/// Whether a character may appear in the output. XML 1.0 forbids the C0 controls other than tab, -/// line feed and carriage return, and U+FFFE/U+FFFF. -pub(crate) fn allowed(c: char) -> bool { - matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}') -} - -pub(crate) fn esc(s: &str) -> String { - let mut o = String::with_capacity(s.len()); - for c in s.chars().filter(|c| allowed(*c)) { - match c { - '&' => o.push_str("&"), - '<' => o.push_str("<"), - '>' => o.push_str(">"), - '"' => o.push_str("""), - c => o.push(c), - } - } - o -} - -/// An inline run of text for portable HTML rendering. -pub(crate) struct HtmlRun<'a> { - pub text: &'a str, - pub bold: bool, - pub italic: bool, - pub color: [u8; 3], -} - -/// A single table cell for portable HTML rendering. -pub(crate) struct HtmlCell<'a> { - pub text: &'a str, - pub bold: bool, - pub italic: bool, - pub color: [u8; 3], - pub span: usize, -} - -/// A table of rows of cells for portable HTML rendering. -pub(crate) struct HtmlTable<'a> { - pub rows: Vec>>, -} - -/// A block-level element in a portable HTML document. -pub(crate) enum HtmlBlock<'a> { - Para { runs: Vec>, level: u8 }, - Table(HtmlTable<'a>), - Image { mime: &'a str, bytes: &'a [u8] }, - PageBreak, -} - -fn rgb_hex(rgb: [u8; 3]) -> Option { - let [r, g, b] = rgb; - (r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}")) -} - -fn style_color(rgb: [u8; 3], simple: bool) -> String { - if simple { String::new() } else { rgb_hex(rgb).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) } -} - -pub(crate) fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String { - if text.trim().is_empty() { - return text; - } - if italic { - text = format!("{text}"); - } - if bold { - text = format!("{text}"); - } - text -} - -pub(crate) fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option { - let non_empty: Vec<_> = runs.iter().map(|r| (r, esc(r.text))).filter(|(_, text)| !text.is_empty()).collect(); - let &(first, _) = non_empty.iter().find(|(_, text)| !text.trim().is_empty())?; - let mut t = String::new(); - for (run, text) in non_empty { - if text.trim().is_empty() { - t.push_str(&text); - continue; - } - let mut out = wrap_inline(text, run.bold && lvl == 0, run.italic); - // The paragraph has its first visible run's colour; a run in another colour says so. - if !simple && run.color != first.color { - let [red, green, blue] = run.color; - out = format!("{out}"); - } - t.push_str(&out); - } - let style = style_color(first.color, simple); - Some(match lvl.min(6) { - 0 => format!("{t}

\n"), - l => format!("{t}\n"), - }) -} - -pub(crate) fn render_table(t: &HtmlTable<'_>, simple: bool) -> String { - let mut s = String::from("\n"); - for row in &t.rows { - s.push_str(""); - for c in row { - let body = wrap_inline(esc(c.text), c.bold, c.italic); - let span = if c.span > 1 { format!(" colspan=\"{}\"", c.span) } else { String::new() }; - let style = style_color(c.color, simple); - s.push_str(&format!("{body}")); - } - s.push_str("\n"); - } - s.push_str("
\n"); - s -} - -/// Render a sequence of portable HTML blocks into a standalone HTML5 document. -pub(crate) fn render(blocks: &[HtmlBlock<'_>], title: &str, simple: bool, language: Option<&str>) -> String { - let lang = language.map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default(); - let mut s = format!( - "\n\n\n\n{}\n{}\n\n\n", - esc(title), - if simple { - "" - } else { - "" - } - ); - for block in blocks { - match block { - HtmlBlock::Para { runs, level } => { - if let Some(p) = render_para(runs, *level, simple) { - s.push_str(&p); - } - } - HtmlBlock::Table(t) => s.push_str(&render_table(t, simple)), - HtmlBlock::Image { mime, bytes } => { - s.push_str(&format!("

\"\"

\n", base64(bytes))); - } - HtmlBlock::PageBreak => s.push_str("
\n"), - } - } - s.push_str("\n\n"); - s -} diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 3310f249d3..b7598518da 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -23,7 +23,6 @@ mod as_rtf; mod as_word; mod clip; mod flow; -mod html; mod layout; #[cfg(test)] @@ -36,11 +35,11 @@ pub use as_markdown::markdown; use as_markdown::{emphasis, paragraph}; pub use as_rtf::{rtf, rtf_with_title, rtf_with_title_checked}; pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family}; +pub(crate) use craft_html::standalone::esc; +#[cfg(test)] +use craft_html::standalone::{allowed, base64}; #[cfg(test)] use flow::list_item; -pub(crate) use html::esc; -#[cfg(test)] -use html::{allowed, base64}; pub use layout::{Block, Cell, Image, Page, Table}; #[cfg(test)] use layout::{LOOKUP_STEPS, MAX_COLS, body_size}; diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml index 826c1835e7..b8c418fa46 100644 --- a/crates/xfdf/Cargo.toml +++ b/crates/xfdf/Cargo.toml @@ -9,7 +9,7 @@ license.workspace = true workspace = true [dependencies] -craft-xfdf = { git = "https://github.com/storytold/craft-libs", rev = "e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72", version = "0.1.0" } +craft-xfdf = { git = "https://github.com/storytold/craft-libs", rev = "1546550b0d4b79b8156a1fefaac8b3b317a4aee0", version = "0.1.0" } pdfcraft-cos = { workspace = true } pdfcraft-annot = { workspace = true } pdfcraft-forms = { workspace = true } diff --git a/crates/xfdf/src/fdf.rs b/crates/xfdf/src/fdf.rs index 95e3b55c81..9a5a55707b 100644 --- a/crates/xfdf/src/fdf.rs +++ b/crates/xfdf/src/fdf.rs @@ -1,7 +1,7 @@ use super::common::{MAX_DEPTH, rect_strict, text_of}; -use super::grammar::fdf_annot_skip_key; use super::xfdf::{add_popup, apply_values, find_by_name, place}; use super::*; +use craft_xfdf::grammar::fdf_annot_skip_key; fn pdf_string(s: &str) -> Vec { let mut v = Vec::new(); diff --git a/crates/xfdf/src/grammar.rs b/crates/xfdf/src/grammar.rs deleted file mode 100644 index 867cd8c535..0000000000 --- a/crates/xfdf/src/grammar.rs +++ /dev/null @@ -1,355 +0,0 @@ -//! Portable XFDF annotation and FDF grammar (no PDF COS document or annotation models). - -use std::fmt::Write as _; - -use super::common::{check_form_xml_depth, csv, el_text, esc, hex, n, parse_form_xml, xml_nesting_depth}; - -/// XFDF's own namespace (ISO 19444-1). -pub(crate) const XFDF_NS: &str = "http://ns.adobe.com/xfdf/"; - -/// Rich text deeper than this is written as text rather than as markup, so the XFDF it goes into -/// stays well inside the nesting the reader accepts (`MAX_XML_DEPTH`). -const MAX_RICH_DEPTH: usize = 512; - -pub(crate) const SUBTYPES: [(&str, &str); 17] = [ - ("Text", "text"), - ("FreeText", "freetext"), - ("Line", "line"), - ("Square", "square"), - ("Circle", "circle"), - ("Polygon", "polygon"), - ("PolyLine", "polyline"), - ("Highlight", "highlight"), - ("Underline", "underline"), - ("Squiggly", "squiggly"), - ("StrikeOut", "strikeout"), - ("Stamp", "stamp"), - ("Caret", "caret"), - ("Ink", "ink"), - ("FileAttachment", "fileattachment"), - ("Sound", "sound"), - ("Redact", "redact"), -]; - -pub(crate) const FLAGS: [(i64, &str); 9] = [ - (1, "invisible"), - (2, "hidden"), - (4, "print"), - (8, "nozoom"), - (16, "norotate"), - (32, "noview"), - (64, "readonly"), - (128, "locked"), - (256, "togglenoview"), -]; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum BorderStyle { - Solid, - Dash, - Bevelled, - Inset, - Underline, -} - -impl BorderStyle { - pub(crate) fn as_pdf_name(self) -> &'static str { - match self { - Self::Solid => "S", - Self::Dash => "D", - Self::Bevelled => "B", - Self::Inset => "I", - Self::Underline => "U", - } - } - - fn as_xfdf_attr(self) -> Option<&'static str> { - match self { - Self::Dash => Some("dash"), - Self::Bevelled => Some("bevelled"), - Self::Inset => Some("inset"), - Self::Underline => Some("underline"), - Self::Solid => None, - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum CaretSymbol { - Paragraph, - None, -} - -impl CaretSymbol { - pub(crate) fn as_pdf_name(self) -> &'static str { - match self { - Self::Paragraph => "P", - Self::None => "None", - } - } -} - -/// Portable XFDF 3.0 annotation formatting attributes. -#[derive(Default)] -pub(crate) struct AnnotFormat { - pub width: Option, - pub border_style: Option, - pub dashes: Option>, - pub cloudy_intensity: Option>, - pub rotation: Option, - pub justification: Option, - pub fringe: Option<[f64; 4]>, - pub leader_length: Option, - pub leader_extend: Option, - pub leader_offset: Option, - pub caption: Option, - pub caption_style: Option, - pub caption_offset: Option<[f64; 2]>, - pub symbol: Option, - pub overlay_text: Option, - pub overlay_text_repeat: Option, -} - -/// Format XFDF 3.0 annotation formatting attributes into `attrs`. -pub(crate) fn write_format_attrs(fmt: &AnnotFormat, is_free_text: bool, attrs: &mut String) { - let list = |v: &[f64]| v.iter().map(|x| n(*x)).collect::>().join(","); - if let Some(w) = fmt.width.filter(|w| w.is_finite()) { - let _ = write!(attrs, " width=\"{}\"", n(w)); - } - if let Some(intensity) = fmt.cloudy_intensity { - attrs.push_str(" style=\"cloudy\""); - if let Some(i) = intensity.filter(|i| i.is_finite()) { - let _ = write!(attrs, " intensity=\"{}\"", n(i)); - } - } else if let Some(s) = fmt.border_style.and_then(BorderStyle::as_xfdf_attr) { - let _ = write!(attrs, " style=\"{s}\""); - } - if let Some(dashes) = &fmt.dashes - && !dashes.is_empty() - && dashes.iter().all(|v| v.is_finite()) - { - let _ = write!(attrs, " dashes=\"{}\"", list(dashes)); - } - if let Some(r) = fmt.rotation { - let _ = write!(attrs, " rotation=\"{r}\""); - } - if let Some(q) = fmt.justification { - match (is_free_text, q) { - (true, 0) => attrs.push_str(" justification=\"left\""), - (true, 1) => attrs.push_str(" justification=\"centered\""), - (true, 2) => attrs.push_str(" justification=\"right\""), - (true, _) => {} - (false, q) => { - let _ = write!(attrs, " justification=\"{q}\""); - } - } - } - if let Some(rd) = fmt.fringe - && rd.iter().all(|v| v.is_finite()) - { - let _ = write!(attrs, " fringe=\"{}\"", list(&rd)); - } - if let Some(ll) = fmt.leader_length.filter(|v| v.is_finite()) { - let _ = write!(attrs, " leaderLength=\"{}\"", n(ll)); - } - if let Some(lle) = fmt.leader_extend.filter(|v| v.is_finite()) { - let _ = write!(attrs, " leaderExtend=\"{}\"", n(lle)); - } - if let Some(llo) = fmt.leader_offset.filter(|v| v.is_finite()) { - let _ = write!(attrs, " leader-offset=\"{}\"", n(llo)); - } - if let Some(cap) = fmt.caption { - let _ = write!(attrs, " caption=\"{}\"", if cap { "yes" } else { "no" }); - } - if let Some(cp) = &fmt.caption_style { - let _ = write!(attrs, " caption-style=\"{}\"", esc(cp)); - } - if let Some([h, v]) = fmt.caption_offset - && h.is_finite() - && v.is_finite() - { - let _ = write!(attrs, " caption-offset-h=\"{}\" caption-offset-v=\"{}\"", n(h), n(v)); - } - match fmt.symbol { - Some(CaretSymbol::Paragraph) => attrs.push_str(" symbol=\"paragraph\""), - Some(CaretSymbol::None) => attrs.push_str(" symbol=\"none\""), - None => {} - } - if let Some(t) = &fmt.overlay_text { - let _ = write!(attrs, " overlay-text=\"{}\"", esc(t)); - } - if let Some(repeat) = fmt.overlay_text_repeat { - let _ = write!(attrs, " overlay-text-repeat=\"{repeat}\""); - } -} - -/// Parse XFDF 3.0 annotation formatting attributes from an XML element. -pub(crate) fn parse_format_attrs(node: &craft_xml::El) -> AnnotFormat { - let num = |a: &str| node.attr(a).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()); - let style = node.attr("style").map(str::trim); - let dashes = node.attr("dashes").map(csv).filter(|v| !v.is_empty() && v.iter().all(|x| *x >= 0.0) && v.iter().any(|x| *x > 0.0)); - let border_style = match style { - Some("dash") => Some(BorderStyle::Dash), - Some("bevelled" | "beveled") => Some(BorderStyle::Bevelled), - Some("inset") => Some(BorderStyle::Inset), - Some("underline") => Some(BorderStyle::Underline), - Some("solid") => Some(BorderStyle::Solid), - _ => None, - }; - let cloudy_intensity = (style == Some("cloudy")).then(|| Some(num("intensity").unwrap_or(1.0).clamp(0.0, 2.0))); - let (h, v) = (num("caption-offset-h"), num("caption-offset-v")); - AnnotFormat { - width: num("width"), - border_style, - dashes, - cloudy_intensity, - rotation: node.attr("rotation").and_then(|r| r.trim().parse::().ok()).map(i64::from), - justification: match node.attr("justification").map(str::trim) { - Some("left" | "0") => Some(0), - Some("centered" | "center" | "1") => Some(1), - Some("right" | "2") => Some(2), - _ => None, - }, - fringe: node.attr("fringe").map(csv).and_then(|r| r.try_into().ok()), - leader_length: num("leaderLength"), - leader_extend: num("leaderExtend").filter(|v| *v >= 0.0), - leader_offset: num("leader-offset").filter(|v| *v >= 0.0), - caption: match node.attr("caption").map(str::trim) { - Some("yes" | "true") => Some(true), - Some("no" | "false") => Some(false), - _ => None, - }, - caption_style: node.attr("caption-style").map(str::trim).filter(|c| matches!(*c, "Inline" | "Top")).map(str::to_owned), - caption_offset: (h.is_some() || v.is_some()).then(|| [h.unwrap_or(0.0), v.unwrap_or(0.0)]), - symbol: match node.attr("symbol").map(str::trim) { - Some("paragraph" | "P") => Some(CaretSymbol::Paragraph), - Some("none" | "None") => Some(CaretSymbol::None), - _ => None, - }, - overlay_text: node.attr("overlay-text").map(str::to_owned), - overlay_text_repeat: match node.attr("overlay-text-repeat").map(str::trim) { - Some("true" | "yes") => Some(true), - Some("false" | "no") => Some(false), - _ => None, - }, - } -} - -pub(crate) fn format_flags(flags: i64) -> String { - FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect::>().join(",") -} - -pub(crate) fn parse_flags(attr: Option<&str>) -> i64 { - attr.unwrap_or("print") - .split(',') - .filter_map(|f| FLAGS.iter().find(|(_, s)| s.eq_ignore_ascii_case(f.trim())).map(|x| x.0)) - .fold(0, |bits, flag| bits | flag) -} - -/// Pairs `x,y;x,y;…` (XFDF vertices and ink gestures). -pub(crate) fn pairs(text: &str) -> Vec<[f64; 2]> { - text.split(';').filter_map(|p| if let [x, y] = csv(p).as_slice() { Some([*x, *y]) } else { None }).collect() -} - -pub(crate) fn format_pairs(pts: &[[f64; 2]]) -> String { - pts.iter().map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect::>().join(";") -} - -/// Rich text (`/RC`) as `` holds it: its root element alone (no XML -/// declaration), when the text is well-formed XML; `None` otherwise. -pub(crate) fn rich_text_element(rc: &str) -> Option { - let t = rc.trim_start_matches('\u{feff}'); - if xml_nesting_depth(t) > MAX_RICH_DEPTH { - return None; - } - let parsed = parse_form_xml(t).ok()?; - Some(parsed.to_xml()) -} - -/// A `` element's plain text, a line per paragraph: what `/Contents` gets -/// when the element comes without ``. -pub(crate) fn rich_plain(node: &craft_xml::El) -> String { - fn walk(node: &craft_xml::El, out: &mut String) { - for n in &node.children { - match n { - craft_xml::Node::El(el) => { - if el.local() == "br" || (matches!(el.local(), "p" | "div" | "li") && !out.is_empty() && !out.ends_with('\r')) { - out.push('\r'); - } - walk(el, out); - } - craft_xml::Node::Text(t) if !(t.trim().is_empty() && t.contains('\n')) => { - out.push_str(&t.replace("\r\n", "\r").replace('\n', "\r")); - } - _ => {} - } - } - } - let mut out = String::new(); - walk(node, &mut out); - out.trim_end_matches('\r').to_string() -} - -/// The one element `markup` (cut out of `rich`, a ``) as an XML -/// document of its own: the namespaces it inherits from the XFDF around it are declared on it. -pub(crate) fn standalone(el: &craft_xml::El, ns: &[(String, String)]) -> String { - let mut clone = (*el).clone(); - let markup = clone.to_xml(); - if let Some((_, uri)) = ns.iter().rfind(|(p, _)| p.is_empty()) - && !uri.is_empty() - && uri != XFDF_NS - && !clone.has_attr("xmlns") - { - clone.set_attr("xmlns", uri); - } - for (prefix, uri) in ns { - if prefix.is_empty() || prefix == "xml" { - continue; - } - let attr_name = format!("xmlns:{prefix}"); - if markup.contains(&format!("{prefix}:")) && !clone.has_attr(&attr_name) { - clone.set_attr(&attr_name, uri); - } - } - clone.to_xml() -} - -/// Whether `text` is XFDF with comments in it (what a paste of copied comments carries). -pub fn is_xfdf_comments(text: &str) -> bool { - let head: String = text.chars().take(400).collect(); - head.contains(" bool { - matches!(key, b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key == b"AP" && !is_stamp) -} - -#[allow(dead_code)] -pub(crate) fn format_color_attr(name: &str, color: &[f64], out: &mut String) { - if let Some(c) = hex(color) { - let _ = write!(out, " {name}=\"{c}\""); - } -} - -#[allow(dead_code)] -pub(crate) fn rich_text_plain(node: &craft_xml::El) -> String { - el_text(node) -} diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index 6b34c6b2c3..0cff7e1016 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -23,18 +23,17 @@ use pdfcraft_forms::{FieldKind, FieldValue}; mod appearance; mod common; mod fdf; -mod grammar; mod xfdf; #[cfg(test)] use common::{MAX_DEPTH, MAX_XML_DEPTH, arr, nums_of, parse_hex, text_of, xml_nesting_depth}; use common::{check_form_xml_depth, el_text, esc, parse_form_xml, xml_name}; +use craft_xfdf::grammar::SUBTYPES; +pub use craft_xfdf::grammar::is_xfdf_comments; pub use fdf::export_fdf; use fdf::{ImportBudget, fdf_body, import_fdf, walk_fdf}; #[cfg(test)] use fdf::{MAX_FDF_BYTES, MAX_FDF_OBJECTS}; -use grammar::SUBTYPES; -pub use grammar::is_xfdf_comments; #[cfg(test)] use xfdf::{LOCKED, find_by_name}; pub use xfdf::{Outline, comment_count, comment_outlines, comments_bounds, export_xfdf, export_xfdf_comments, import_comments}; diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs index d427bade73..2c713f1bf1 100644 --- a/crates/xfdf/src/tests.rs +++ b/crates/xfdf/src/tests.rs @@ -2789,3 +2789,47 @@ fn shared_xfdf_fields_match_retained_reader() -> Result<(), Box