use super::documents::{declare_document, DocTree, TagRule, Vocabulary};
use super::element::{attributes, elements};
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
elements! {
pdf: children;
page: children;
highlight: leaf;
underline: leaf;
strikeout: leaf;
squiggly: leaf;
note: children;
reply: leaf;
textbox: leaf;
ink: leaf;
rectangle: leaf;
ellipse: leaf;
line: leaf;
polygon: leaf;
polyline: leaf;
stamp: leaf;
signature: leaf;
redact: leaf;
field: leaf;
fill: leaf;
bookmark: children;
label: leaf;
attach: leaf;
header: leaf;
footer: leaf;
bates: leaf;
}
attributes! {
pub trait PdfAttrs {
title; author; subject; keywords; creator;
id; src; n; rotate; size; width; height;
text; color; opacity; date; rects; at; icon; open; rect; text_color; border; fill; align;
strokes; from; to; arrow; points; name; label; image; typed; style; overlay;
kind; value; options; checked; multiline; max_length; required; read_only; tooltip; default_; editable; state;
page; top; bold; italic; url; prefix; start; description; mime_type;
left; center; right; family; margin; inset; pages; suffix; digits; position;
}
}
pub(crate) const FAMILY: Family = Family { module: "pdf", roots: &["pdf"], declare };
const PAGE_SIZES: &[&str] = &["a3", "a4", "a5", "letter", "legal", "tabloid"];
const PDF_FIELDS: &[&str] = &["title", "author", "subject", "keywords", "creator"];
const PAGE_FIELDS: &[&str] = &["id", "src", "n", "rotate", "size", "width", "height"];
const BOOKMARK_FIELDS: &[&str] = &["id", "title", "page", "top", "open", "bold", "italic", "color", "url"];
const LABEL_FIELDS: &[&str] = &["from", "style", "prefix", "start"];
const ATTACH_FIELDS: &[&str] = &["src", "name", "description", "mimeType"];
const BAND_FIELDS: &[&str] = &["left", "center", "right", "size", "color", "family", "margin", "inset", "pages", "start", "date"];
const BATES_FIELDS: &[&str] = &["prefix", "suffix", "start", "digits", "position", "size", "color", "family", "margin", "inset"];
const BATES_POSITIONS: &[&str] = &["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"];
pub const REVIEW_STATES: &[&str] = &["Accepted", "Rejected", "Cancelled", "Completed", "None"];
const TEXT_MARK: &[&str] = &["id", "author", "text", "color", "opacity", "date", "rects"];
const PDF: Vocabulary = Vocabulary {
format: "pdf",
noun: "a PDF",
root: "pdf",
tags: &[
TagRule::new("pdf", &[]).attrs(PDF_FIELDS),
TagRule::new("page", &["pdf"]).key("id").attrs(PAGE_FIELDS),
TagRule::new("highlight", &["page"]).key("id").required(&["rects"]).attrs(TEXT_MARK),
TagRule::new("underline", &["page"]).key("id").required(&["rects"]).attrs(TEXT_MARK),
TagRule::new("strikeout", &["page"]).key("id").required(&["rects"]).attrs(TEXT_MARK),
TagRule::new("squiggly", &["page"]).key("id").required(&["rects"]).attrs(TEXT_MARK),
TagRule::new("note", &["page"]).key("id").required(&["at"]).attrs(&["id", "author", "text", "color", "opacity", "date", "at", "icon", "open"]),
TagRule::new("textbox", &["page"]).key("id").required(&["rect", "text"]).attrs(&["id", "author", "text", "color", "opacity", "date", "rect", "size", "textColor", "border", "fill", "align"]),
TagRule::new("ink", &["page"]).key("id").required(&["strokes"]).attrs(&["id", "author", "text", "color", "opacity", "date", "strokes", "width"]),
TagRule::new("rectangle", &["page"]).key("id").required(&["rect"]).attrs(&["id", "author", "text", "color", "opacity", "date", "rect", "width", "fill"]),
TagRule::new("ellipse", &["page"]).key("id").required(&["rect"]).attrs(&["id", "author", "text", "color", "opacity", "date", "rect", "width", "fill"]),
TagRule::new("line", &["page"]).key("id").required(&["from", "to"]).attrs(&["id", "author", "text", "color", "opacity", "date", "from", "to", "width", "arrow"]),
TagRule::new("polygon", &["page"]).key("id").required(&["points"]).attrs(&["id", "author", "text", "color", "opacity", "date", "points", "width", "fill"]),
TagRule::new("polyline", &["page"]).key("id").required(&["points"]).attrs(&["id", "author", "text", "color", "opacity", "date", "points", "width"]),
TagRule::new("stamp", &["page"]).key("id").required(&["rect"]).attrs(&["id", "author", "text", "color", "opacity", "date", "rect", "name", "label", "image"]),
TagRule::new("signature", &["page"]).key("id").required(&["rect"]).attrs(&["id", "author", "rect", "typed", "style", "image", "strokes", "color", "width"]),
TagRule::new("redact", &["page"]).key("id").required(&["rect"]).attrs(&["id", "rect", "fill", "overlay"]),
TagRule::new("field", &["page"]).key("id").required(&["kind", "name"]).attrs(&["id", "kind", "name", "rect", "rects", "value", "options", "checked", "multiline", "maxLength", "required", "readOnly", "tooltip", "default", "editable", "size"]),
TagRule::new("reply", &["note"]).required(&["text"]).attrs(&["text", "author", "date", "state"]),
TagRule::new("fill", &["pdf"]).key("name").required(&["name", "value"]).attrs(&["name", "value"]),
TagRule::new("bookmark", &["pdf", "bookmark"]).key("id").required(&["title"]).attrs(BOOKMARK_FIELDS),
TagRule::new("label", &["pdf"]).required(&["from"]).attrs(LABEL_FIELDS),
TagRule::new("attach", &["pdf"]).required(&["src"]).attrs(ATTACH_FIELDS),
TagRule::new("header", &["pdf"]).attrs(BAND_FIELDS),
TagRule::new("footer", &["pdf"]).attrs(BAND_FIELDS),
TagRule::new("bates", &["pdf"]).attrs(BATES_FIELDS),
],
from_tree: pdf_of,
};
fn declare(root: El) -> Result<Declared, String> {
declare_document(&root, &PDF)
}
fn num(v: Option<&Json>) -> Option<f64> {
v.and_then(|v| v.as_f64()).filter(|n| n.is_finite())
}
fn is_int(v: Option<&Json>) -> bool {
num(v).is_some_and(|n| n.fract() == 0.0)
}
fn nums(v: &Json, len: Option<usize>) -> bool {
matches!(v, Json::Arr(a) if len.is_none_or(|l| a.len() == l) && a.iter().all(|x| x.as_f64().is_some_and(f64::is_finite)))
}
fn rect(v: Option<&Json>) -> bool {
v.is_some_and(|v| nums(v, Some(4)))
}
fn color(v: &Json) -> bool {
nums(v, Some(3)) && matches!(v, Json::Arr(a) if a.iter().all(|x| x.as_f64().is_some_and(|n| (0.0..=1.0).contains(&n))))
}
fn own(t: &DocTree, keys: &[&str]) -> Json {
let mut out = Json::obj();
for k in keys {
if let Some(v) = t.attr_of(k) {
out.set(k, v.clone());
}
}
out
}
fn check_mark(c: &DocTree) -> Result<(), String> {
let w = format!("{}()", c.tag);
if c.attr_of("rect").is_some() && !rect(c.attr_of("rect")) {
return Err(format!("{w}: rect is [x0, y0, x1, y1] in points"));
}
if let Some(r) = c.attr_of("rects") {
if !matches!(r, Json::Arr(a) if !a.is_empty() && a.iter().all(|x| nums(x, Some(4)))) {
return Err(format!("{w}: rects is a list of [x0, y0, x1, y1]"));
}
}
for k in ["at", "from", "to"] {
if c.attr_of(k).is_some_and(|v| !nums(v, Some(2))) {
return Err(format!("{w}: {k} is [x, y] in points"));
}
}
for k in ["color", "textColor"] {
if c.attr_of(k).is_some_and(|v| !color(v)) {
return Err(format!("{w}: {k} is [r, g, b], each 0 to 1"));
}
}
for k in ["fill", "border"] {
if c.attr_of(k).is_some_and(|v| *v != Json::Null && !color(v)) {
return Err(format!("{w}: {k} is [r, g, b], each 0 to 1, or null"));
}
}
if c.attr_of("opacity").is_some() && !num(c.attr_of("opacity")).is_some_and(|n| (0.0..=1.0).contains(&n)) {
return Err(format!("{w}: opacity is 0 to 1"));
}
if let Some(s) = c.attr_of("strokes") {
if !matches!(s, Json::Arr(a) if a.iter().all(|x| nums(x, None) && matches!(x, Json::Arr(p) if p.len() >= 2 && p.len() % 2 == 0))) {
return Err(format!("{w}: strokes is a list of [x, y, x, y …]"));
}
}
if let Some(p) = c.attr_of("points") {
if !(nums(p, None) && matches!(p, Json::Arr(a) if a.len() >= 4 && a.len() % 2 == 0)) {
return Err(format!("{w}: points is [x, y, x, y …]"));
}
}
if c.attr_of("arrow").is_some_and(|a| !["none", "start", "end", "both"].contains(&a.as_str().unwrap_or(""))) {
return Err(format!(r#"{w}: arrow is "none", "start", "end" or "both""#));
}
if c.tag == "field" {
let kind = c.attr_of("kind").and_then(Json::as_str).unwrap_or("");
if !["text", "checkbox", "radio", "dropdown", "list", "signature"].contains(&kind) {
return Err(r#"field(): kind is "text", "checkbox", "radio", "dropdown", "list" or "signature""#.into());
}
if kind == "radio" {
let len = |k: &str| match c.attr_of(k) {
Some(Json::Arr(a)) => Some(a.len()),
_ => None,
};
if len("options").is_none() || len("options") != len("rects") {
return Err(r#"field(): kind "radio" has options and rects, one rect per option"#.into());
}
} else if !rect(c.attr_of("rect")) {
return Err("field(): rect is [x0, y0, x1, y1] in points".into());
}
}
if c.tag == "signature" && ["typed", "image", "strokes"].iter().filter(|k| c.attr_of(k).is_some()).count() != 1 {
return Err("signature(): is one of typed, image or strokes".into());
}
if c.tag == "stamp" && !["name", "image", "label"].iter().any(|k| c.attr_of(k).is_some()) {
return Err("stamp(): has a name (Approved, Draft …), a label or an image".into());
}
for k in ["text", "author", "name", "label", "image", "typed", "overlay", "tooltip"] {
if c.attr_of(k).is_some_and(|v| !matches!(v, Json::Str(_))) {
return Err(format!("{w}: {k} is text"));
}
}
for k in ["required", "readOnly", "multiline", "checked", "editable"] {
if c.attr_of(k).is_some_and(|v| !matches!(v, Json::Bool(_))) {
return Err(format!("{w}: {k} is true or false"));
}
}
if c.attr_of("default").is_some_and(|v| !matches!(v, Json::Str(_)) && !matches!(v, Json::Arr(a) if a.iter().all(|x| matches!(x, Json::Str(_))))) {
return Err(format!("{w}: default is text, or a list of texts"));
}
for r in c.children.iter().filter(|r| r.tag == "reply") {
if r.attr_of("state").is_some_and(|s| !REVIEW_STATES.contains(&s.as_str().unwrap_or(""))) {
return Err(r#"reply(): state is "Accepted", "Rejected", "Cancelled", "Completed" or "None""#.into());
}
}
Ok(())
}
fn check_page(p: &DocTree) -> Result<(), String> {
if let Some(src) = p.attr_of("src") {
if !matches!(src, Json::Str(s) if !s.is_empty()) {
return Err("page(): src is the ref of a PDF".into());
}
if !(is_int(p.attr_of("n")) && num(p.attr_of("n")).unwrap_or(0.0) >= 1.0) {
return Err("page(): n is the page's number in src, from 1".into());
}
if ["size", "width", "height"].iter().any(|k| p.attr_of(k).is_some()) {
return Err("page(): is a page of src, or a blank page of a size: not both".into());
}
} else {
if p.attr_of("n").is_some() {
return Err("page(): n is the page number in src".into());
}
match p.attr_of("size") {
Some(s) if !PAGE_SIZES.contains(&s.as_str().unwrap_or("")) => return Err(format!("page(): size is {}", PAGE_SIZES.join(", "))),
None if !(num(p.attr_of("width")).is_some_and(|w| w > 0.0) && num(p.attr_of("height")).is_some_and(|h| h > 0.0)) => {
return Err("page(): is a page of a PDF (src and n) or a blank page (size, or width and height in points)".into())
}
_ => {}
}
}
if p.attr_of("rotate").is_some() && !(is_int(p.attr_of("rotate")) && num(p.attr_of("rotate")).unwrap_or(1.0) % 90.0 == 0.0) {
return Err("page(): rotate is a multiple of 90".into());
}
p.children.iter().try_for_each(check_mark)
}
fn check_band(t: &DocTree) -> Result<(), String> {
let w = format!("{}()", t.tag);
if t.tag != "bates" && !["left", "center", "right"].iter().any(|k| matches!(t.attr_of(k), Some(Json::Str(s)) if !s.trim().is_empty())) {
return Err(format!("{w}: has text in left, center or right"));
}
for k in ["left", "center", "right", "pages", "date", "prefix", "suffix"] {
if t.attr_of(k).is_some_and(|v| !matches!(v, Json::Str(_))) {
return Err(format!("{w}: {k} is text"));
}
}
for k in ["size", "margin", "inset"] {
if t.attr_of(k).is_some() && !num(t.attr_of(k)).is_some_and(|n| n >= 0.0) {
return Err(format!("{w}: {k} is points, 0 or more"));
}
}
if t.attr_of("color").is_some_and(|v| !color(v)) {
return Err(format!("{w}: color is [r, g, b], each 0 to 1"));
}
if t.attr_of("family").is_some_and(|f| !["sans", "serif", "mono"].contains(&f.as_str().unwrap_or(""))) {
return Err(format!(r#"{w}: family is "sans", "serif" or "mono""#));
}
if t.attr_of("start").is_some() && !(is_int(t.attr_of("start")) && num(t.attr_of("start")).unwrap_or(-1.0) >= 0.0) {
return Err(format!("{w}: start is a whole number"));
}
if t.attr_of("digits").is_some() && !(is_int(t.attr_of("digits")) && num(t.attr_of("digits")).is_some_and(|d| (1.0..=15.0).contains(&d))) {
return Err("bates(): digits is 1 to 15".into());
}
if t.attr_of("position").is_some_and(|p| !BATES_POSITIONS.contains(&p.as_str().unwrap_or(""))) {
return Err(format!("bates(): position is {}", BATES_POSITIONS.join(", ")));
}
Ok(())
}
fn bookmark_of(t: &DocTree) -> Result<Json, String> {
if !matches!(t.attr_of("title"), Some(Json::Str(_))) {
return Err("bookmark(): title is text".into());
}
if t.attr_of("page").is_some() && !(is_int(t.attr_of("page")) && num(t.attr_of("page")).unwrap_or(0.0) >= 1.0) {
return Err("bookmark(): page is a page number, from 1".into());
}
let mut b = own(t, BOOKMARK_FIELDS);
let kids = t.children.iter().filter(|c| c.tag == "bookmark").map(bookmark_of).collect::<Result<Vec<_>, _>>()?;
if !kids.is_empty() {
b.set("children", kids);
}
Ok(b)
}
fn pdf_of(t: &DocTree) -> Result<Json, String> {
for k in PDF_FIELDS {
if t.attr_of(k).is_some_and(|v| !matches!(v, Json::Str(_))) {
return Err(format!("pdf(): {k} is text"));
}
}
let (mut pages, mut fills, mut bookmarks, mut labels, mut attachments) = (vec![], vec![], vec![], vec![], vec![]);
let mut bands: Vec<(&str, Json)> = vec![];
for c in &t.children {
match c.tag {
"page" => {
check_page(c)?;
let mut page = own(c, PAGE_FIELDS);
let marks: Vec<Json> = c
.children
.iter()
.map(|m| {
let mut mark = Json::obj().with("type", m.tag);
for (k, v) in &m.attrs {
mark.set(k, v.clone());
}
let replies: Vec<Json> = m.children.iter().filter(|r| r.tag == "reply").map(DocTree::record).collect();
if !replies.is_empty() {
mark.set("replies", replies);
}
mark
})
.collect();
if !marks.is_empty() {
page.set("marks", marks);
}
pages.push(page);
}
"fill" => {
let ok = match c.attr_of("value") {
Some(Json::Str(_) | Json::Bool(_)) => true,
Some(Json::Arr(a)) => a.iter().all(|x| matches!(x, Json::Str(_))),
_ => false,
};
if !ok {
return Err("fill(): value is text, true or false, or a list of texts".into());
}
fills.push(own(c, &["name", "value"]));
}
"bookmark" => bookmarks.push(bookmark_of(c)?),
"label" => {
if !(is_int(c.attr_of("from")) && num(c.attr_of("from")).unwrap_or(0.0) >= 1.0) {
return Err("label(): from is a page number, from 1".into());
}
if c.attr_of("style").is_some_and(|s| !["D", "r", "R", "a", "A"].contains(&s.as_str().unwrap_or(""))) {
return Err(r#"label(): style is "D" (1 2 3), "r" (i ii), "R" (I II), "a" (a b) or "A" (A B)"#.into());
}
labels.push(own(c, LABEL_FIELDS));
}
"attach" => attachments.push(own(c, ATTACH_FIELDS)),
"header" | "footer" | "bates" => {
if bands.iter().any(|(t, _)| *t == c.tag) {
return Err(format!("pdf(): a PDF has one {}()", c.tag));
}
check_band(c)?;
bands.push((c.tag, own(c, if c.tag == "bates" { BATES_FIELDS } else { BAND_FIELDS })));
}
_ => {}
}
}
let mut out = own(t, PDF_FIELDS).with("pages", pages);
for (k, v) in [("fill", fills), ("bookmarks", bookmarks), ("labels", labels), ("attachments", attachments)] {
if !v.is_empty() {
out.set(k, v);
}
}
for tag in ["header", "footer", "bates"] {
if let Some((_, b)) = bands.iter().find(|(t, _)| *t == tag) {
out.set(tag, b.clone());
}
}
Ok(out)
}