export: isolate portable HTML and XFDF/FDF grammar (#7868)

* export: isolate portable HTML and XFDF/FDF grammar

* Fix extracted XFDF helper references and format affected crates

* Borrow HTML export items and finish extracted XFDF lint cleanup
This commit is contained in:
Dylan M. Taylor
2026-11-19 14:00:55 -05:00
committed by GitHub
parent f0bbce5b30
commit 043ccbdf84
8 changed files with 633 additions and 393 deletions
+45 -95
View File
@@ -1,12 +1,10 @@
use super::as_docx::{hex, rgb8, room_for};
use super::layout::{Image, Item, Page, Run, Table, items};
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};
/// 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. Text extracted from PDFs often holds them
/// (fonts without a usable `/ToUnicode`), and Word refuses a whole document over one (#72).
pub(crate) fn allowed(c: char) -> bool {
matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}')
}
pub(crate) use super::html::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.
@@ -43,22 +41,6 @@ pub(crate) fn language_tag(lang: Option<&str>) -> Option<&str> {
(!singleton).then_some(tag)
}
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("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
c => o.push(c),
}
}
o
}
pub(crate) use craft_mime::transfer::base64;
/// One HTML file: headings and paragraphs, tables as real `<table>` elements, images inline, a
/// rule between pages.
pub fn html(pages: &[Page], title: &str) -> String {
@@ -83,96 +65,64 @@ pub fn html_simple_with_language(pages: &[Page], title: &str, language: Option<&
html_with_mode(pages, title, true, language)
}
fn style_color(color: [f64; 3], simple: bool) -> String {
if simple { String::new() } else { hex(color).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) }
}
fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String {
if text.trim().is_empty() {
return text;
}
if italic {
text = format!("<em>{text}</em>");
}
if bold {
text = format!("<strong>{text}</strong>");
}
text
}
#[cfg(test)]
fn para_html(runs: &[Run<'_>], lvl: u8, simple: bool) -> Option<String> {
let non_empty: Vec<_> = runs.iter().map(|r| (r.block, 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 (block, text) in non_empty {
if text.trim().is_empty() {
t.push_str(&text);
continue;
}
let mut run = wrap_inline(text, block.bold && lvl == 0, block.italic);
// The paragraph has its first visible run's colour; a run in another colour says so.
let colour = rgb8(block.color);
if !simple && colour != rgb8(first.color) {
let [red, green, blue] = colour;
run = format!("<span style=\"color:#{red:02X}{green:02X}{blue:02X}\">{run}</span>");
}
t.push_str(&run);
}
let style = style_color(first.color, simple);
Some(match lvl.min(6) {
0 => format!("<p{style}>{t}</p>\n"),
l => format!("<h{l}{style}>{t}</h{l}>\n"),
})
let html_runs: Vec<HtmlRun<'_>> =
runs.iter().map(|r| HtmlRun { text: &r.text, bold: r.block.bold, italic: r.block.italic, color: rgb8(r.block.color) }).collect();
html::render_para(&html_runs, lvl, simple)
}
#[cfg(test)]
fn table_html(t: &Table, simple: bool) -> String {
let mut s = String::from("<table>\n");
for row in &t.rows {
s.push_str("<tr>");
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!("<td{span}{style}>{body}</td>"));
}
s.push_str("</tr>\n");
}
s.push_str("</table>\n");
s
let table = HtmlTable {
rows: t
.rows
.iter()
.map(|row| row.iter().map(|c| HtmlCell { text: &c.text, bold: c.bold, italic: c.italic, color: rgb8(c.color), span: c.span }).collect())
.collect(),
};
html::render_table(&table, simple)
}
fn html_with_mode(pages: &[Page], title: &str, simple: bool, language: Option<&str>) -> String {
let lang = language_tag(language).map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default();
let mut s = format!(
"<!DOCTYPE html>\n<html{lang}>\n<head>\n<meta charset=\"utf-8\">\n<title>{}</title>\n{}\n</head>\n<body>\n",
esc(title),
if simple {
""
} else {
"<style>body{max-width:46em;margin:2em auto;font-family:sans-serif;line-height:1.45}img{max-width:100%}hr{border:0;border-top:1px solid #ccc;margin:2em 0}table{border-collapse:collapse;margin:1em 0}td,th{border:1px solid #999;padding:2px 6px;vertical-align:top}</style>"
}
);
let mut embedded: Vec<(String, &Image)> = Vec::new();
for it in items(pages) {
let mut blocks: Vec<HtmlBlock<'_>> = Vec::new();
let items: Vec<Item<'_>> = items(pages);
for it in &items {
match it {
Item::Para(runs, lvl) => {
if let Some(p) = para_html(&runs, lvl, simple) {
s.push_str(&p);
}
blocks.push(HtmlBlock::Para {
runs: runs
.iter()
.map(|r| HtmlRun { text: &r.text, bold: r.block.bold, italic: r.block.italic, color: rgb8(r.block.color) })
.collect(),
level: *lvl,
});
}
Item::Table(t) => {
blocks.push(HtmlBlock::Table(HtmlTable {
rows: t
.rows
.iter()
.map(|row| {
row.iter()
.map(|c| HtmlCell { text: &c.text, bold: c.bold, italic: c.italic, color: rgb8(c.color), span: c.span })
.collect()
})
.collect(),
}));
}
Item::Table(t) => s.push_str(&table_html(&t, simple)),
// HTML embeds each placement in full, so repeated pictures also consume the budget.
Item::Img(im) if room_for(&embedded, im) => {
let mime = if im.ext == "jpg" { "image/jpeg" } else { "image/png" };
s.push_str(&format!("<p><img alt=\"\" src=\"data:{mime};base64,{}\"></p>\n", base64(&im.bytes)));
blocks.push(HtmlBlock::Image { mime, bytes: &im.bytes });
embedded.push((String::new(), im));
}
Item::Img(_) => {}
Item::PageBreak => s.push_str("<hr>\n"),
Item::PageBreak => blocks.push(HtmlBlock::PageBreak),
}
}
s.push_str("</body>\n</html>\n");
s
html::render(&blocks, title, simple, language_tag(language))
}
#[cfg(test)]
+145
View File
@@ -0,0 +1,145 @@
//! 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("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
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<Vec<HtmlCell<'a>>>,
}
/// A block-level element in a portable HTML document.
pub(crate) enum HtmlBlock<'a> {
Para { runs: Vec<HtmlRun<'a>>, level: u8 },
Table(HtmlTable<'a>),
Image { mime: &'a str, bytes: &'a [u8] },
PageBreak,
}
fn rgb_hex(rgb: [u8; 3]) -> Option<String> {
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!("<em>{text}</em>");
}
if bold {
text = format!("<strong>{text}</strong>");
}
text
}
pub(crate) fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option<String> {
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!("<span style=\"color:#{red:02X}{green:02X}{blue:02X}\">{out}</span>");
}
t.push_str(&out);
}
let style = style_color(first.color, simple);
Some(match lvl.min(6) {
0 => format!("<p{style}>{t}</p>\n"),
l => format!("<h{l}{style}>{t}</h{l}>\n"),
})
}
pub(crate) fn render_table(t: &HtmlTable<'_>, simple: bool) -> String {
let mut s = String::from("<table>\n");
for row in &t.rows {
s.push_str("<tr>");
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!("<td{span}{style}>{body}</td>"));
}
s.push_str("</tr>\n");
}
s.push_str("</table>\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!(
"<!DOCTYPE html>\n<html{lang}>\n<head>\n<meta charset=\"utf-8\">\n<title>{}</title>\n{}\n</head>\n<body>\n",
esc(title),
if simple {
""
} else {
"<style>body{max-width:46em;margin:2em auto;font-family:sans-serif;line-height:1.45}img{max-width:100%}hr{border:0;border-top:1px solid #ccc;margin:2em 0}table{border-collapse:collapse;margin:1em 0}td,th{border:1px solid #999;padding:2px 6px;vertical-align:top}</style>"
}
);
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!("<p><img alt=\"\" src=\"data:{mime};base64,{}\"></p>\n", base64(bytes)));
}
HtmlBlock::PageBreak => s.push_str("<hr>\n"),
}
}
s.push_str("</body>\n</html>\n");
s
}
+4 -3
View File
@@ -23,15 +23,13 @@ mod as_rtf;
mod as_word;
mod clip;
mod flow;
mod html;
mod layout;
#[cfg(test)]
use as_docx::MAX_MEDIA;
pub(crate) use as_docx::hex;
pub use as_docx::{docx, docx_with_language};
pub(crate) use as_html::esc;
#[cfg(test)]
use as_html::{allowed, base64};
pub use as_html::{html, html_simple, html_simple_with_language, html_with_language};
pub use as_markdown::markdown;
#[cfg(test)]
@@ -40,6 +38,9 @@ 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};
#[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};
+1 -52
View File
@@ -105,58 +105,7 @@ pub(crate) fn el_text(el: &craft_xml::El) -> String {
.collect()
}
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"),
];
pub(crate) fn esc(s: &str) -> String {
let mut o = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => o.push_str("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
// XML 1.0 §3.3.3 normalizes literal attribute whitespace, but not references.
'\t' => o.push_str("&#9;"),
'\n' => o.push_str("&#10;"),
'\r' => o.push_str("&#13;"),
c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}
// XML 1.0 noncharacters are not allowed even as raw text.
'\u{FFFE}' | '\u{FFFF}' => {}
c => o.push(c),
}
}
o
}
pub(crate) use craft_xml::esc_attr as esc;
pub(crate) fn n(v: f64) -> String {
let s = format!("{v:.4}");
+3 -2
View File
@@ -1,4 +1,5 @@
use super::common::{MAX_DEPTH, SUBTYPES, rect_strict, text_of};
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::*;
@@ -105,7 +106,7 @@ impl<'a> FdfCopy<'a> {
let stamp = dict.name(b"Subtype") == Some(b"Stamp".as_slice());
let mut out = Dict::new();
for (key, value) in dict.iter() {
if matches!(key.as_slice(), b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key.as_slice() == b"AP" && !stamp) {
if fdf_annot_skip_key(key.as_slice(), stamp) {
continue;
}
self.dict_entry(&mut out, key, value, 1)?;
+355
View File
@@ -0,0 +1,355 @@
//! 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<f64>,
pub border_style: Option<BorderStyle>,
pub dashes: Option<Vec<f64>>,
pub cloudy_intensity: Option<Option<f64>>,
pub rotation: Option<i64>,
pub justification: Option<i64>,
pub fringe: Option<[f64; 4]>,
pub leader_length: Option<f64>,
pub leader_extend: Option<f64>,
pub leader_offset: Option<f64>,
pub caption: Option<bool>,
pub caption_style: Option<String>,
pub caption_offset: Option<[f64; 2]>,
pub symbol: Option<CaretSymbol>,
pub overlay_text: Option<String>,
pub overlay_text_repeat: Option<bool>,
}
/// 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::<Vec<_>>().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::<f64>().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::<i32>().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::<Vec<_>>().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::<Vec<_>>().join(";")
}
/// Rich text (`/RC`) as `<contents-richtext>` 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<String> {
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 `<contents-richtext>` element's plain text, a line per paragraph: what `/Contents` gets
/// when the element comes without `<contents>`.
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 `<contents-richtext>`) 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("<xfdf") && text.contains("<annots")
}
/// Every comment element of an XFDF text, in order (none when it is no XFDF).
pub(crate) fn with_comment_nodes(text: &str, mut f: impl FnMut(&craft_xml::El)) {
if check_form_xml_depth(text).is_err() {
return;
}
let Ok(root) = parse_form_xml(text) else { return };
if root.local() != "xfdf" {
return;
}
let Some(annots) = root.child(craft_xml::Local("annots")) else { return };
for node in annots.elements() {
if SUBTYPES.iter().any(|(_, t)| *t == node.local().to_ascii_lowercase()) {
f(node);
}
}
}
/// Whether an annotation dictionary key is skipped when exporting into FDF (ISO 32000-2 §12.7.8.3.4).
pub(crate) fn fdf_annot_skip_key(key: &[u8], is_stamp: bool) -> 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)
}
+4 -1
View File
@@ -23,6 +23,7 @@ use pdfcraft_forms::{FieldKind, FieldValue};
mod appearance;
mod common;
mod fdf;
mod grammar;
mod xfdf;
#[cfg(test)]
@@ -32,9 +33,11 @@ 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, is_xfdf_comments};
pub use xfdf::{Outline, comment_count, comment_outlines, comments_bounds, export_xfdf, export_xfdf_comments, import_comments};
use xfdf::{apply_values, import_xfdf};
#[cfg(test)]
+76 -240
View File
@@ -1,6 +1,10 @@
use super::common::{
FLAGS, MAX_DEPTH, SUBTYPES, arr, check_form_xml_depth, csv, el_text, esc, hex, n, nums_of, parse_form_xml, parse_hex, quad_has_area, rect_strict,
text_of, walk_xfdf, xml_nesting_depth,
MAX_DEPTH, arr, check_form_xml_depth, csv, el_text, esc, hex, n, nums_of, parse_form_xml, parse_hex, quad_has_area, rect_strict, text_of,
walk_xfdf,
};
use super::grammar::{
AnnotFormat, BorderStyle, CaretSymbol, SUBTYPES, format_flags, format_pairs, pairs, parse_flags, parse_format_attrs, rich_plain,
rich_text_element, standalone, with_comment_nodes, write_format_attrs,
};
use super::*;
@@ -113,21 +117,6 @@ fn read_own_keys(node: &craft_xml::El, ns: &[(String, String)], d: &mut Dict) {
}
}
/// 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;
/// Rich text (`/RC`) as `<contents-richtext>` holds it: its root element alone (no XML
/// declaration), when the text is well-formed XML; `None` otherwise.
fn rich_text_element(rc: &str) -> Option<String> {
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())
}
/// The formatting attributes of a comment: XFDF 3.0 "Border style attributes" (`width`, `style`,
/// `dashes`), "Border effect attributes" (`style="cloudy"`, `intensity`), and the free text
/// (`rotation`, `justification`), stamp (`rotation`), circle/square/caret (`fringe`), line
@@ -137,7 +126,6 @@ fn rich_text_element(rc: &str) -> Option<String> {
fn format_attrs(doc: &Document, d: &Dict, sub: &[u8], attrs: &mut String) {
let num = |k: &[u8]| d.get(k).and_then(|o| doc.resolve(o).as_f64()).filter(|v| v.is_finite());
let name = |k: &[u8]| d.get(k).and_then(|o| doc.resolve(o).as_name().map(<[u8]>::to_vec));
let list = |v: &[f64]| v.iter().map(|x| n(*x)).collect::<Vec<_>>().join(",");
// The border: /BS, or (without one) the older /Border array [h v width dashes].
let (width, style, dashes) = match d.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned()) {
Some(bs) => (
@@ -151,193 +139,105 @@ fn format_attrs(doc: &Document, d: &Dict, sub: &[u8], attrs: &mut String) {
(border.get(2).and_then(|w| doc.resolve(w).as_f64()), (!dash.is_empty()).then(|| b"D".to_vec()), dash)
}
};
if let Some(w) = width.filter(|w| w.is_finite()) {
let _ = write!(attrs, " width=\"{}\"", n(w));
}
// One `style` attribute names both: a cloudy border effect (/BE /S /C) takes it.
let cloudy = d.get(b"BE").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).filter(|b| b.name(b"S") == Some(b"C".as_slice()));
if let Some(be) = cloudy {
attrs.push_str(" style=\"cloudy\"");
if let Some(i) = be.get(b"I").and_then(|i| doc.resolve(i).as_f64()).filter(|i| i.is_finite()) {
let _ = write!(attrs, " intensity=\"{}\"", n(i));
}
} else if let Some(s) = match style.as_deref() {
Some(b"D") => Some("dash"),
Some(b"B") => Some("bevelled"),
Some(b"I") => Some("inset"),
Some(b"U") => Some("underline"),
_ => None,
} {
let _ = write!(attrs, " style=\"{s}\"");
}
// The dash array (/D) whatever the style, as `dashes` maps it; only `style="dash"` draws it.
if !dashes.is_empty() && dashes.iter().all(|v| v.is_finite()) {
let _ = write!(attrs, " dashes=\"{}\"", list(&dashes));
}
if let Some(r) = d.get(b"Rotate").and_then(|o| doc.resolve(o).as_int()) {
let _ = write!(attrs, " rotation=\"{r}\"");
}
if let Some(q) = d.get(b"Q").and_then(|o| doc.resolve(o).as_int()) {
// Free text names its justification; a redaction mark gives the number (XFDF 3.0).
match (sub, q) {
(b"FreeText", 0) => attrs.push_str(" justification=\"left\""),
(b"FreeText", 1) => attrs.push_str(" justification=\"centered\""),
(b"FreeText", 2) => attrs.push_str(" justification=\"right\""),
(b"FreeText", _) => {}
(_, q) => {
let _ = write!(attrs, " justification=\"{q}\"");
}
}
}
let rd = nums_of(doc, d.get(b"RD"));
if rd.len() == 4 && rd.iter().all(|v| v.is_finite()) {
let _ = write!(attrs, " fringe=\"{}\"", list(&rd));
}
if let Some(ll) = num(b"LL") {
let _ = write!(attrs, " leaderLength=\"{}\"", n(ll));
}
if let Some(lle) = num(b"LLE") {
let _ = write!(attrs, " leaderExtend=\"{}\"", n(lle));
}
if let Some(llo) = num(b"LLO") {
let _ = write!(attrs, " leader-offset=\"{}\"", n(llo));
}
if let Some(Object::Bool(cap)) = d.get(b"Cap").map(|o| doc.resolve(o)).as_deref() {
let _ = write!(attrs, " caption=\"{}\"", if *cap { "yes" } else { "no" });
}
if let Some(cp) = name(b"CP") {
let _ = write!(attrs, " caption-style=\"{}\"", esc(&String::from_utf8_lossy(&cp)));
}
if let [h, v] = nums_of(doc, d.get(b"CO")).as_slice()
&& h.is_finite()
&& v.is_finite()
{
let _ = write!(attrs, " caption-offset-h=\"{}\" caption-offset-v=\"{}\"", n(*h), n(*v));
}
match name(b"Sy").as_deref() {
Some(b"P") => attrs.push_str(" symbol=\"paragraph\""),
Some(b"None") => attrs.push_str(" symbol=\"none\""),
_ => {}
}
if let Some(t) = text_of(doc, d, b"OverlayText") {
let _ = write!(attrs, " overlay-text=\"{}\"", esc(&t));
}
if let Some(Object::Bool(repeat)) = d.get(b"Repeat").map(|o| doc.resolve(o)).as_deref() {
let _ = write!(attrs, " overlay-text-repeat=\"{repeat}\"");
}
let fmt = AnnotFormat {
width,
border_style: match style.as_deref() {
Some(b"D") => Some(BorderStyle::Dash),
Some(b"B") => Some(BorderStyle::Bevelled),
Some(b"I") => Some(BorderStyle::Inset),
Some(b"U") => Some(BorderStyle::Underline),
_ => None,
},
dashes: (!dashes.is_empty()).then_some(dashes),
cloudy_intensity: cloudy.map(|be| be.get(b"I").and_then(|i| doc.resolve(i).as_f64()).filter(|i| i.is_finite())),
rotation: d.get(b"Rotate").and_then(|o| doc.resolve(o).as_int()),
justification: d.get(b"Q").and_then(|o| doc.resolve(o).as_int()),
fringe: nums_of(doc, d.get(b"RD")).try_into().ok(),
leader_length: num(b"LL"),
leader_extend: num(b"LLE"),
leader_offset: num(b"LLO"),
caption: match d.get(b"Cap").map(|o| doc.resolve(o)).as_deref() {
Some(Object::Bool(cap)) => Some(*cap),
_ => None,
},
caption_style: name(b"CP").map(|cp| String::from_utf8_lossy(&cp).into_owned()),
caption_offset: match nums_of(doc, d.get(b"CO")).as_slice() {
[h, v] => Some([*h, *v]),
_ => None,
},
symbol: match name(b"Sy").as_deref() {
Some(b"P") => Some(CaretSymbol::Paragraph),
Some(b"None") => Some(CaretSymbol::None),
_ => None,
},
overlay_text: text_of(doc, d, b"OverlayText"),
overlay_text_repeat: match d.get(b"Repeat").map(|o| doc.resolve(o)).as_deref() {
Some(Object::Bool(repeat)) => Some(*repeat),
_ => None,
},
};
write_format_attrs(&fmt, sub == b"FreeText", attrs);
}
/// The formatting attributes of an XFDF comment element back as dictionary entries (see
/// [`format_attrs`]). Values that are not numbers, or out of range, are left out.
fn read_format(node: &craft_xml::El, d: &mut Dict) {
let num = |a: &str| node.attr(a).and_then(|v| v.trim().parse::<f64>().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 bs_style = match style {
Some("dash") => Some("D"),
Some("bevelled" | "beveled") => Some("B"),
Some("inset") => Some("I"),
Some("underline") => Some("U"),
Some("solid") => Some("S"),
_ => None,
};
let width = num("width");
if width.is_some() || bs_style.is_some() || dashes.is_some() {
let fmt = parse_format_attrs(node);
if fmt.width.is_some() || fmt.border_style.is_some() || fmt.dashes.is_some() {
let mut bs = Dict::new();
// XFDF 3.0: the width is 1 and the style solid unless given.
bs.set(b"W".to_vec(), Object::Real(width.unwrap_or(1.0).max(0.0)));
bs.set(b"S".to_vec(), Object::name(bs_style.unwrap_or("S")));
if let Some(dv) = &dashes {
bs.set(b"W".to_vec(), Object::Real(fmt.width.unwrap_or(1.0).max(0.0)));
bs.set(b"S".to_vec(), Object::name(fmt.border_style.map_or("S", BorderStyle::as_pdf_name)));
if let Some(dv) = &fmt.dashes {
bs.set(b"D".to_vec(), arr(dv));
}
d.set(b"BS".to_vec(), Object::Dict(bs));
}
if style == Some("cloudy") {
if let Some(intensity) = fmt.cloudy_intensity {
let mut be = Dict::new();
be.set(b"S".to_vec(), Object::name("C"));
let intensity = num("intensity").unwrap_or(1.0);
be.set(b"I".to_vec(), Object::Real(intensity.clamp(0.0, 2.0)));
be.set(b"I".to_vec(), Object::Real(intensity.unwrap_or(1.0).clamp(0.0, 2.0)));
d.set(b"BE".to_vec(), Object::Dict(be));
}
if let Some(r) = node.attr("rotation").and_then(|r| r.trim().parse::<i32>().ok()) {
d.set(b"Rotate".to_vec(), Object::Int(i64::from(r)));
if let Some(r) = fmt.rotation {
d.set(b"Rotate".to_vec(), Object::Int(r));
}
let q = match node.attr("justification").map(str::trim) {
Some("left" | "0") => Some(0),
Some("centered" | "center" | "1") => Some(1),
Some("right" | "2") => Some(2),
_ => None,
};
if let Some(q) = q {
if let Some(q) = fmt.justification {
d.set(b"Q".to_vec(), Object::Int(q));
}
if let Some(rd) = node.attr("fringe").map(csv).filter(|r| r.len() == 4) {
if let Some(rd) = fmt.fringe {
d.set(b"RD".to_vec(), arr(&rd));
}
if let Some(ll) = num("leaderLength") {
if let Some(ll) = fmt.leader_length {
d.set(b"LL".to_vec(), Object::Real(ll));
}
if let Some(lle) = num("leaderExtend").filter(|v| *v >= 0.0) {
if let Some(lle) = fmt.leader_extend {
d.set(b"LLE".to_vec(), Object::Real(lle));
}
if let Some(llo) = num("leader-offset").filter(|v| *v >= 0.0) {
if let Some(llo) = fmt.leader_offset {
d.set(b"LLO".to_vec(), Object::Real(llo));
}
match node.attr("caption").map(str::trim) {
Some("yes" | "true") => d.set(b"Cap".to_vec(), Object::Bool(true)),
Some("no" | "false") => d.set(b"Cap".to_vec(), Object::Bool(false)),
_ => {}
if let Some(cap) = fmt.caption {
d.set(b"Cap".to_vec(), Object::Bool(cap));
}
if let Some(cp) = node.attr("caption-style").map(str::trim).filter(|c| matches!(*c, "Inline" | "Top")) {
d.set(b"CP".to_vec(), Object::name(cp));
if let Some(cp) = fmt.caption_style {
d.set(b"CP".to_vec(), Object::name(&cp));
}
let (h, v) = (num("caption-offset-h"), num("caption-offset-v"));
if h.is_some() || v.is_some() {
d.set(b"CO".to_vec(), arr(&[h.unwrap_or(0.0), v.unwrap_or(0.0)]));
if let Some([h, v]) = fmt.caption_offset {
d.set(b"CO".to_vec(), arr(&[h, v]));
}
match node.attr("symbol").map(str::trim) {
Some("paragraph" | "P") => d.set(b"Sy".to_vec(), Object::name("P")),
Some("none" | "None") => d.set(b"Sy".to_vec(), Object::name("None")),
_ => {}
if let Some(sym) = fmt.symbol {
d.set(b"Sy".to_vec(), Object::name(sym.as_pdf_name()));
}
if let Some(t) = node.attr("overlay-text") {
d.set(b"OverlayText".to_vec(), PdfString::text(t));
if let Some(t) = fmt.overlay_text {
d.set(b"OverlayText".to_vec(), PdfString::text(&t));
}
match node.attr("overlay-text-repeat").map(str::trim) {
Some("true" | "yes") => d.set(b"Repeat".to_vec(), Object::Bool(true)),
Some("false" | "no") => d.set(b"Repeat".to_vec(), Object::Bool(false)),
_ => {}
if let Some(repeat) = fmt.overlay_text_repeat {
d.set(b"Repeat".to_vec(), Object::Bool(repeat));
}
}
/// A `<contents-richtext>` element's plain text, a line per paragraph: what `/Contents` gets
/// when the element comes without `<contents>`.
fn walk_rich_plain(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_rich_plain(el, out);
}
craft_xml::Node::Text(t) => {
// Indentation between elements is not text.
if !(t.trim().is_empty() && t.contains('\n')) {
out.push_str(&t.replace("\r\n", "\r").replace('\n', "\r"));
}
}
_ => {}
}
}
}
fn rich_plain(node: &craft_xml::El) -> String {
let mut out = String::new();
walk_rich_plain(node, &mut out);
out.trim_end_matches('\r').to_string()
}
/// The name of every annotation, for `inreplyto`: its /NM, or, for one without one (other tools
/// leave /NM out) that is in `only` or that another annotation replies to or is grouped under
/// (`/IRT`, ISO 32000-2 §12.5.6.2; a Replace Text pair is such a group), a name new to the
@@ -423,16 +323,16 @@ fn xfdf_annot_children(doc: &Document, out: &mut String, d: &Dict, pi: usize, ap
out.push_str("<inklist>");
for g in ink {
let v = nums_of(doc, Some(&g));
let pts: Vec<String> = v.as_chunks::<2>().0.iter().map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect();
let _ = write!(out, "<gesture>{}</gesture>", pts.join(";"));
let pts: Vec<[f64; 2]> = v.as_chunks::<2>().0.to_vec();
let _ = write!(out, "<gesture>{}</gesture>", format_pairs(&pts));
}
out.push_str("</inklist>");
}
// Polygon and polyline points (XFDF `<vertices>`: `x,y;x,y;…`).
let vertices = nums_of(doc, d.get(b"Vertices"));
let pts: Vec<String> = vertices.as_chunks::<2>().0.iter().map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect();
let pts: Vec<[f64; 2]> = vertices.as_chunks::<2>().0.to_vec();
if !pts.is_empty() {
let _ = write!(out, "<vertices>{}</vertices>", pts.join(";"));
let _ = write!(out, "<vertices>{}</vertices>", format_pairs(&pts));
}
if let Some(pd) = d.get(b"Popup").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()) {
let r = nums_of(doc, pd.get(b"Rect"));
@@ -498,8 +398,7 @@ fn xfdf_annots(doc: &Document, out: &mut String, only: Option<&HashSet<(usize, u
}
}
let flags = d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);
let fl: Vec<&str> = FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect();
let _ = write!(attrs, " flags=\"{}\"", fl.join(","));
let _ = write!(attrs, " flags=\"{}\"", format_flags(flags));
if let Some(c) = hex(&nums_of(doc, d.get(b"C"))) {
let _ = write!(attrs, " color=\"{c}\"");
}
@@ -623,12 +522,6 @@ pub fn export_xfdf_comments(doc: &Document, which: &[(usize, usize)], file: &str
out
}
/// 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("<xfdf") && text.contains("<annots")
}
/// What a comment of an XFDF text looks like, for drawing a bundle of copied comments before
/// it is placed: its geometry in user space and its colour (RGB 0–1).
#[derive(Clone, Debug, PartialEq)]
@@ -648,23 +541,6 @@ pub enum Outline {
Text { rect: [f64; 4], text: String, size: f64, color: Option<[f64; 3]> },
}
/// Every comment element of an XFDF text, in order (none when it is no XFDF).
fn with_comment_nodes(text: &str, mut f: impl FnMut(&craft_xml::El)) {
if check_form_xml_depth(text).is_err() {
return;
}
let Ok(root) = parse_form_xml(text) else { return };
if root.local() != "xfdf" {
return;
}
let Some(annots) = root.child(craft_xml::Local("annots")) else { return };
for node in annots.elements() {
if SUBTYPES.iter().any(|(_, t)| *t == node.local().to_ascii_lowercase()) {
f(node);
}
}
}
/// The comment elements of an XFDF text: tag, `inreplyto`, rect.
fn comment_nodes(text: &str) -> Vec<(String, Option<String>, Vec<f64>)> {
let mut out = Vec::new();
@@ -674,11 +550,6 @@ fn comment_nodes(text: &str) -> Vec<(String, Option<String>, Vec<f64>)> {
out
}
/// Pairs `x,y;x,y;…` (XFDF vertices and ink gestures).
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()
}
/// The outlines of the comments in an XFDF text (replies, which have no place of their own,
/// left out): what a paste shows hanging on the pointer.
pub fn comment_outlines(text: &str) -> Vec<Outline> {
@@ -914,12 +785,7 @@ fn annot_from_xml(node: &craft_xml::El, ns: &[(String, String)], subtype: &str,
if let Some(v) = node.attr("icon") {
d.set(b"Name".to_vec(), Object::name(v));
}
let flags: i64 = node
.attr("flags")
.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);
let flags = parse_flags(node.attr("flags"));
d.set(b"F".to_vec(), Object::Int(flags));
if let Some(c) = node.attr("color").and_then(parse_hex) {
d.set(b"C".to_vec(), arr(&c));
@@ -1029,36 +895,6 @@ fn read_rich_text(rich: &craft_xml::El, ns: &[(String, String)], has_contents: b
}
}
/// The one element `markup` (cut out of `rich`, a `<contents-richtext>`) as an XML
/// document of its own: the namespaces it inherits from the XFDF around it are declared on it,
/// the default one (XHTML declared on `<contents-richtext>`, say; not XFDF's own, which a
/// standalone document has no use for) and the prefixes it uses. Unchanged when nothing is
/// inherited, or when the declarations would not make it parse.
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()
}
/// XFDF's own namespace (ISO 19444-1).
const XFDF_NS: &str = "http://ns.adobe.com/xfdf/";
/// Put an annotation dictionary on a page, replacing one with the same `/NM`. Returns its
/// reference.
/// `/F` bits an imported file may not set on a redaction mark: Invisible, Hidden, NoView — so a