mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-01 05:58:12 -06:00
Merge remote-tracking branch 'origin/main' into fix/background-hidden-by-page-backdrop
# Conflicts: # crates/ui-egui/src/commands.rs # crates/ui-egui/src/marks_ui.rs
This commit is contained in:
Generated
-2
@@ -2591,8 +2591,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
|
||||
@@ -115,6 +115,7 @@ hayro-interpret = { path = "vendor/hayro-interpret" }
|
||||
hayro = { path = "vendor/hayro" }
|
||||
hayro-syntax = { path = "vendor/hayro-syntax" }
|
||||
hayro-cmap = { path = "vendor/hayro-cmap" }
|
||||
hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
|
||||
lopdf = { path = "vendor/lopdf" }
|
||||
winit = { path = "vendor/winit" }
|
||||
|
||||
@@ -176,3 +176,7 @@ real_name = "Nick Nyssen"
|
||||
|
||||
[people.agent-reed]
|
||||
sync_github_name = true
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
+20
-14
@@ -211,6 +211,25 @@ fn close(marks: &mut Vec<Mark>, matching: &mut usize, out: &mut HashMap<i64, [f6
|
||||
draw(marks, b);
|
||||
}
|
||||
|
||||
/// The page-space box a `Do` operator paints: a form's transformed `/BBox`, or the unit square for an image.
|
||||
/// `None` when the operand is not a resolvable XObject or the form's box is malformed.
|
||||
fn xobject_bbox(doc: &Document, xobjects: &Dict, op: &pdfcraft_content::Op, top: &Matrix) -> Option<[f64; 4]> {
|
||||
let r = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref)?;
|
||||
Some(match &*doc.get(r) {
|
||||
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
|
||||
let bb: Vec<f64> =
|
||||
s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
|
||||
let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
|
||||
.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
|
||||
match bb[..] {
|
||||
[a, b, c, d] => m.then(top).bbox([a, b, c, d]),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
_ => top.bbox([0.0, 0.0, 1.0, 1.0]),
|
||||
})
|
||||
}
|
||||
|
||||
/// Where each of the marked content `ids` is drawn on a page (images, forms and paths), in one pass
|
||||
/// over the page. What a sequence draws counts for every sequence of `ids` around it too.
|
||||
pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> HashMap<i64, [f64; 4]> {
|
||||
@@ -274,20 +293,7 @@ pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) ->
|
||||
path.clear();
|
||||
}
|
||||
b"Do" if inside => {
|
||||
let Some(r) = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref) else { continue };
|
||||
let unit = match &*doc.get(r) {
|
||||
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
|
||||
let bb: Vec<f64> =
|
||||
s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
|
||||
let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
|
||||
.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
|
||||
match bb[..] {
|
||||
[a, b, c, d] => m.then(&top).bbox([a, b, c, d]),
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
_ => top.bbox([0.0, 0.0, 1.0, 1.0]),
|
||||
};
|
||||
let Some(unit) = xobject_bbox(doc, &xobjects, &op, &top) else { continue };
|
||||
draw(&mut marks, unit);
|
||||
}
|
||||
b"BI" if inside => draw(&mut marks, top.bbox([0.0, 0.0, 1.0, 1.0])),
|
||||
|
||||
+33
-27
@@ -132,6 +132,38 @@ fn harmless_inside(op: &[u8]) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The `(BT, ET)` operator index pairs of each text object that shows text, or why the page cannot be tagged.
|
||||
fn text_spans(ops: &[Op], index: usize) -> Result<Vec<(usize, usize)>, AutoTagError> {
|
||||
let mut start = None;
|
||||
let mut has_text = false;
|
||||
let mut spans = Vec::new();
|
||||
for (at, op) in ops.iter().enumerate() {
|
||||
match op.op.as_slice() {
|
||||
b"BT" if start.is_none() => {
|
||||
start = Some(at);
|
||||
has_text = false;
|
||||
}
|
||||
b"ET" => {
|
||||
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
|
||||
if has_text {
|
||||
spans.push((first, at));
|
||||
if spans.len() > MAX_TEXT_OBJECTS {
|
||||
return Err(unsupported(index, "too many text objects (maximum 4096)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
|
||||
name if start.is_some() && harmless_inside(name) => {}
|
||||
name if start.is_none() && harmless_outside(name) => {}
|
||||
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
|
||||
}
|
||||
}
|
||||
if start.is_some() {
|
||||
return Err(unsupported(index, "unterminated BT text object"));
|
||||
}
|
||||
Ok(spans)
|
||||
}
|
||||
|
||||
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
let root = doc.root().ok_or(AutoTagError::NoCatalog)?;
|
||||
let catalog = doc.get(root);
|
||||
@@ -163,33 +195,7 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
if parsed.skipped > 0 || parsed.ops.len() > MAX_OPERATORS {
|
||||
return Err(unsupported(index, "content has malformed or too many operators"));
|
||||
}
|
||||
let mut start = None;
|
||||
let mut has_text = false;
|
||||
let mut spans = Vec::new();
|
||||
for (at, op) in parsed.ops.iter().enumerate() {
|
||||
match op.op.as_slice() {
|
||||
b"BT" if start.is_none() => {
|
||||
start = Some(at);
|
||||
has_text = false;
|
||||
}
|
||||
b"ET" => {
|
||||
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
|
||||
if has_text {
|
||||
spans.push((first, at));
|
||||
if spans.len() > MAX_TEXT_OBJECTS {
|
||||
return Err(unsupported(index, "too many text objects (maximum 4096)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
|
||||
name if start.is_some() && harmless_inside(name) => {}
|
||||
name if start.is_none() && harmless_outside(name) => {}
|
||||
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
|
||||
}
|
||||
}
|
||||
if start.is_some() {
|
||||
return Err(unsupported(index, "unterminated BT text object"));
|
||||
}
|
||||
let spans = text_spans(&parsed.ops, index)?;
|
||||
total = total.saturating_add(spans.len());
|
||||
out.push(Plan { page: page.obj, ops: parsed.ops, spans });
|
||||
}
|
||||
|
||||
@@ -9,10 +9,12 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
|
||||
line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`).
|
||||
- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
|
||||
and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
|
||||
A line's leader lines (`/LL`, `/LLE`, `/LLO`) and caption (`/Cap`, `/CP`, `/CO`) are drawn as
|
||||
ISO 32000-2 Table 178 places them, the caption in black Helvetica 10.
|
||||
Note icons are PdfCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with
|
||||
line breaking by approximate Helvetica proportions (no font program is bundled). Text it can't
|
||||
draw (in a text box, callout, Fill & Sign text, measurement label or dynamic stamp's by-line;
|
||||
`appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
|
||||
draw (in a text box, callout, Fill & Sign text, line caption, measurement label or dynamic
|
||||
stamp's by-line; `appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
|
||||
the first such character (`pdfcraft_fonts::UNDRAWN_MARK`) so the engine reports the edit and
|
||||
flattening refuses to make it permanent. Two refusals (`AnnotError::Undrawable`): a redaction
|
||||
mark's overlay text, which becomes page content when applied; and a restyle or resize of a
|
||||
|
||||
@@ -302,13 +302,14 @@ fn text_turn(d: &Dict) -> i64 {
|
||||
|
||||
/// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that
|
||||
/// they can't, which would come out as `?`: what it is (for the message) and the character. The
|
||||
/// text of a text box, callout or Fill & Sign text, a measurement's label, a dynamic stamp's
|
||||
/// "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
|
||||
/// text of a text box, callout or Fill & Sign text, a line's caption, a measurement's label, a
|
||||
/// dynamic stamp's "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
|
||||
/// it can be drawn.
|
||||
pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
|
||||
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
|
||||
let (what, text) = match d.name(b"Subtype")? {
|
||||
b"FreeText" => ("the comment's text", text(b"Contents")?),
|
||||
b"Line" if !d.contains(b"PCMeasureValue") => ("the line's caption", line_caption(d)?),
|
||||
b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?),
|
||||
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?),
|
||||
// Drawn in Helvetica when the redaction is applied: refused when it is marked.
|
||||
@@ -389,6 +390,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
let w = border_width(d);
|
||||
let mut res = Dict::new();
|
||||
let mut c = String::new();
|
||||
// Content after `c` that isn't UTF-8 (WinAnsi text).
|
||||
let mut tail: Vec<u8> = Vec::new();
|
||||
let markup = matches!(subtype.as_slice(), b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly");
|
||||
if let Some(gs) = ext_gstate(opacity, subtype == b"Highlight") {
|
||||
res.set(b"ExtGState".to_vec(), Object::Dict(gs));
|
||||
@@ -513,13 +516,29 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
return None;
|
||||
}
|
||||
let fill = interior_color(d, Some(col)).unwrap_or(col);
|
||||
let layout = line_layout(d, [(l[0], l[1]), (l[2], l[3])], w);
|
||||
let [p, q] = layout.line;
|
||||
c.push_str(&format!("{}{}{} w 1 J 1 j\n{}", rg_stroke(col), rg(fill), n(w), dash(d)));
|
||||
c.push_str(&format!("{} {} m {} {} l S\n[] 0 d\n", n(l[0]), n(l[1]), n(l[2]), n(l[3])));
|
||||
for (end, (tip, from)) in ends.iter().zip([((l[0], l[1]), (l[2], l[3])), ((l[2], l[3]), (l[0], l[1]))]) {
|
||||
for [s, e] in layout.leaders.iter().chain(&layout.strokes).chain(&layout.tick) {
|
||||
c.push_str(&format!("{} {} m {} {} l S\n", n(s.0), n(s.1), n(e.0), n(e.1)));
|
||||
}
|
||||
c.push_str("[] 0 d\n");
|
||||
for (end, (tip, from)) in ends.iter().zip([(p, q), (q, p)]) {
|
||||
if !line_end(&mut c, end, tip, from, w) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Some((text, m)) = layout.caption {
|
||||
// The caption is black, in the standard font the measurement label uses.
|
||||
tail.extend(
|
||||
format!("q 0 g BT /Helv {} Tf {} {} {} {} {} {} Tm ", n(CAPTION_SIZE), n(m[0]), n(m[1]), n(m[2]), n(m[3]), n(m[4]), n(m[5]))
|
||||
.bytes(),
|
||||
);
|
||||
// WinAnsi bytes go into the stream as-is, not through UTF-8.
|
||||
tail.extend(literal(&win_ansi(&text)));
|
||||
tail.extend_from_slice(b" Tj ET Q\n");
|
||||
res.set(b"Font".to_vec(), helvetica_resource());
|
||||
}
|
||||
}
|
||||
b"Polygon" | b"PolyLine" => {
|
||||
let v = nums(d, b"Vertices").filter(|v| v.len() >= 4 && v.len() % 2 == 0 && v.iter().all(|x| x.is_finite()))?;
|
||||
@@ -866,6 +885,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
// PdfCraft measurement captions are kept separate from the comment's free-form text.
|
||||
// A restyle regenerates the path and its value together.
|
||||
let mut out = c.into_bytes();
|
||||
out.extend(tail);
|
||||
if let Some(value) = d.get(b"PCMeasureValue").and_then(Object::as_string) {
|
||||
let value = value.to_text();
|
||||
if value.chars().count() <= 256 && matches!(subtype.as_slice(), b"Line" | b"PolyLine" | b"Polygon") {
|
||||
@@ -969,6 +989,190 @@ pub(crate) fn display_stamp(d: &Dict) -> Option<Stream> {
|
||||
Some(form(rect, c.as_bytes(), res))
|
||||
}
|
||||
|
||||
/// Size of a line's caption, as of a measurement's label.
|
||||
const CAPTION_SIZE: f64 = 10.0;
|
||||
|
||||
/// Characters of a line's caption drawn at most, as for a measurement's label.
|
||||
const MAX_CAPTION_CHARS: usize = 256;
|
||||
|
||||
/// Leader lengths and caption offsets (Table 178) are held within this many points (200 inches,
|
||||
/// the largest page side ISO 32000-2 Annex C allows), so an absurd value can't overflow.
|
||||
const MAX_LINE_EXTENT: f64 = 14_400.0;
|
||||
|
||||
/// A Table 178 length or offset: finite and within [`MAX_LINE_EXTENT`], 0 when absent or not one.
|
||||
fn line_length(v: Option<f64>) -> f64 {
|
||||
v.filter(|v| v.is_finite()).map_or(0.0, |v| v.clamp(-MAX_LINE_EXTENT, MAX_LINE_EXTENT))
|
||||
}
|
||||
|
||||
/// The caption a Line with `/Cap true` shows (ISO 32000-2 Table 178): its `/Contents`, else the
|
||||
/// plain text of its `/RC`, on one line and cut to [`MAX_CAPTION_CHARS`]. `None` without a
|
||||
/// caption, and for PdfCraft's own measurements, whose label (`/PCMeasureValue`) is the caption.
|
||||
fn line_caption(d: &Dict) -> Option<String> {
|
||||
if !matches!(d.get(b"Cap"), Some(Object::Bool(true))) || d.contains(b"PCMeasureValue") {
|
||||
return None;
|
||||
}
|
||||
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
|
||||
let raw = text(b"Contents").filter(|t| !t.trim().is_empty()).or_else(|| text(b"RC").map(|rc| rich_plain(&rc)))?;
|
||||
let words: Vec<&str> = raw.split_whitespace().collect();
|
||||
let caption: String = words.join(" ").chars().filter(|c| !c.is_control()).take(MAX_CAPTION_CHARS).collect();
|
||||
(!caption.is_empty()).then_some(caption)
|
||||
}
|
||||
|
||||
/// The text of rich text (§12.7.4.3, XHTML): its markup dropped, the five XML entities and
|
||||
/// numeric character references read, block ends read as spaces.
|
||||
fn rich_plain(rc: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut tag: Option<String> = None;
|
||||
// Rich text past this is not caption material; it bounds the work.
|
||||
for ch in rc.chars().take(MAX_CAPTION_CHARS * 64) {
|
||||
match (&mut tag, ch) {
|
||||
(None, '<') => tag = Some(String::new()),
|
||||
(Some(name), '>') => {
|
||||
let name =
|
||||
name.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or_default().to_ascii_lowercase();
|
||||
if matches!(name.as_str(), "p" | "br" | "div" | "li") {
|
||||
out.push(' ');
|
||||
}
|
||||
tag = None;
|
||||
}
|
||||
(Some(name), c) => {
|
||||
if name.len() < 16 {
|
||||
name.push(c);
|
||||
}
|
||||
}
|
||||
(None, c) => out.push(c),
|
||||
}
|
||||
}
|
||||
let mut text = String::new();
|
||||
let mut rest = out.as_str();
|
||||
while let Some(at) = rest.find('&') {
|
||||
text.push_str(rest.get(..at).unwrap_or_default());
|
||||
let after = rest.get(at + 1..).unwrap_or_default();
|
||||
let entity = after.find(';').filter(|&end| end <= 10).and_then(|end| Some((after.get(..end)?, end)));
|
||||
let decoded = entity.and_then(|(name, end)| {
|
||||
let c = match name {
|
||||
"amp" => '&',
|
||||
"lt" => '<',
|
||||
"gt" => '>',
|
||||
"quot" => '"',
|
||||
"apos" => '\'',
|
||||
_ => {
|
||||
let num = name.strip_prefix('#')?;
|
||||
let code = match num.strip_prefix(['x', 'X']) {
|
||||
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
|
||||
None => num.parse().ok()?,
|
||||
};
|
||||
char::from_u32(code)?
|
||||
}
|
||||
};
|
||||
Some((c, end))
|
||||
});
|
||||
match decoded {
|
||||
Some((c, end)) => {
|
||||
text.push(c);
|
||||
rest = after.get(end + 1..).unwrap_or_default();
|
||||
}
|
||||
None => {
|
||||
text.push('&');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
text.push_str(rest);
|
||||
text
|
||||
}
|
||||
|
||||
/// Where a Line annotation's parts go (ISO 32000-2 §12.5.6.7, Table 178).
|
||||
#[derive(Debug, Default)]
|
||||
struct LineLayout {
|
||||
/// The line itself, start to end: `/L`, or `/L` moved out by its leader lines.
|
||||
line: [(f64, f64); 2],
|
||||
/// Strokes along the line: the whole line, or the two pieces either side of an inline caption.
|
||||
strokes: Vec<[(f64, f64); 2]>,
|
||||
/// The leader lines, from `/L` (past the `/LLO` gap) to the line and on by `/LLE`.
|
||||
leaders: Vec<[(f64, f64); 2]>,
|
||||
/// A short stroke from the line to a caption `/CO` moved off it.
|
||||
tick: Option<[(f64, f64); 2]>,
|
||||
/// The caption and its text matrix.
|
||||
caption: Option<(String, [f64; 6])>,
|
||||
}
|
||||
|
||||
/// Lay out a Line annotation from `/L` = `[a b]`, line width `w`, and its leader and caption
|
||||
/// entries.
|
||||
///
|
||||
/// Leader lines: a positive `/LL` puts the line on the left of travel from `a` to `b` (above `/L`
|
||||
/// for a line drawn left to right), so the leader lines, followed from the line to `/L`, turn
|
||||
/// clockwise from the direction of travel; a negative one puts it on the right. The line sits
|
||||
/// `|LL| + LLO` from `/L`. `/LLE` and `/LLO` are non-negative: a negative one counts as 0.
|
||||
///
|
||||
/// Caption (`/Cap true`): centred on the line's midpoint and turned with it so it reads left to
|
||||
/// right (bottom to top for a vertical line). `/CP /Inline` (the default) centres it on the line,
|
||||
/// which is broken around it; `/Top` sets it on top of the unbroken line. `/CO [h v]` moves it `h`
|
||||
/// along the line and `v` across it (positive: up in reading direction); a caption moved off an
|
||||
/// inline line gets a tick from the line to it.
|
||||
///
|
||||
/// A zero-length or overflowing `/L` has no direction: it gets neither leader lines nor caption.
|
||||
/// Every point is finite; if anything derived from the entries is not, they are left out.
|
||||
fn line_layout(d: &Dict, [a, b]: [(f64, f64); 2], w: f64) -> LineLayout {
|
||||
let plain = LineLayout { line: [a, b], strokes: vec![[a, b]], ..LineLayout::default() };
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let len = dx.hypot(dy);
|
||||
if !len.is_finite() || len <= 0.0 {
|
||||
return plain;
|
||||
}
|
||||
let (ux, uy) = (dx / len, dy / len);
|
||||
let mut out = LineLayout { line: [a, b], ..LineLayout::default() };
|
||||
let ll = line_length(d.get(b"LL").and_then(Object::as_f64));
|
||||
if ll != 0.0 {
|
||||
// The unit normal from `/L` towards the line: left of travel for a positive /LL.
|
||||
let s = ll.signum();
|
||||
let (nx, ny) = (-uy * s, ux * s);
|
||||
let llo = line_length(d.get(b"LLO").and_then(Object::as_f64)).max(0.0);
|
||||
let lle = line_length(d.get(b"LLE").and_then(Object::as_f64)).max(0.0);
|
||||
let at = |p: (f64, f64), k: f64| (p.0 + nx * k, p.1 + ny * k);
|
||||
let off = ll.abs() + llo;
|
||||
out.line = [at(a, off), at(b, off)];
|
||||
out.leaders = vec![[at(a, llo), at(a, off + lle)], [at(b, llo), at(b, off + lle)]];
|
||||
}
|
||||
let [p, _] = out.line;
|
||||
let along = |t: f64| (p.0 + ux * t, p.1 + uy * t);
|
||||
let mut gap = None;
|
||||
if let Some(text) = line_caption(d) {
|
||||
let size = CAPTION_SIZE;
|
||||
let width = text_width(&text, size);
|
||||
// Reading direction, and "up" across it.
|
||||
let (tx, ty) = if ux < 0.0 || (ux == 0.0 && uy < 0.0) { (-ux, -uy) } else { (ux, uy) };
|
||||
let (vx, vy) = (-ty, tx);
|
||||
let co = nums(d, b"CO").filter(|c| c.len() == 2).unwrap_or_default();
|
||||
let h = line_length(co.first().copied());
|
||||
let v = line_length(co.get(1).copied());
|
||||
let top = d.name(b"CP") == Some(b"Top");
|
||||
// The caption's centre, as a distance along the line from `p`.
|
||||
let centre = len / 2.0 + h * (tx * ux + ty * uy);
|
||||
let mid = along(centre);
|
||||
// Baseline across the line: on top of it, or with the text centred on it.
|
||||
let base = if top { w.max(0.0) / 2.0 + 2.0 + v } else { v - size * 0.35 };
|
||||
let origin = (mid.0 - tx * width / 2.0 + vx * base, mid.1 - ty * width / 2.0 + vy * base);
|
||||
out.caption = Some((text, [tx, ty, -ty, tx, origin.0, origin.1]));
|
||||
if !top && v.abs() < size / 2.0 {
|
||||
let half = width / 2.0 + 2.0;
|
||||
gap = Some(((centre - half).clamp(0.0, len), (centre + half).clamp(0.0, len)));
|
||||
} else if !top {
|
||||
let reach = v - v.signum() * size * 0.4;
|
||||
out.tick = Some([mid, (mid.0 + vx * reach, mid.1 + vy * reach)]);
|
||||
}
|
||||
}
|
||||
out.strokes = match gap {
|
||||
Some((g0, g1)) => [(0.0, g0), (g1, len)].into_iter().filter(|(s, e)| e > s).map(|(s, e)| [along(s), along(e)]).collect(),
|
||||
None => vec![out.line],
|
||||
};
|
||||
let finite = |q: &(f64, f64)| q.0.is_finite() && q.1.is_finite();
|
||||
let all_finite =
|
||||
out.line.iter().chain(out.strokes.iter().flatten()).chain(out.leaders.iter().flatten()).chain(out.tick.iter().flatten()).all(finite)
|
||||
&& out.caption.as_ref().is_none_or(|(_, m)| m.iter().all(|x| x.is_finite()));
|
||||
if all_finite { out } else { plain }
|
||||
}
|
||||
|
||||
/// A rubber stamp: a rounded frame (a pointed tag for sign-here stamps) with the label in bold
|
||||
/// capitals, and the dynamic stamps' "By … at …" line.
|
||||
fn stamp(label: &str, sign_here: bool, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
|
||||
|
||||
@@ -1867,3 +1867,230 @@ fn a_caret_with_a_paragraph_symbol_draws_the_pilcrow() {
|
||||
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
|
||||
assert!(appearance::build(&d).is_some());
|
||||
}
|
||||
|
||||
// ── Line annotations: leader lines and captions (ISO 32000-2 §12.5.6.7, Table 178) ──────────
|
||||
|
||||
/// A red Line from `l` with a 1 pt border, a generous `/Rect`, and `extra` entries.
|
||||
fn table_178_line(l: [f64; 4], extra: &[(&str, Object)]) -> Dict {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Subtype".to_vec(), Object::name("Line"));
|
||||
d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 600.0, 800.0].map(Object::Real).to_vec()));
|
||||
d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
|
||||
d.set(b"L".to_vec(), Object::Array(l.map(Object::Real).to_vec()));
|
||||
for (k, v) in extra {
|
||||
d.set(k.as_bytes().to_vec(), v.clone());
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The built appearance's content.
|
||||
fn line_drawing(d: &Dict) -> String {
|
||||
let s = crate::appearance::build(d).expect("the line is drawn");
|
||||
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
|
||||
}
|
||||
|
||||
/// Every straight two-point stroke (`x0 y0 m x1 y1 l S`) in a drawing.
|
||||
fn segments(content: &str) -> Vec<[f64; 4]> {
|
||||
content
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let t: Vec<&str> = line.split_whitespace().collect();
|
||||
if t.len() != 7 || t[2] != "m" || t[5] != "l" || t[6] != "S" {
|
||||
return None;
|
||||
}
|
||||
let v: Vec<f64> = [t[0], t[1], t[3], t[4]].iter().map(|x| x.parse().unwrap()).collect();
|
||||
Some([v[0], v[1], v[2], v[3]])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The caption's text matrix (`a b c d e f Tm`), if any.
|
||||
fn caption_matrix(content: &str) -> Option<[f64; 6]> {
|
||||
let at = content.find(" Tm")?;
|
||||
let before: Vec<f64> = content[..at].split_whitespace().rev().take(6).map(|x| x.parse().unwrap()).collect();
|
||||
Some([before[5], before[4], before[3], before[2], before[1], before[0]])
|
||||
}
|
||||
|
||||
fn has(segs: &[[f64; 4]], want: [f64; 4]) -> bool {
|
||||
segs.iter().any(|s| s.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positive_leader_length_puts_the_line_above_a_left_to_right_line_and_a_negative_one_below() {
|
||||
let up = segments(&line_drawing(&table_178_line([72.0, 620.0, 272.0, 620.0], &[("LL", Object::Real(20.0))])));
|
||||
assert!(has(&up, [72.0, 640.0, 272.0, 640.0]), "the line is 20 above /L: {up:?}");
|
||||
assert!(has(&up, [72.0, 620.0, 72.0, 640.0]) && has(&up, [272.0, 620.0, 272.0, 640.0]), "leader lines from /L up to it: {up:?}");
|
||||
assert!(!has(&up, [72.0, 620.0, 272.0, 620.0]), "nothing along /L itself: {up:?}");
|
||||
|
||||
let down = segments(&line_drawing(&table_178_line([72.0, 540.0, 272.0, 540.0], &[("LL", Object::Real(-20.0)), ("LLE", Object::Real(10.0))])));
|
||||
assert!(has(&down, [72.0, 520.0, 272.0, 520.0]), "the line is 20 below /L: {down:?}");
|
||||
assert!(has(&down, [72.0, 540.0, 72.0, 510.0]) && has(&down, [272.0, 540.0, 272.0, 510.0]), "leaders run 10 past it: {down:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leader_offset_leaves_a_gap_and_the_endings_sit_on_the_line_itself() {
|
||||
let d = table_178_line(
|
||||
[72.0, 460.0, 272.0, 460.0],
|
||||
&[("LL", Object::Real(20.0)), ("LLO", Object::Real(10.0)), ("LE", Object::Array(vec![Object::name("OpenArrow"), Object::name("OpenArrow")]))],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
let segs = segments(&content);
|
||||
assert!(has(&segs, [72.0, 490.0, 272.0, 490.0]), "the line sits |LL| + LLO above /L: {segs:?}");
|
||||
assert!(has(&segs, [72.0, 470.0, 72.0, 490.0]) && has(&segs, [272.0, 470.0, 272.0, 490.0]), "leaders start LLO from /L: {segs:?}");
|
||||
// The open arrows' tips (`tip l`) are at the ends of the line, not of /L.
|
||||
assert!(content.contains(" 72 490 l ") && content.contains(" 272 490 l "), "arrows at the moved line: {content}");
|
||||
assert!(!content.contains(" 72 460 l "), "no arrow on /L: {content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_caption_breaks_the_line_around_its_text() {
|
||||
let d =
|
||||
table_178_line([72.0, 380.0, 272.0, 380.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("Inline 50 mm")))]);
|
||||
let content = line_drawing(&d);
|
||||
assert!(content.contains("(Inline 50 mm) Tj"), "the caption is drawn: {content}");
|
||||
assert!(content.contains("/Helv 10 Tf"), "in Helvetica 10: {content}");
|
||||
let m = caption_matrix(&content).expect("text matrix");
|
||||
let width = crate::appearance::text_width("Inline 50 mm", 10.0);
|
||||
assert!((m[4] - (172.0 - width / 2.0)).abs() < 0.01 && m[5] < 380.0 && m[5] > 380.0 - 10.0, "centred on the line: {m:?}");
|
||||
let segs = segments(&content);
|
||||
assert_eq!(segs.len(), 2, "two pieces: {segs:?}");
|
||||
assert!(segs.iter().all(|s| s[2] <= 172.0 - width / 2.0 || s[0] >= 172.0 + width / 2.0), "no stroke under the text: {segs:?}");
|
||||
assert!(has(&segs, [72.0, 380.0, 172.0 - width / 2.0 - 2.0, 380.0]), "the left piece starts at the line's start: {segs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_caption_sits_above_the_unbroken_line() {
|
||||
let d = table_178_line(
|
||||
[72.0, 300.0, 272.0, 300.0],
|
||||
&[("Cap", Object::Bool(true)), ("CP", Object::name("Top")), ("Contents", Object::String(PdfString::text("Top 50 mm")))],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
let m = caption_matrix(&content).expect("text matrix");
|
||||
assert!(m[5] > 300.0 && m[5] < 305.0, "baseline just above the line: {m:?}");
|
||||
assert_eq!(segments(&content), vec![[72.0, 300.0, 272.0, 300.0]], "the line is whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caption_offset_moves_it_along_and_off_the_line_with_a_tick() {
|
||||
let co = |h: f64, v: f64| Object::Array(vec![Object::Real(h), Object::Real(v)]);
|
||||
let text = ("Contents", Object::String(PdfString::text("Offset 15")));
|
||||
let base = caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), text.clone()]))).unwrap();
|
||||
let content = line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(0.0, 15.0)), text.clone()]));
|
||||
let up = caption_matrix(&content).unwrap();
|
||||
assert!((up[5] - base[5] - 15.0).abs() < 0.01 && (up[4] - base[4]).abs() < 0.01, "15 up: {base:?} → {up:?}");
|
||||
let segs = segments(&content);
|
||||
assert!(has(&segs, [330.0, 700.0, 530.0, 700.0]), "a caption off the line leaves it whole: {segs:?}");
|
||||
assert!(segs.iter().any(|s| s[0] == 430.0 && s[2] == 430.0 && s[1] == 700.0 && s[3] > 705.0), "a tick from the midpoint up: {segs:?}");
|
||||
let along =
|
||||
caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(-30.0, 0.0)), text])))
|
||||
.unwrap();
|
||||
assert!((along[4] - base[4] + 30.0).abs() < 0.01 && (along[5] - base[5]).abs() < 0.01, "30 left: {base:?} → {along:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_cap_true_no_caption_is_drawn() {
|
||||
for cap in [None, Some(Object::Bool(false)), Some(Object::Int(1))] {
|
||||
let mut extra = vec![("Contents", Object::String(PdfString::text("Hidden caption")))];
|
||||
if let Some(c) = cap.clone() {
|
||||
extra.push(("Cap", c));
|
||||
}
|
||||
let d = table_178_line([330.0, 620.0, 530.0, 620.0], &extra);
|
||||
let content = line_drawing(&d);
|
||||
assert!(!content.contains("Tj"), "{cap:?}: {content}");
|
||||
assert_eq!(segments(&content), vec![[330.0, 620.0, 530.0, 620.0]]);
|
||||
assert!(crate::appearance::undrawable_text(&d).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_diagonal_lines_leaders_are_perpendicular_and_its_caption_turns_with_it() {
|
||||
let d = table_178_line(
|
||||
[330.0, 460.0, 530.0, 560.0],
|
||||
&[
|
||||
("LL", Object::Real(20.0)),
|
||||
("LLE", Object::Real(10.0)),
|
||||
("Cap", Object::Bool(true)),
|
||||
("Contents", Object::String(PdfString::text("Diagonal"))),
|
||||
],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
let segs = segments(&content);
|
||||
let (ux, uy) = (200.0 / 100f64.hypot(200.0), 100.0 / 100f64.hypot(200.0));
|
||||
let leaders: Vec<&[f64; 4]> = segs.iter().filter(|s| (s[2] - s[0]) * ux + (s[3] - s[1]) * uy < 1e-2).collect();
|
||||
assert_eq!(leaders.len(), 2, "two leader lines across the line: {segs:?}");
|
||||
for l in leaders {
|
||||
let (dx, dy) = (l[2] - l[0], l[3] - l[1]);
|
||||
assert!((dx.hypot(dy) - 30.0).abs() < 0.01, "|LL| + LLE long: {l:?}");
|
||||
assert!(dx < 0.0 && dy > 0.0, "up and to the left (left of travel): {l:?}");
|
||||
}
|
||||
let m = caption_matrix(&content).expect("caption");
|
||||
assert!((m[0] - ux).abs() < 1e-3 && (m[1] - uy).abs() < 1e-3, "the text runs along the line: {m:?}");
|
||||
// Drawn right to left, it still reads left to right.
|
||||
let back = caption_matrix(&line_drawing(&table_178_line(
|
||||
[530.0, 560.0, 330.0, 460.0],
|
||||
&[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("x")))],
|
||||
)))
|
||||
.unwrap();
|
||||
assert!(back[0] > 0.0, "{back:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caption_from_rich_text_and_one_the_font_cant_draw() {
|
||||
let rc = "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\"><p>Dim & <b>5</b>0 mm <x></p></body>";
|
||||
let d = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("RC", Object::String(PdfString::text(rc)))]);
|
||||
let s = crate::appearance::build(&d).unwrap().decoded().unwrap();
|
||||
assert!(s.windows(17).any(|w| w == b"(Dim & 50 mm <x>)"), "{}", String::from_utf8_lossy(&s));
|
||||
let cjk = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("長さ")))]);
|
||||
assert_eq!(crate::appearance::undrawable_text(&cjk), Some(("the line's caption", '長')));
|
||||
// A PdfCraft measurement's label is its caption: the comment text isn't drawn a second time.
|
||||
let mut measured = cjk.clone();
|
||||
measured.set(b"PCMeasureValue".to_vec(), Object::String(PdfString::text("5 mm")));
|
||||
assert_eq!(crate::appearance::undrawable_text(&measured), None);
|
||||
let content = line_drawing(&measured);
|
||||
assert_eq!(content.matches(" Tj").count(), 1, "{content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_and_absurd_leader_and_caption_values_do_not_panic() {
|
||||
let cap = ("Cap", Object::Bool(true));
|
||||
let text = ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))));
|
||||
// A zero-length line has no direction: no leader lines, no caption, no NaN.
|
||||
let point =
|
||||
line_drawing(&table_178_line([50.0, 50.0, 50.0, 50.0], &[("LL", Object::Real(20.0)), ("LLE", Object::Real(5.0)), cap.clone(), text.clone()]));
|
||||
assert!(!point.contains("NaN") && !point.contains("inf") && !point.contains("Tj"), "{point}");
|
||||
assert_eq!(segments(&point).len(), 1);
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1e300, f64::MAX] {
|
||||
let d = table_178_line(
|
||||
[0.0, 0.0, 100.0, 0.0],
|
||||
&[
|
||||
("LL", Object::Real(bad)),
|
||||
("LLE", Object::Real(bad)),
|
||||
("LLO", Object::Real(bad)),
|
||||
("CO", Object::Array(vec![Object::Real(bad), Object::Real(bad)])),
|
||||
cap.clone(),
|
||||
text.clone(),
|
||||
],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
assert!(!content.contains("NaN") && !content.contains("inf"), "{bad}: {content}");
|
||||
for s in segments(&content) {
|
||||
assert!(s.iter().all(|x| x.abs() <= 50_000.0), "{bad}: {s:?}");
|
||||
}
|
||||
}
|
||||
// Negative LLE and LLO count as 0.
|
||||
let neg = segments(&line_drawing(&table_178_line(
|
||||
[0.0, 0.0, 100.0, 0.0],
|
||||
&[("LL", Object::Real(10.0)), ("LLE", Object::Real(-5.0)), ("LLO", Object::Real(-5.0))],
|
||||
)));
|
||||
assert!(has(&neg, [0.0, 0.0, 0.0, 10.0]) && has(&neg, [0.0, 10.0, 100.0, 10.0]), "{neg:?}");
|
||||
// Huge endpoints whose midpoint would overflow fall back to the plain line.
|
||||
let huge = line_drawing(&table_178_line([f64::MAX, f64::MAX, f64::MAX / 2.0, f64::MAX], &[("LL", Object::Real(20.0)), cap, text]));
|
||||
assert!(!huge.contains("NaN") && !huge.contains("inf"), "{huge}");
|
||||
// The caption is cut to 256 characters.
|
||||
let long = line_drawing(&table_178_line(
|
||||
[0.0, 0.0, 100.0, 0.0],
|
||||
&[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))))],
|
||||
));
|
||||
assert!(long.contains(&format!("({}) Tj", "w".repeat(256))), "cut to 256");
|
||||
assert!(!long.contains(&"w".repeat(257)));
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ its undo/redo history.
|
||||
- For proportional image signature resizing, use the embedded image layer's width/height ratio rather than a previously stretched annotation rectangle. The GUI preserves this ratio at corners with the opposite corner anchored; edge midpoint handles change only their own axis. `comment_edit` accepts the resulting rectangle.
|
||||
- `doc_close` refuses to drop unsaved changes unless `discard_changes: true`. `doc_save` writes atomically, incrementally in place, and in full for a new path. Atomic output writes call `sync_all` on the staging file before replacing the destination. A write or sync error leaves the destination intact, removes staging and leaves the document dirty for retry. A filesystem that does not support syncing returns an error; there is no unsynced fallback. This flushes file contents, but does not guarantee persistence of the parent-directory rename across power loss.
|
||||
- With a root set, every read and write path must resolve inside it (symlinks and `..` included). Relative paths resolve inside the root, and `..` is resolved by name before the check. Every path outside the root gets the same refusal (`<path> is outside the allowed directory <root>`), whether or not it exists, so a confined agent can't probe the rest of the disk; on Windows another network share or device path (`\\host\share`, `\\?\UNC\…`, `\\.\…`) is refused without being contacted. "Not found" and other filesystem errors are reported only for paths inside the root. Tools that write several files into a folder name them after the document or input file, with separators, colons and control characters replaced by `_`, so a name can't lead them out of the folder. The root itself must be a folder.
|
||||
- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. It applies on top of `with_root`.
|
||||
- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. As with a root set, on Windows a path on another network share or device path is refused with that refusal without being contacted (#4003). It applies on top of `with_root`.
|
||||
|
||||
## Text search and cache limits
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - A path on another network share or in a device namespace (`\\host\share`, `\\.\pipe\x`)
|
||||
//! than the root's is refused by name, before anything is resolved: resolving it would contact
|
||||
//! the host.
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
@@ -97,7 +100,10 @@ impl AutomationRoots {
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {shown}")),
|
||||
};
|
||||
};
|
||||
if inside(&resolve(shown, target)?, folder) {
|
||||
let absolute = absolute(shown, target)?;
|
||||
// Another network share or a device is refused by name, as `--root` refuses it: even
|
||||
// resolving the path would contact the host (#4003).
|
||||
if !foreign_share(&absolute, folder) && inside(&resolve(shown, &absolute)?, folder) {
|
||||
return Ok(());
|
||||
}
|
||||
let root = root_shown.display();
|
||||
@@ -123,9 +129,8 @@ fn plain(path: PathBuf) -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
/// `path` made absolute against the working directory, by name: nothing on disk is read.
|
||||
fn absolute(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
@@ -133,10 +138,15 @@ fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
|
||||
return Err(format!("automation path rejected: reserved device names are not allowed: {shown}"));
|
||||
}
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?;
|
||||
std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))
|
||||
}
|
||||
|
||||
/// `absolute` with its links followed; for a path that doesn't exist (yet), its nearest existing
|
||||
/// folder's links followed and the rest appended.
|
||||
fn resolve(shown: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute.as_path();
|
||||
let mut at = absolute;
|
||||
loop {
|
||||
match std::fs::canonicalize(at) {
|
||||
Ok(mut found) => {
|
||||
@@ -189,6 +199,24 @@ fn same_component(a: Component, b: Component) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` names another network share or device namespace than `root` (Windows
|
||||
/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
|
||||
/// that one exists would contact the host. Drive letters are left to the normal check.
|
||||
pub(crate) fn foreign_share(path: &Path, root: &Path) -> bool {
|
||||
use std::path::Prefix;
|
||||
fn share(p: &Path) -> Option<String> {
|
||||
let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
|
||||
let (kind, a, b) = match prefix.kind() {
|
||||
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
|
||||
Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
|
||||
Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
|
||||
Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
|
||||
};
|
||||
Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
|
||||
}
|
||||
share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
@@ -233,6 +261,27 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// #4003: another share or a device namespace is refused by name, with the same words as any
|
||||
/// other path outside the root, before anything is resolved (which would contact the host).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn other_shares_and_devices_are_refused_before_they_are_resolved() {
|
||||
let (base, roots) = folders("shares");
|
||||
for p in [
|
||||
r"\\.\pipe\pdfcraft-4003.pdf",
|
||||
r"\\?\GLOBALROOT\Device\Null",
|
||||
r"\\pdfcraft-no-such-host.invalid\share\a.pdf",
|
||||
"//pdfcraft-no-such-host.invalid/share/a.pdf",
|
||||
r"\\?\UNC\pdfcraft-no-such-host.invalid\share\a.pdf",
|
||||
] {
|
||||
let e = roots.check(p, Access::Read).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the read root"), "{p}: {e}");
|
||||
let e = roots.check(p, Access::Write).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the write root"), "{p}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sibling_with_the_same_prefix_is_outside() {
|
||||
let (base, roots) = folders("prefix");
|
||||
|
||||
@@ -106,6 +106,7 @@ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0;
|
||||
const FIND_FIRST_BATCH: usize = 8;
|
||||
const FIND_MAX_BATCH: usize = 128;
|
||||
|
||||
use file_access::foreign_share;
|
||||
use text_cache::TextCache;
|
||||
|
||||
type PageTexts = Vec<(usize, std::result::Result<Arc<PageText>, String>)>;
|
||||
@@ -2396,24 +2397,6 @@ fn lexical(path: &Path) -> Option<PathBuf> {
|
||||
Some(parts.iter().collect())
|
||||
}
|
||||
|
||||
/// Whether `path` names another network share or device namespace than `root` (Windows
|
||||
/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
|
||||
/// that one exists would contact the host. Drive letters are left to the normal check.
|
||||
fn foreign_share(path: &Path, root: &Path) -> bool {
|
||||
use std::path::{Component, Prefix};
|
||||
fn share(p: &Path) -> Option<String> {
|
||||
let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
|
||||
let (kind, a, b) = match prefix.kind() {
|
||||
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
|
||||
Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
|
||||
Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
|
||||
Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
|
||||
};
|
||||
Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
|
||||
}
|
||||
share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
|
||||
}
|
||||
|
||||
// ---- JSON helpers ----------------------------------------------------------------------------
|
||||
|
||||
fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::RangeStyle>> {
|
||||
@@ -2676,6 +2659,9 @@ fn info(d: &Document) -> Value {
|
||||
"creator": i.creator, "producer": i.producer,
|
||||
"tagged": i.tagged,
|
||||
"has_javascript": i.has_javascript,
|
||||
// Where the document opens (/OpenAction, named destinations resolved): 1-based page and
|
||||
// destination, null without one.
|
||||
"open_destination": i.open_dest.as_ref().map(|(p, view)| json!({ "page": page1(*p), "destination": i.pages.get(*p).and_then(|pg| destination(view, pg)) })),
|
||||
// XFA forms: "static" (the PDF's own fields work; the XFA data is ignored) or "dynamic"
|
||||
// (laid out from the template by PdfCraft, see xfa_layout; placeholder pages when that failed).
|
||||
"xfa": i.xfa.map(|x| match x { pdfcraft_render::Xfa::Static => "static", pdfcraft_render::Xfa::Dynamic => "dynamic" }),
|
||||
|
||||
@@ -139,7 +139,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.cmd("file.open")
|
||||
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
|
||||
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, attachments, fonts, security and repair notes.")
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security and repair notes.")
|
||||
.ro()
|
||||
.cmd("file.properties")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
|
||||
@@ -213,6 +213,49 @@ fn doc_info_lists_page_transitions_and_display_times() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `doc_info` says where the document opens: the `/OpenAction` destination, a named one
|
||||
/// resolved (ISO 32000-2 §12.3.2.4), as a 1-based page and a destination in view coordinates.
|
||||
#[test]
|
||||
fn doc_info_reports_the_open_destination() {
|
||||
let dir = workdir("open-destination");
|
||||
let write = |name: &str, catalog: &str| {
|
||||
let objects: Vec<String> = vec![
|
||||
format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R >>".into(),
|
||||
];
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join(name), bytes).unwrap();
|
||||
};
|
||||
write("named.pdf", "/OpenAction << /S /GoTo /D /there >> /Dests << /there [4 0 R /XYZ 100 500 2] >>");
|
||||
write("script.pdf", "/OpenAction << /S /JavaScript /JS (1) >>");
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "named.pdf" }))["doc"].as_u64().unwrap();
|
||||
let open = ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].clone();
|
||||
assert_eq!(open["page"], 2, "{open}");
|
||||
// y 500 is 292 points below the top of the 792-point page.
|
||||
assert_eq!(
|
||||
(open["destination"]["fit"].as_str(), open["destination"]["left"].as_f64(), open["destination"]["top"].as_f64()),
|
||||
(Some("XYZ"), Some(100.0), Some(292.0)),
|
||||
"{open}"
|
||||
);
|
||||
assert_eq!(open["destination"]["zoom"].as_f64(), Some(2.0));
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "script.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].is_null());
|
||||
}
|
||||
|
||||
/// Page transitions through the tools: set on chosen pages, written to the file as `/Trans` and
|
||||
/// `/Dur`, removed again, bad values refused, and one undo step. (Read through `pdfcraft_cos`,
|
||||
/// so this does not lean on `doc_info` listing them.)
|
||||
|
||||
@@ -352,6 +352,19 @@ fn links_out_of_a_root_are_refused() {
|
||||
assert_eq!(names(&base.join("outside")), ["pic.png", "secret.pdf"]);
|
||||
}
|
||||
|
||||
/// #4003: without `--root`, another network share or a device is refused by name through the
|
||||
/// tools too, with the same words as any other path outside a root.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn other_shares_and_devices_are_refused_by_name() {
|
||||
let (mut server, base) = confined("shares", true, true);
|
||||
ok(&mut server, "doc_open", json!({"path": s(&base.join("in/a.pdf"))}));
|
||||
for p in [r"\\.\pipe\pdfcraft-4003.pdf", r"\\pdfcraft-no-such-host.invalid\share\a.pdf", "//pdfcraft-no-such-host.invalid/share/a.pdf"] {
|
||||
refused(&mut server, "doc_open", json!({"path": p}), "outside the read root");
|
||||
refused(&mut server, "doc_save", json!({"doc": 1, "path": p}), "outside the write root");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_roots_nothing_is_confined() {
|
||||
let base = folders("none");
|
||||
|
||||
@@ -311,6 +311,35 @@ fn refine(q: [Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[
|
||||
order_quad(refined)
|
||||
}
|
||||
|
||||
/// A candidate quad's score (its area times the square of its sides' mean support), or `None` when it
|
||||
/// strays off the image, is too small, or has a side without enough edge support.
|
||||
fn quad_score(q: &[Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<f64> {
|
||||
let (fw, fh) = (w as f64, h as f64);
|
||||
let (mx, my) = (MARGIN * fw, MARGIN * fh);
|
||||
if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) {
|
||||
return None;
|
||||
}
|
||||
let area = (0..4)
|
||||
.map(|k| {
|
||||
let (p, n) = (q[k], q[(k + 1) % 4]);
|
||||
p[0] * n[1] - n[0] * p[1]
|
||||
})
|
||||
.sum::<f64>()
|
||||
.abs()
|
||||
/ 2.0;
|
||||
if area < MIN_AREA * fw * fh {
|
||||
return None;
|
||||
}
|
||||
let sides: Vec<f64> = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect();
|
||||
if sides.iter().any(|&s| s < MIN_SUPPORT) {
|
||||
return None;
|
||||
}
|
||||
// Large, and with every side on its edge: a slightly larger quad with a side
|
||||
// off the sheet loses to the sheet itself.
|
||||
let mean = sides.iter().sum::<f64>() / 4.0;
|
||||
Some(area * mean * mean)
|
||||
}
|
||||
|
||||
/// The convex quadrilateral of two near-horizontal and two near-vertical lines whose four sides
|
||||
/// all lie on edges, scored by its area times the square of its sides' mean support.
|
||||
fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[Point; 4]> {
|
||||
@@ -318,8 +347,6 @@ fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Opti
|
||||
let flat = |l: &&Line| (l.theta.to_degrees() - 90.0).abs() <= 45.0;
|
||||
let horizontal: Vec<&Line> = lines.iter().filter(flat).collect();
|
||||
let vertical: Vec<&Line> = lines.iter().filter(|l| !flat(l)).collect();
|
||||
let (fw, fh) = (w as f64, h as f64);
|
||||
let (mx, my) = (MARGIN * fw, MARGIN * fh);
|
||||
let mut best: Option<(f64, [Point; 4])> = None;
|
||||
for (i, &h1) in horizontal.iter().enumerate() {
|
||||
for &h2 in horizontal.iter().skip(i + 1) {
|
||||
@@ -328,28 +355,7 @@ fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Opti
|
||||
let corners = [intersect(*h1, *v1), intersect(*h1, *v2), intersect(*h2, *v2), intersect(*h2, *v1)];
|
||||
let [Some(a), Some(b), Some(c), Some(d)] = corners else { continue };
|
||||
let Some(q) = order_quad([a, b, c, d]) else { continue };
|
||||
if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) {
|
||||
continue;
|
||||
}
|
||||
let area = (0..4)
|
||||
.map(|k| {
|
||||
let (p, n) = (q[k], q[(k + 1) % 4]);
|
||||
p[0] * n[1] - n[0] * p[1]
|
||||
})
|
||||
.sum::<f64>()
|
||||
.abs()
|
||||
/ 2.0;
|
||||
if area < MIN_AREA * fw * fh {
|
||||
continue;
|
||||
}
|
||||
let sides: Vec<f64> = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect();
|
||||
if sides.iter().any(|&s| s < MIN_SUPPORT) {
|
||||
continue;
|
||||
}
|
||||
// Large, and with every side on its edge: a slightly larger quad with a side
|
||||
// off the sheet loses to the sheet itself.
|
||||
let mean = sides.iter().sum::<f64>() / 4.0;
|
||||
let score = area * mean * mean;
|
||||
let Some(score) = quad_score(&q, edges, w, h) else { continue };
|
||||
if best.is_none_or(|(b, _)| score > b) {
|
||||
best = Some((score, q));
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transitio
|
||||
/// One file produced by a split: (1-based first page, last page, PDF bytes).
|
||||
pub use pdfcraft_organize::LabelStyle;
|
||||
pub use pdfcraft_organize::Standard;
|
||||
pub use pdfcraft_organize::check_custom_key;
|
||||
pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation};
|
||||
|
||||
pub use pdfcraft_cos::Algorithm;
|
||||
@@ -951,6 +952,11 @@ impl Document {
|
||||
self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key))
|
||||
}
|
||||
|
||||
/// Whether the document information has an entry `key`, of any type, listed or not.
|
||||
pub fn has_info(&self, key: &str) -> bool {
|
||||
self.editor.as_ref().is_some_and(|e| pdfcraft_organize::has_info(&e.cos, key))
|
||||
}
|
||||
|
||||
/// The custom document properties as they are now (name, text), Document Properties ▸ Custom.
|
||||
pub fn custom_info(&self) -> Vec<(String, String)> {
|
||||
self.editor.as_ref().map(|e| pdfcraft_organize::custom_info(&e.cos)).unwrap_or_default()
|
||||
|
||||
@@ -6466,6 +6466,42 @@ fn comments_without_appearances_are_drawn_but_not_saved() {
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 178: with `/LL`, `/L` gives the ends of the leader lines, and the line itself
|
||||
/// is drawn `/LL` from it (above, for a positive `/LL` on a line drawn left to right). The page
|
||||
/// view shows the line there, with its leaders down to `/L`, and nothing along `/L` itself.
|
||||
#[test]
|
||||
fn a_line_without_an_appearance_is_drawn_at_its_leader_length() {
|
||||
let objs: Vec<&[u8]> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Line /Rect [0 0 200 300] /L [40 100 160 100] /LL 30 /C [1 0 0] /BS << /W 4 >> >>",
|
||||
];
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
bytes.extend_from_slice(o);
|
||||
bytes.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("line.pdf", None, Arc::new(bytes), None).expect("opens");
|
||||
let p = shown(&s, id, 0);
|
||||
let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();
|
||||
// y down: /L is row 200, the line itself row 170.
|
||||
assert_eq!(px(100, 170), vec![255, 0, 0, 255], "the line, 30 above /L");
|
||||
assert_eq!(px(40, 185), vec![255, 0, 0, 255], "the leader line at the start");
|
||||
assert_eq!(px(160, 185), vec![255, 0, 0, 255], "the leader line at the end");
|
||||
assert_eq!(px(100, 200), vec![255, 255, 255, 255], "nothing along /L");
|
||||
}
|
||||
|
||||
/// A stamp's `/Rect` and the colour family expected inside it.
|
||||
type StampRect = ([f64; 4], char);
|
||||
|
||||
|
||||
@@ -110,6 +110,16 @@ fn standard_role(doc: &pdfcraft_cos::Document, map: &Dict, role: &[u8]) -> Vec<u
|
||||
role
|
||||
}
|
||||
|
||||
/// Whether the page's resources hold a Form XObject, whose MCIDs are a separate namespace.
|
||||
fn page_has_form_xobject(doc: &pdfcraft_cos::Document, page: &pdfcraft_cos::Dict) -> bool {
|
||||
let resources = page.get(b"Resources").map(|o| doc.resolve(o));
|
||||
let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o));
|
||||
objects
|
||||
.as_ref()
|
||||
.and_then(|o| o.as_dict())
|
||||
.is_some_and(|d| d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form"))))
|
||||
}
|
||||
|
||||
type Exclusions = HashMap<usize, HashSet<i32>>;
|
||||
|
||||
/// Resolve page-local MCIDs through the structure hierarchy, including inherited roles and
|
||||
@@ -179,11 +189,7 @@ fn exclusions(source: &ExportSource, options: Options) -> Result<(Exclusions, bo
|
||||
if !out.contains_key(&index) {
|
||||
continue;
|
||||
}
|
||||
let resources = page.dict.get(b"Resources").map(|o| doc.resolve(o));
|
||||
let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o));
|
||||
let has_form = objects.as_ref().and_then(|o| o.as_dict()).is_some_and(|d| {
|
||||
d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form")))
|
||||
});
|
||||
let has_form = page_has_form_xobject(&doc, &page.dict);
|
||||
if has_form {
|
||||
out.remove(&index);
|
||||
unclassified = true;
|
||||
|
||||
@@ -133,8 +133,11 @@ impl TextBox {
|
||||
// As the appearance draws it: the first baseline is 0.85 em below the padded top and
|
||||
// a line is drawn while its descent (0.207 em) stays inside the border, so the
|
||||
// padding below the last line is not needed: `inner_h` plus 2 pt.
|
||||
let above = wrap_with(&shown, size, self.inner_w, width_of).len().saturating_sub(1) as f64;
|
||||
above * size * 1.15 + 1.057 * size <= self.inner_h + 2.0 + 0.01
|
||||
// Long words break by character, so a line is wider than the box only when it is a
|
||||
// single character wider than the box, which the appearance still cuts at the sides.
|
||||
let lines = wrap_with(&shown, size, self.inner_w, width_of);
|
||||
let above = lines.len().saturating_sub(1) as f64;
|
||||
above * size * 1.15 + 1.057 * size <= self.inner_h + 2.0 + 0.01 && lines.iter().all(|l| width_of(l, size) <= self.inner_w + 0.01)
|
||||
} else {
|
||||
// A line break in a single-line value is drawn as a space.
|
||||
let line: String = shown.chars().map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect();
|
||||
|
||||
@@ -471,6 +471,32 @@ fn a_short_multiline_field_takes_the_one_line_it_draws() {
|
||||
assert!(!tb("boxed").fits("one line"));
|
||||
}
|
||||
|
||||
/// A multi-line field narrower than one glyph: wrapping can't break inside a character, so the
|
||||
/// appearance cuts that character at the sides (`Overflow::Wide`), and `fits` must say so too.
|
||||
#[test]
|
||||
fn a_multiline_field_rejects_a_glyph_wider_than_the_field() {
|
||||
// 12 x 40 pt with no border: 8 pt inside the 2 pt padding. At 12 pt Helvetica a W is 11.3 pt
|
||||
// wide and an i 2.7 pt.
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (thin) /V (W) /DA (/Helv 12 Tf 0 g) /Ff {} /Rect [50 660 62 700] /P 3 0 R >>",
|
||||
flags::MULTILINE
|
||||
),
|
||||
];
|
||||
let doc = document(&objs);
|
||||
let all = fields(&doc);
|
||||
let f = field(&all, "thin");
|
||||
let tb = appearance::text_box(&doc, f, &f.widgets[0]);
|
||||
assert!(tb.fits("i") && tb.fits("i\ni"));
|
||||
assert!(matches!(appearance::value_overflow(&doc, f, &f.widgets[0]), Some(appearance::Overflow::Wide { .. })));
|
||||
assert!(!tb.fits("W") && !tb.fits("iW"));
|
||||
}
|
||||
|
||||
/// An edit to a field that doesn't scroll keeps as much of what it inserted as fits, wherever the
|
||||
/// caret was, and always keeps a deletion.
|
||||
#[test]
|
||||
|
||||
@@ -152,11 +152,12 @@ fn referenced_names(doc: &Document) -> HashSet<Vec<u8>> {
|
||||
Object::Dict(d) => {
|
||||
// Resolve first: /Dest and a GoTo's /D may be an indirect reference to the name
|
||||
// string, and an unresolved ref has no name, so the destination it uses would
|
||||
// look unreferenced and be removed.
|
||||
// look unreferenced and be removed. A GoToR or GoToE /D names a destination in
|
||||
// another document, so it does not count as a use of this one's.
|
||||
if let Some(n) = d.get(b"Dest").and_then(|x| dest_name(doc.resolve(x).as_ref())) {
|
||||
out.insert(n);
|
||||
}
|
||||
if matches!(d.name(b"S"), Some(b"GoTo" | b"GoToR" | b"GoToE"))
|
||||
if d.name(b"S") == Some(b"GoTo")
|
||||
&& let Some(n) = d.get(b"D").and_then(|x| dest_name(doc.resolve(x).as_ref()))
|
||||
{
|
||||
out.insert(n);
|
||||
|
||||
@@ -1273,6 +1273,50 @@ fn indirectly_referenced_destination_is_kept() {
|
||||
assert!(!left.contains(&b"unused".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destination_named_only_by_a_remote_or_embedded_go_to_is_removed() {
|
||||
// The /D of a GoToR or GoToE action names a destination in another document. A local
|
||||
// destination of the same name that nothing else uses is unreferenced.
|
||||
let mut doc = Document::new_empty();
|
||||
let p = page(&mut doc, &[], "BT ET");
|
||||
let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec()));
|
||||
let link = |doc: &mut Document, action: Dict| {
|
||||
let mut link = Dict::new();
|
||||
link.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
link.set(b"Subtype".to_vec(), Object::name("Link"));
|
||||
link.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]));
|
||||
link.set(b"A".to_vec(), Object::Dict(action));
|
||||
Object::Ref(doc.add(Object::Dict(link)))
|
||||
};
|
||||
let mut go_to = Dict::new();
|
||||
go_to.set(b"S".to_vec(), Object::name("GoTo"));
|
||||
go_to.set(b"D".to_vec(), s("local"));
|
||||
let mut remote = Dict::new();
|
||||
remote.set(b"S".to_vec(), Object::name("GoToR"));
|
||||
remote.set(b"F".to_vec(), s("other.pdf"));
|
||||
remote.set(b"D".to_vec(), s("remote"));
|
||||
let mut target = Dict::new();
|
||||
target.set(b"R".to_vec(), Object::name("C"));
|
||||
target.set(b"N".to_vec(), s("attached.pdf"));
|
||||
let mut embedded = Dict::new();
|
||||
embedded.set(b"S".to_vec(), Object::name("GoToE"));
|
||||
embedded.set(b"T".to_vec(), Object::Dict(target));
|
||||
embedded.set(b"D".to_vec(), s("embedded"));
|
||||
let links = vec![link(&mut doc, go_to), link(&mut doc, remote), link(&mut doc, embedded)];
|
||||
doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(links))).unwrap();
|
||||
let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]);
|
||||
let mut tree = Dict::new();
|
||||
tree.set(b"Names".to_vec(), Object::Array(vec![s("embedded"), fit.clone(), s("local"), fit.clone(), s("remote"), fit]));
|
||||
let tree = doc.add(Object::Dict(tree));
|
||||
let mut names = Dict::new();
|
||||
names.set(b"Dests".to_vec(), Object::Ref(tree));
|
||||
let root = doc.root().unwrap();
|
||||
doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap();
|
||||
let report = optimize(&mut doc, &Settings::default()).unwrap();
|
||||
assert_eq!(report.unreferenced_dests, 2);
|
||||
assert_eq!(named_dest_keys(&doc), vec![b"local".to_vec()]);
|
||||
}
|
||||
|
||||
/// The keys in the catalog's /Names /Dests name tree (one level, as the optimizer writes it).
|
||||
fn named_dest_keys(doc: &Document) -> Vec<Vec<u8>> {
|
||||
let cat = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
|
||||
|
||||
@@ -672,6 +672,11 @@ pub fn info(doc: &Document, key: &str) -> Option<String> {
|
||||
in_info.filter(|v| !v.trim_matches('\0').trim().is_empty()).or_else(|| xmp::info_value(doc, key))
|
||||
}
|
||||
|
||||
/// Whether the document information has an entry `key`, of any type.
|
||||
pub fn has_info(doc: &Document, key: &str) -> bool {
|
||||
doc.trailer().get(b"Info").map(|o| doc.resolve(o)).is_some_and(|info| info.as_dict().is_some_and(|d| d.get(key.as_bytes()).is_some()))
|
||||
}
|
||||
|
||||
/// Set (or clear, with an empty value) a document-information entry.
|
||||
///
|
||||
/// Documents with XMP metadata also carry Title, Author, Subject, Keywords, Creator and Producer
|
||||
@@ -699,12 +704,18 @@ fn set_info_entry(doc: &mut Document, key: &[u8], entry: Option<Object>) -> Resu
|
||||
})?;
|
||||
}
|
||||
_ => {
|
||||
let Some(v) = entry else { return Ok(()) };
|
||||
let mut d = match doc.trailer().get(b"Info") {
|
||||
Some(Object::Dict(d)) => d.clone(),
|
||||
_ => Dict::new(),
|
||||
};
|
||||
d.set(key.to_vec(), v);
|
||||
match entry {
|
||||
Some(v) => d.set(key.to_vec(), v),
|
||||
None => {
|
||||
if d.remove(key).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
let r = doc.add(d);
|
||||
doc.trailer_mut().set(b"Info".to_vec(), Object::Ref(r));
|
||||
}
|
||||
|
||||
@@ -553,10 +553,7 @@ pub fn add_bookmark_at(
|
||||
let at = index.min(kids.len());
|
||||
kids.insert(at, item);
|
||||
relink(doc, parent, &kids)?;
|
||||
// Show the new bookmark: open its parent (the root is always open).
|
||||
if !parent_path.is_empty() && doc.get(parent).as_dict().and_then(|d| d.int(b"Count")).is_none_or(|c| c <= 0) {
|
||||
put(doc, parent, b"Count", Some(Object::Int(1)))?;
|
||||
}
|
||||
show_children(doc, parent, parent_path)?;
|
||||
recount(doc)?;
|
||||
let mut path = parent_path.to_vec();
|
||||
path.push(at);
|
||||
@@ -699,11 +696,23 @@ pub fn move_bookmark(doc: &mut Document, from: &[usize], to_parent: &[usize], in
|
||||
let at = index.min(kids.len());
|
||||
kids.insert(at, r);
|
||||
relink(doc, parent, &kids)?;
|
||||
if parent != old_parent {
|
||||
show_children(doc, parent, &to_parent)?;
|
||||
}
|
||||
recount(doc)?;
|
||||
to_parent.push(at);
|
||||
Ok(to_parent)
|
||||
}
|
||||
|
||||
/// Open `parent` so a bookmark just added or moved into it shows (the root is always open).
|
||||
/// Only the sign of `/Count` matters here: [`recount`] sets its value.
|
||||
fn show_children(doc: &mut Document, parent: ObjRef, parent_path: &[usize]) -> Result<()> {
|
||||
if !parent_path.is_empty() && doc.get(parent).as_dict().and_then(|d| d.int(b"Count")).is_none_or(|c| c <= 0) {
|
||||
put(doc, parent, b"Count", Some(Object::Int(1)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Expand or collapse a bookmark that has children.
|
||||
pub fn set_bookmark_open(doc: &mut Document, path: &[usize], open: bool) -> Result<()> {
|
||||
let (r, _) = resolve_path(doc, path)?;
|
||||
|
||||
@@ -528,6 +528,29 @@ fn custom_document_properties_are_listed_set_removed_and_their_names_checked() {
|
||||
assert!(custom_info(&doc).is_empty());
|
||||
}
|
||||
|
||||
/// An `/Info` dictionary written directly in the trailer: a cleared entry is removed, and the
|
||||
/// other entries are kept.
|
||||
#[test]
|
||||
fn document_info_entries_are_cleared_from_an_info_dictionary_in_the_trailer() {
|
||||
let b = build(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".into(),
|
||||
body("X"),
|
||||
],
|
||||
"/Root 1 0 R /Info << /Title (Report) /Project (Apollo) /Revision (7) >>",
|
||||
);
|
||||
let mut doc = open(b);
|
||||
set_info(&mut doc, "Missing", "").unwrap();
|
||||
assert!(matches!(doc.trailer().get(b"Info"), Some(Object::Dict(_))), "clearing an absent entry changes nothing");
|
||||
set_info(&mut doc, "Project", "").unwrap();
|
||||
set_info(&mut doc, "Title", "").unwrap();
|
||||
let doc = save_and_reopen(&doc);
|
||||
assert_eq!(custom_info(&doc), [("Revision".to_string(), "7".to_string())]);
|
||||
assert_eq!(info(&doc, "Title"), None);
|
||||
}
|
||||
|
||||
/// Padding is not part of a custom value, in any mix of NULs and whitespace, a value that is only
|
||||
/// padding is not listed, and such entries don't count towards the 256 listed: a real property
|
||||
/// after 300 blank ones is still there.
|
||||
@@ -1725,6 +1748,18 @@ fn bookmarks_add_rename_move_delete() {
|
||||
assert_eq!(crate::move_bookmark(&mut d, &[0], &[2], 9).unwrap(), vec![1, 1]);
|
||||
assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Table,Figure 1]"]);
|
||||
assert_eq!(crate::move_bookmark(&mut d, &[1], &[1, 0], 0), Err(crate::OutlineError::IntoItself));
|
||||
// Into a bookmark with no children yet (Indent): it opens, so the moved one shows.
|
||||
assert_eq!(crate::move_bookmark(&mut d, &[1, 1], &[0], 0).unwrap(), vec![0, 0]);
|
||||
let intro = crate::bookmarks(&d)[0].obj;
|
||||
assert_eq!(count_of(&d, intro), Some(1));
|
||||
// Reordering inside a closed parent leaves it closed.
|
||||
crate::add_bookmark(&mut d, &[0], 1, "Second", 0).unwrap();
|
||||
crate::set_bookmark_open(&mut d, &[0], false).unwrap();
|
||||
crate::move_bookmark(&mut d, &[0, 1], &[0], 0).unwrap();
|
||||
assert_eq!(count_of(&d, intro), Some(-2));
|
||||
crate::delete_bookmark(&mut d, &[0, 0]).unwrap();
|
||||
crate::move_bookmark(&mut d, &[0, 0], &[1], 9).unwrap();
|
||||
assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Table,Figure 1]"]);
|
||||
crate::delete_bookmark(&mut d, &[1, 0]).unwrap();
|
||||
assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Figure 1]"]);
|
||||
|
||||
@@ -2392,6 +2427,46 @@ fn initial_view_round_trips_and_keeps_scripts() {
|
||||
assert!(crate::set_initial_view(&mut doc, &crate::InitialView { page: 9, ..Default::default() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_opening_destination_keeps_its_position_and_name() {
|
||||
use crate::view::{Magnification, Navigation};
|
||||
let page2 = Object::Ref(pdfcraft_cos::ObjRef::new(5, 0));
|
||||
let xyz = Object::Array(vec![page2.clone(), Object::name("XYZ"), Object::Int(100), Object::Int(500), Object::Int(2)]);
|
||||
let mut named = pdfcraft_cos::Dict::new();
|
||||
named.set(b"S".to_vec(), Object::name("GoTo"));
|
||||
named.set(b"D".to_vec(), Object::name("there"));
|
||||
let mut dests = pdfcraft_cos::Dict::new();
|
||||
dests.set(b"there".to_vec(), Object::Array(vec![page2, Object::name("Fit")]));
|
||||
let mut prefs = pdfcraft_cos::Dict::new();
|
||||
prefs.set(b"NonFullScreenPageMode".to_vec(), Object::name("UseOutlines"));
|
||||
for action in [xyz, Object::Dict(named)] {
|
||||
let mut doc = open(fixture());
|
||||
let root = doc.root().unwrap();
|
||||
doc.update_dict(root, |c| {
|
||||
c.set(b"OpenAction".to_vec(), action.clone());
|
||||
c.set(b"Dests".to_vec(), Object::Dict(dests.clone()));
|
||||
c.set(b"PageMode".to_vec(), Object::name("FullScreen"));
|
||||
c.set(b"ViewerPreferences".to_vec(), Object::Dict(prefs.clone()));
|
||||
})
|
||||
.unwrap();
|
||||
// Another option changes: the opening action is written back as it was, and so is the
|
||||
// full-screen panel, which the dialog doesn't edit.
|
||||
let v = crate::initial_view(&doc);
|
||||
assert_eq!(v.non_full_screen, Navigation::Bookmarks);
|
||||
crate::set_initial_view(&mut doc, &crate::InitialView { hide_toolbar: true, ..v.clone() }).unwrap();
|
||||
let catalog = doc.get(root).as_dict().cloned().unwrap();
|
||||
assert_eq!(catalog.get(b"OpenAction"), Some(&action));
|
||||
let doc = save_and_reopen(&doc);
|
||||
assert_eq!(crate::initial_view(&doc), crate::InitialView { hide_toolbar: true, ..v.clone() });
|
||||
// A changed magnification writes a destination of its own.
|
||||
let mut doc = doc;
|
||||
crate::set_initial_view(&mut doc, &crate::InitialView { magnification: Magnification::FitPage, ..v }).unwrap();
|
||||
let catalog = doc.get(root).as_dict().cloned().unwrap();
|
||||
assert_ne!(catalog.get(b"OpenAction"), Some(&action));
|
||||
assert_eq!(crate::initial_view(&doc).magnification, Magnification::FitPage);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Split / Extract keep only the resources the part draws (#204) ──────────────────────────────
|
||||
|
||||
/// A content stream with no text operators (an image draw).
|
||||
|
||||
@@ -63,6 +63,10 @@ pub struct InitialView {
|
||||
pub language: Option<String>,
|
||||
/// Right-edge binding (`/Direction /R2L`).
|
||||
pub right_to_left: bool,
|
||||
/// The navigation panel on leaving full screen (`/ViewerPreferences /NonFullScreenPageMode`,
|
||||
/// ISO 32000-2 Table 147), read only when `full_screen` is set. It is read, not written:
|
||||
/// [`set_initial_view`] leaves the entry as it is.
|
||||
pub non_full_screen: Navigation,
|
||||
}
|
||||
|
||||
fn catalog(doc: &Document) -> Result<(pdfcraft_cos::ObjRef, Dict), OrganizeError> {
|
||||
@@ -104,6 +108,15 @@ pub fn initial_view(doc: &Document) -> InitialView {
|
||||
v.hide_toolbar = flag(b"HideToolbar");
|
||||
v.hide_window_ui = flag(b"HideWindowUI");
|
||||
v.right_to_left = name(&vp, b"Direction").as_deref() == Some(b"R2L");
|
||||
// Table 147: meaningful only with `/PageMode /FullScreen`, and only these four values.
|
||||
if v.full_screen {
|
||||
v.non_full_screen = match name(&vp, b"NonFullScreenPageMode").as_deref() {
|
||||
Some(b"UseOutlines") => Navigation::Bookmarks,
|
||||
Some(b"UseThumbs") => Navigation::Pages,
|
||||
Some(b"UseOC") => Navigation::Layers,
|
||||
_ => Navigation::PageOnly,
|
||||
};
|
||||
}
|
||||
}
|
||||
// The opening destination: an explicit array, or a GoTo action's.
|
||||
let dest = c.get(b"OpenAction").map(|o| doc.resolve(o)).and_then(|o| match &*o {
|
||||
@@ -149,8 +162,13 @@ pub fn displays_doc_title(doc: &Document) -> bool {
|
||||
}
|
||||
|
||||
/// Write the initial view. An opening action that isn't a plain destination (a script, say) is
|
||||
/// kept unless the page or magnification asks for a destination.
|
||||
/// kept unless the page or magnification asks for a destination, and an opening action whose page
|
||||
/// and magnification `v` leaves as [`initial_view`] reads them is kept as it is.
|
||||
pub fn set_initial_view(doc: &mut Document, v: &InitialView) -> Result<(), OrganizeError> {
|
||||
let same_destination = {
|
||||
let now = initial_view(doc);
|
||||
now.page == v.page && now.magnification == v.magnification
|
||||
};
|
||||
let (root, c) = catalog(doc)?;
|
||||
let pages = crate::walk(doc)?;
|
||||
if v.page >= pages.len() {
|
||||
@@ -238,6 +256,9 @@ pub fn set_initial_view(doc: &mut Document, v: &InitialView) -> Result<(), Organ
|
||||
}
|
||||
}
|
||||
match (&dest, open_action_is_dest) {
|
||||
// The opening page and magnification are as read: the action stays as written, with
|
||||
// its position or named destination (§12.3.2.4) that the view model doesn't hold.
|
||||
_ if same_destination => {}
|
||||
(Some(d), _) => c.set(b"OpenAction".to_vec(), Object::Array(d.clone())),
|
||||
(None, true) => {
|
||||
c.remove(b"OpenAction");
|
||||
@@ -294,4 +315,40 @@ mod tests {
|
||||
assert_eq!(flags(initial_view(&doc)), [false; 6]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog with `/PageMode page_mode` and `/ViewerPreferences << /NonFullScreenPageMode mode >>`.
|
||||
fn with_modes(page_mode: &str, mode: Object) -> Document {
|
||||
let mut doc = Document::new_empty();
|
||||
let mode = doc.add(mode);
|
||||
let mut preferences = Dict::new();
|
||||
preferences.set(b"NonFullScreenPageMode".to_vec(), Object::Ref(mode));
|
||||
let root = doc.root().unwrap();
|
||||
doc.update_dict(root, |c| {
|
||||
c.set(b"PageMode".to_vec(), Object::name(page_mode));
|
||||
c.set(b"ViewerPreferences".to_vec(), Object::Dict(preferences));
|
||||
})
|
||||
.unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_full_screen_page_mode_is_read_with_full_screen_only() {
|
||||
for (mode, want) in [
|
||||
("UseOutlines", Navigation::Bookmarks),
|
||||
("UseThumbs", Navigation::Pages),
|
||||
("UseOC", Navigation::Layers),
|
||||
("UseNone", Navigation::PageOnly),
|
||||
// Not a value Table 147 lists.
|
||||
("UseAttachments", Navigation::PageOnly),
|
||||
("FullScreen", Navigation::PageOnly),
|
||||
] {
|
||||
let v = initial_view(&with_modes("FullScreen", Object::name(mode)));
|
||||
assert!(v.full_screen);
|
||||
assert_eq!(v.non_full_screen, want, "{mode}");
|
||||
// Ignored unless the document opens in full screen.
|
||||
let v = initial_view(&with_modes("UseThumbs", Object::name(mode)));
|
||||
assert_eq!((v.navigation, v.non_full_screen), (Navigation::Pages, Navigation::PageOnly), "{mode}");
|
||||
}
|
||||
assert_eq!(initial_view(&with_modes("FullScreen", Object::Int(1))).non_full_screen, Navigation::PageOnly);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -455,8 +455,8 @@ fn content_draws(doc: &Document, content: &[Vec<u8>], xo: &Dict, name: &[u8], de
|
||||
if depth >= MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let Ok(_data) = s.decoded() else { return None };
|
||||
match content_draws(doc, content, xo, name, depth + 1, seen) {
|
||||
let Ok(data) = s.decoded() else { return None };
|
||||
match content_draws(doc, std::slice::from_ref(&data), xo, name, depth + 1, seen) {
|
||||
Some(false) => {}
|
||||
other => return other,
|
||||
}
|
||||
|
||||
@@ -66,3 +66,42 @@ fn an_image_a_surviving_form_draws_is_kept() {
|
||||
assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1);
|
||||
assert!(full_save_holds(&doc, b"IMAGESECRET"), "the image the form still draws outside the mark");
|
||||
}
|
||||
|
||||
/// The surviving form draws the image through a nested form without /Resources of its own,
|
||||
/// which draws through the outer form's: the image is kept.
|
||||
#[test]
|
||||
fn an_image_a_surviving_forms_nested_form_draws_is_kept() {
|
||||
let mut doc = pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
|
||||
stream("", b"q 100 0 0 100 0 0 cm /Im Do Q /Fm Do"),
|
||||
b"<< /XObject << /Im 6 0 R /Fm 7 0 R /Inner 8 0 R >> >>".to_vec(),
|
||||
stream("/Type /XObject /Subtype /Image /Width 11 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"IMAGESECRET"),
|
||||
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources 5 0 R", b"/Inner Do"),
|
||||
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"q 50 0 0 50 200 200 cm /Im Do Q"),
|
||||
]);
|
||||
mark(&mut doc, 0, &[[0.0, 0.0, 120.0, 120.0]], "");
|
||||
assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1);
|
||||
assert!(full_save_holds(&doc, b"IMAGESECRET"), "the image the nested form still draws outside the mark");
|
||||
}
|
||||
|
||||
/// Two pages share one resource dictionary, and the second draws the image only through a form
|
||||
/// without /Resources: redacting the image on the first page keeps it for the second.
|
||||
#[test]
|
||||
fn an_image_another_page_draws_through_a_form_without_resources_is_kept() {
|
||||
let mut doc = pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Resources 7 0 R >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 6 0 R /Resources 7 0 R >>".to_vec(),
|
||||
stream("", b"q 100 0 0 100 0 0 cm /Im Do Q"),
|
||||
stream("", b"/Inner Do"),
|
||||
b"<< /XObject << /Im 8 0 R /Inner 9 0 R >> >>".to_vec(),
|
||||
stream("/Type /XObject /Subtype /Image /Width 11 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"IMAGESECRET"),
|
||||
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"q 50 0 0 50 200 200 cm /Im Do Q"),
|
||||
]);
|
||||
mark(&mut doc, 0, &[[0.0, 0.0, 120.0, 120.0]], "");
|
||||
assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1);
|
||||
assert!(full_save_holds(&doc, b"IMAGESECRET"), "the second page still draws the image through its form");
|
||||
}
|
||||
|
||||
@@ -110,6 +110,10 @@ pub struct DocInfo {
|
||||
pub attachments: Vec<Attachment>,
|
||||
/// Pages with a presentation transition (`/Trans`) or display time (`/Dur`), in page order.
|
||||
pub transitions: Vec<PageTransition>,
|
||||
/// Where the document opens (`/OpenAction`): the (0-based page, view) of its destination,
|
||||
/// named destinations resolved. `None` without one, for an action that goes nowhere in this
|
||||
/// document (a script, say), or for one that doesn't resolve to a page of it.
|
||||
pub open_dest: Option<(usize, DestView)>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -401,6 +405,9 @@ pub struct OutlineItem {
|
||||
/// Where on `page` the bookmark goes ([`DestView::Top`] for a bookmark without a page).
|
||||
pub view: DestView,
|
||||
pub children: Vec<OutlineItem>,
|
||||
/// Whether the bookmark starts open: only a positive `/Count` says so (ISO 32000-2 §12.3.3,
|
||||
/// Table 151). A negative one is closed, and so is a missing one, which a bookmark with
|
||||
/// children should not have.
|
||||
pub open: bool,
|
||||
/// The title's colour (`/C`, DeviceRGB, ISO 32000-2 §12.3.3 Table 151), or `None` for the
|
||||
/// default black or a value that isn't three numbers.
|
||||
@@ -825,6 +832,25 @@ impl<'a> Inspector<'a> {
|
||||
{
|
||||
info.has_javascript = true;
|
||||
}
|
||||
info.open_dest = catalog.get(b"OpenAction").ok().and_then(|o| self.open_dest(o));
|
||||
}
|
||||
|
||||
/// The destination `/OpenAction` opens at (ISO 32000-2 §7.7.2 Table 29): an explicit
|
||||
/// destination array, a `/GoTo` action's `/D`, or (leniently, since Table 29 asks for an array
|
||||
/// or an action) a destination name or string; a name or string is looked up as a named
|
||||
/// destination (§12.3.2.4). Any other action (a script, a remote go-to) has none here, and
|
||||
/// neither has a page number past the end of the document.
|
||||
fn open_dest(&self, action: &Object) -> Option<(usize, DestView)> {
|
||||
let dest = match self.resolve(action) {
|
||||
Object::Dictionary(d) => {
|
||||
if d.get(b"S").ok().and_then(|o| self.resolve(o).as_name().ok()) != Some(&b"GoTo"[..]) {
|
||||
return None;
|
||||
}
|
||||
d.get(b"D").ok()?
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
self.dest(dest, 0).filter(|(page, _)| *page < self.page_ids.len())
|
||||
}
|
||||
|
||||
// ── object helpers ──────────────────────────────────────────────────────────────────────
|
||||
@@ -4114,3 +4140,112 @@ mod open_action_javascript_tests {
|
||||
assert!(!info.has_javascript, "a /GoTo /OpenAction is not JavaScript");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod open_dest_tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{DestView, inspect};
|
||||
|
||||
/// Three 612×792 pages (objects 3, 4, 5); `catalog` is added to the catalog dictionary and
|
||||
/// `extra` become objects 6, 7, ….
|
||||
fn pdf(catalog: &str, extra: &[String]) -> Vec<u8> {
|
||||
let mut objs =
|
||||
vec![format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"), "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>".to_string()];
|
||||
for _ in 0..3 {
|
||||
objs.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_string());
|
||||
}
|
||||
objs.extend(extra.iter().cloned());
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn open_dest(catalog: &str, extra: &[String]) -> Option<(usize, DestView)> {
|
||||
inspect(Arc::new(pdf(catalog, extra)), None).expect("inspects").open_dest
|
||||
}
|
||||
|
||||
const XYZ: DestView = DestView::Xyz { left: Some(100.0), top: Some(500.0), zoom: Some(2.0) };
|
||||
|
||||
#[test]
|
||||
fn an_explicit_destination_opens_at_its_page_and_position() {
|
||||
assert_eq!(open_dest("/OpenAction [5 0 R /XYZ 100 500 2]", &[]), Some((2, XYZ)));
|
||||
assert_eq!(open_dest("/OpenAction [4 0 R /FitH 400]", &[]), Some((1, DestView::FitH { top: Some(400.0) })));
|
||||
// Indirect, and a zoom of 0 keeps the zoom (Table 149).
|
||||
assert_eq!(
|
||||
open_dest("/OpenAction 6 0 R", &["[4 0 R /XYZ 0 792 0]".into()]),
|
||||
Some((1, DestView::Xyz { left: Some(0.0), top: Some(792.0), zoom: None }))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_go_to_action_opens_at_its_destination_explicit_or_named() {
|
||||
assert_eq!(open_dest("/OpenAction << /S /GoTo /D [5 0 R /XYZ 100 500 2] >>", &[]), Some((2, XYZ)));
|
||||
// A name, through the PDF 1.1 catalog /Dests dictionary (§12.3.2.4).
|
||||
assert_eq!(open_dest("/OpenAction << /S /GoTo /D /there >> /Dests << /there [5 0 R /XYZ 100 500 2] >>", &[]), Some((2, XYZ)));
|
||||
// A byte string, through the /Names /Dests name tree, whose value is a dictionary with /D.
|
||||
assert_eq!(
|
||||
open_dest(
|
||||
"/OpenAction << /S /GoTo /D (there) >> /Names << /Dests 6 0 R >>",
|
||||
&["<< /Kids [7 0 R] >>".into(), "<< /Names [(here) [3 0 R /Fit] (there) << /D [5 0 R /XYZ 100 500 2] >>] >>".into()]
|
||||
),
|
||||
Some((2, XYZ))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_action_given_as_a_name_or_string_is_looked_up() {
|
||||
assert_eq!(open_dest("/OpenAction /there /Dests << /there [4 0 R /Fit] >>", &[]), Some((1, DestView::Fit)));
|
||||
assert_eq!(
|
||||
open_dest("/OpenAction (there) /Names << /Dests << /Names [(there) [5 0 R /FitV 30]] >> >>", &[]),
|
||||
Some((2, DestView::FitV { left: Some(30.0) }))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_action_that_goes_nowhere_here_has_no_destination() {
|
||||
for catalog in [
|
||||
"",
|
||||
"/OpenAction << /S /JavaScript /JS (app.alert(1)) >>",
|
||||
// A remote go-to's /D is a page of another file.
|
||||
"/OpenAction << /S /GoToR /F (other.pdf) /D [1 /Fit] >>",
|
||||
"/OpenAction << /D [4 0 R /Fit] >>",
|
||||
// An unknown name, and no name dictionaries at all.
|
||||
"/OpenAction << /S /GoTo /D /missing >> /Dests << /there [4 0 R /Fit] >>",
|
||||
"/OpenAction /missing",
|
||||
// A page number past the end, and a page reference that is no page.
|
||||
"/OpenAction [7 /Fit]",
|
||||
"/OpenAction [2 0 R /Fit]",
|
||||
"/OpenAction 42",
|
||||
] {
|
||||
assert_eq!(open_dest(catalog, &[]), None, "{catalog}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cyclic_and_deep_named_destinations_end() {
|
||||
// Names that refer to each other.
|
||||
assert_eq!(open_dest("/OpenAction /a /Dests << /a /b /b /a >>", &[]), None);
|
||||
assert_eq!(open_dest("/OpenAction /a /Dests << /a << /D /a >> >>", &[]), None);
|
||||
// A name tree whose node is its own kid.
|
||||
assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &["<< /Kids [6 0 R] >>".into()]), None);
|
||||
// A name tree deeper than the depth bound: the leaf past it isn't read.
|
||||
let depth = 40;
|
||||
let mut nodes: Vec<String> = (0..depth).map(|i| format!("<< /Kids [{} 0 R] >>", 7 + i)).collect();
|
||||
nodes.push("<< /Names [(x) [4 0 R /Fit]] >>".into());
|
||||
assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &nodes), None);
|
||||
// A shallow one is read.
|
||||
let shallow = ["<< /Kids [7 0 R] >>".to_string(), "<< /Kids [8 0 R] >>".into(), "<< /Names [(x) [4 0 R /Fit]] >>".into()];
|
||||
assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &shallow), Some((1, DestView::Fit)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,3 +6,4 @@ mod jbig2_invariants;
|
||||
mod named_form_properties;
|
||||
mod search;
|
||||
mod substitute_widths;
|
||||
mod tiling_cell_placement;
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! Tiling pattern cells sit at whole multiples of `/XStep` and `/YStep` in pattern space
|
||||
//! (ISO 32000-2 8.7.3.1, Table 74), at any rendering scale, however far they are from the
|
||||
//! pattern's origin.
|
||||
//!
|
||||
//! Each page is filled (or stroked) with a pattern whose 20 × 20 cell holds one 6 × 6 blue square
|
||||
//! at (7, 7). At 110 dpi a step is 30.56 device pixels; every probe finds the blue square in a
|
||||
//! disc around where the pattern matrix puts it and checks that its centroid is within one
|
||||
//! device pixel of that place.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind};
|
||||
|
||||
/// The rendering scale for 110 dpi: a step of 20 points is 30.56 pixels, not a whole number.
|
||||
const SCALE: f64 = 110.0 / 72.0;
|
||||
/// The page is `SIDE` × `SIDE` points.
|
||||
const SIDE: f64 = 400.0;
|
||||
|
||||
/// One page `SIDE` points square whose content `content` paints with `/P1`: the 20-point cell
|
||||
/// with its blue square, `/XStep` and `/YStep` 20, under pattern matrix `matrix`.
|
||||
fn page_pdf(content: &str, matrix: [f64; 6]) -> Vec<u8> {
|
||||
let cell = "0 0 1 rg 7 7 6 6 re f";
|
||||
let m = matrix.map(|v| format!("{v}")).join(" ");
|
||||
format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 {SIDE} {SIDE}] /Contents 4 0 R /Resources << /Pattern << /P1 5 0 R >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
5 0 obj << /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Matrix [{m}] /Length {} >> stream
|
||||
{cell}
|
||||
endstream endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len(),
|
||||
cell.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
struct Page {
|
||||
rgba: Vec<u8>,
|
||||
width: usize,
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn render(content: &str, matrix: [f64; 6]) -> Page {
|
||||
let mut r = PageRenderer::new(Arc::new(page_pdf(content, matrix)), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: SCALE as f32, tag: 0, ..Default::default() });
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
Page { rgba: page.rgba.to_vec(), width: page.width as usize, height: page.height as usize }
|
||||
}
|
||||
|
||||
/// The device position of pattern-space point `(x, y)`: the pattern matrix to page space, then
|
||||
/// page space to device pixels (y down).
|
||||
fn device(matrix: [f64; 6], x: f64, y: f64) -> (f64, f64) {
|
||||
let [a, b, c, d, e, f] = matrix;
|
||||
let (px, py) = (a * x + c * y + e, b * x + d * y + f);
|
||||
(px * SCALE, (SIDE - py) * SCALE)
|
||||
}
|
||||
|
||||
/// The centroid of blue (weighted by how far each pixel is from white) in the disc of `radius`
|
||||
/// pixels around `(cx, cy)`, and the total weight. `None` when the disc leaves the page.
|
||||
fn blue_centroid(page: &Page, cx: f64, cy: f64, radius: f64) -> Option<((f64, f64), f64)> {
|
||||
let (x0, x1) = ((cx - radius).floor(), (cx + radius).ceil());
|
||||
let (y0, y1) = ((cy - radius).floor(), (cy + radius).ceil());
|
||||
if x0 < 0.0 || y0 < 0.0 || x1 >= page.width as f64 || y1 >= page.height as f64 {
|
||||
return None;
|
||||
}
|
||||
let (mut sum, mut sx, mut sy) = (0.0, 0.0, 0.0);
|
||||
for j in (y0 as usize)..=(y1 as usize) {
|
||||
for i in (x0 as usize)..=(x1 as usize) {
|
||||
let (px, py) = (i as f64 + 0.5, j as f64 + 0.5);
|
||||
if (px - cx).powi(2) + (py - cy).powi(2) > radius * radius {
|
||||
continue;
|
||||
}
|
||||
let red = *page.rgba.get((j * page.width + i) * 4)?;
|
||||
let w = f64::from(255 - red) / 255.0;
|
||||
sum += w;
|
||||
sx += w * px;
|
||||
sy += w * py;
|
||||
}
|
||||
}
|
||||
(sum > 0.0).then(|| ((sx / sum, sy / sum), sum))
|
||||
}
|
||||
|
||||
/// Checks every cell `(k, m)` whose blue square's centre falls in the page rectangle `area`
|
||||
/// (points: x0, y0, x1, y1): its square is found where the matrix puts it, within one pixel.
|
||||
/// Returns how many cells were checked.
|
||||
fn assert_cells_in_place(page: &Page, matrix: [f64; 6], area: [f64; 4], what: &str) -> usize {
|
||||
let [a, b, c, d, _, _] = matrix;
|
||||
// The square is 6 × 6 at (7, 7); its centre is (10, 10) in the cell. A disc of 6 cell
|
||||
// units around it holds the whole square (half-diagonal 4.24) and no neighbour (7 away).
|
||||
let units = (a * a + b * b).sqrt().min((c * c + d * d).sqrt());
|
||||
let radius = 6.0 * units * SCALE;
|
||||
let area_px = 36.0 * units * units * SCALE * SCALE;
|
||||
let mut checked = 0;
|
||||
for k in -60..60 {
|
||||
for m in -60..60 {
|
||||
let (cx_cell, cy_cell) = (20.0 * f64::from(k) + 10.0, 20.0 * f64::from(m) + 10.0);
|
||||
let [ea, eb, ec, ed, ee, ef] = matrix;
|
||||
let (px, py) = (ea * cx_cell + ec * cy_cell + ee, eb * cx_cell + ed * cy_cell + ef);
|
||||
if px < area[0] || px > area[2] || py < area[1] || py > area[3] {
|
||||
continue;
|
||||
}
|
||||
let (cx, cy) = device(matrix, cx_cell, cy_cell);
|
||||
let Some(((gx, gy), weight)) = blue_centroid(page, cx, cy, radius) else { continue };
|
||||
assert!(weight > 0.8 * area_px, "{what}: cell ({k}, {m}) at ({cx:.1}, {cy:.1}) only partly there: {weight:.1} of {area_px:.1}");
|
||||
assert!(
|
||||
(gx - cx).abs() <= 1.0 && (gy - cy).abs() <= 1.0,
|
||||
"{what}: cell ({k}, {m}) should be centred at ({cx:.2}, {cy:.2}) px, found at ({gx:.2}, {gy:.2})"
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
checked
|
||||
}
|
||||
|
||||
const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// A fill far from the pattern's origin: the cells 300 to 400 points away (15 to 19 steps) are
|
||||
/// where 15 to 19 steps put them, not 0.44 pixel further for every step.
|
||||
#[test]
|
||||
fn far_cells_of_a_fill_sit_at_whole_steps() {
|
||||
let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", IDENTITY);
|
||||
let near = assert_cells_in_place(&page, IDENTITY, [0.0, 0.0, 100.0, 100.0], "near the origin");
|
||||
let far = assert_cells_in_place(&page, IDENTITY, [290.0, 290.0, 400.0, 400.0], "far from the origin");
|
||||
assert!(near >= 16 && far >= 16, "{near} near, {far} far");
|
||||
}
|
||||
|
||||
/// The same under a pattern matrix that scales by 1.49 and turns by 30 degrees: a step is
|
||||
/// 45.5 pixels along each turned axis.
|
||||
#[test]
|
||||
fn far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix() {
|
||||
let (scale, turn) = (1.49_f64, 30_f64.to_radians());
|
||||
let matrix = [scale * turn.cos(), scale * turn.sin(), -scale * turn.sin(), scale * turn.cos(), 3.0, 5.0];
|
||||
let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", matrix);
|
||||
let far = assert_cells_in_place(&page, matrix, [250.0, 250.0, 390.0, 390.0], "turned and scaled");
|
||||
assert!(far >= 6, "{far} cells checked");
|
||||
}
|
||||
|
||||
/// A stroke painted with the pattern: the cells under a wide border far from the origin are
|
||||
/// in place on every side of it.
|
||||
#[test]
|
||||
fn far_cells_of_a_stroke_sit_at_whole_steps() {
|
||||
let page = render("/Pattern CS /P1 SCN 40 w 200 200 180 180 re S", IDENTITY);
|
||||
let mut checked = 0;
|
||||
// The border is 40 points wide around the square from (200, 200) to (380, 380).
|
||||
for band in [[180.0, 180.0, 400.0, 220.0], [180.0, 360.0, 400.0, 400.0], [180.0, 180.0, 220.0, 400.0], [360.0, 180.0, 400.0, 400.0]] {
|
||||
checked += assert_cells_in_place(&page, IDENTITY, band, "stroke");
|
||||
}
|
||||
assert!(checked >= 20, "{checked} cells checked");
|
||||
// Inside the border nothing is painted.
|
||||
let (cx, cy) = device(IDENTITY, 290.0, 290.0);
|
||||
let at = ((cy as usize) * page.width + cx as usize) * 4;
|
||||
assert_eq!(page.rgba.get(at..at + 3), Some(&[255, 255, 255][..]), "inside the stroked square");
|
||||
}
|
||||
|
||||
/// The cell pixmap's side and the scale its cell is drawn at: one step is exactly the side, the
|
||||
/// side stays within 1 and the cap whatever the step, and nothing odd reaches the cast.
|
||||
#[test]
|
||||
fn a_cell_pixmap_spans_exactly_one_step() {
|
||||
// 110 dpi, a step of 20: 30.56 pixels, drawn at 31 / 20.
|
||||
assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, 20.0, 3000.0), (31, 31.0 / 20.0));
|
||||
assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, -20.0, 3000.0), (31, 31.0 / 20.0), "a negative step");
|
||||
for (scale, step) in [(1.0_f32, 7.3_f32), (2.37, 0.9), (0.013, 1234.5), (3.0, 999.9), (1.0, 2.0e9)] {
|
||||
let (side, drawn) = hayro::tiling_cell_pixels(scale, step, 3000.0);
|
||||
assert!((1..=3000).contains(&side), "{scale} {step}: {side}");
|
||||
let span = drawn * f64::from(step);
|
||||
assert!((span - f64::from(side)).abs() < 1e-9 * f64::from(side), "{scale} {step}: a step spans {span}, not {side}");
|
||||
if f64::from(scale) * f64::from(step) <= 3000.0 {
|
||||
assert!((span - f64::from(scale) * f64::from(step)).abs() <= 0.5 + 1e-9, "{scale} {step}: drawn {drawn}");
|
||||
}
|
||||
}
|
||||
// A step under half a pixel still gets one pixel (a 0 × N pixmap can't be sampled).
|
||||
assert_eq!(hayro::tiling_cell_pixels(0.03, 10.0, 3000.0), (1, 0.1));
|
||||
// Steps and scales that aren't finite and positive: the side is bounded, the scale kept.
|
||||
assert_eq!(hayro::tiling_cell_pixels(2.0, f32::INFINITY, 3000.0), (3000, 2.0));
|
||||
assert_eq!(hayro::tiling_cell_pixels(2.0, 0.0, 3000.0), (1, 2.0));
|
||||
let (side, drawn) = hayro::tiling_cell_pixels(f32::NAN, 20.0, 3000.0);
|
||||
assert!(side == 1 && drawn.is_nan());
|
||||
// A cap past u16::MAX is lowered to it, and the scale follows the side the pixmap gets.
|
||||
let (side, drawn) = hayro::tiling_cell_pixels(2.0, 1.0e6, 1.0e9);
|
||||
assert_eq!(side, u16::MAX, "the cap is at most u16::MAX");
|
||||
assert!((drawn * 1.0e6 - f64::from(u16::MAX)).abs() < 1e-6, "a step spans the side: {drawn}");
|
||||
// A cap that is not a whole number, or not a number, is a whole number of pixels.
|
||||
assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, 30.7), (30, 0.3));
|
||||
assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, f32::NAN), (1, 0.01));
|
||||
}
|
||||
@@ -752,7 +752,7 @@ pub(crate) fn paint_page(
|
||||
let pointer = ui.input(|i| i.pointer.hover_pos());
|
||||
let hovered = pointer.and_then(|p| on_page.iter().rev().find(|(_, r)| r.contains(p))).map(|(n, _)| (*n).to_owned());
|
||||
let at: HashMap<&str, Rect> = on_page.iter().copied().collect();
|
||||
let zoom = (xf.rect.width() / xf.pw.max(1.0)).clamp(0.5, 3.0);
|
||||
let zoom = xf.zoom().clamp(0.5, 3.0);
|
||||
let focus = if view.hide_links { None } else { view.focus(selected) };
|
||||
// The focus's links, and the fields at either end of them (with the focus itself).
|
||||
let shown: Vec<&Link> = focus.as_deref().map(|f| listed.links.iter().filter(|l| l.from == f || l.to == f).collect()).unwrap_or_default();
|
||||
|
||||
@@ -391,6 +391,7 @@ impl PdfCraftApp {
|
||||
};
|
||||
self.marks_draft.replace = id.ends_with(".update");
|
||||
self.marks_draft.opened(kind);
|
||||
self.marks_draft.preview = None;
|
||||
self.dialog = Some(Dialog::Marks(kind));
|
||||
}
|
||||
"edit.bates" => {
|
||||
@@ -401,6 +402,7 @@ impl PdfCraftApp {
|
||||
self.marks_draft.hf.text[5] = "<<Bates Number#6#1##>>".into();
|
||||
}
|
||||
self.marks_draft.focused_box = 5;
|
||||
self.marks_draft.preview = None;
|
||||
self.dialog = Some(Dialog::Marks(pdfcraft_engine::MarkKind::HeaderFooter));
|
||||
}
|
||||
"edit.header_footer.remove" | "edit.watermark.remove" | "edit.background.remove" => {
|
||||
|
||||
@@ -510,7 +510,7 @@ pub(crate) fn after_refresh(view: &mut DocView, added: &[Added]) {
|
||||
pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, added: &[Added]) -> (Option<Edit>, bool) {
|
||||
let Some(page) = view.content.draft.as_ref().map(|d| d.page) else { return (None, false) };
|
||||
let Some(xf) = view.page_xform(page) else { return (None, false) };
|
||||
let zoom = xf.rect.width() / xf.pw.max(1.0);
|
||||
let zoom = xf.zoom();
|
||||
let Some(draft) = view.content.draft.as_mut() else { return (None, false) };
|
||||
let font = crate::edit_text_ui::editor_font(&draft.style, (draft.style.size as f32 * zoom).clamp(1.0, 300.0));
|
||||
let text = AddedText { text: draft.text.clone(), ..draft.style.clone() };
|
||||
|
||||
@@ -36,6 +36,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
let Some(dialog) = app.dialog else {
|
||||
app.props_draft = None;
|
||||
app.view_draft = None;
|
||||
app.custom_draft = None;
|
||||
return;
|
||||
};
|
||||
// Properties ▸ Fonts shows the fonts as they are now, after any content edits.
|
||||
@@ -49,6 +50,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
{
|
||||
app.props_draft = Some((id, INFO_KEYS.map(|k| doc.info_value(k).unwrap_or_default())));
|
||||
app.view_draft = Some((id, doc.initial_view()));
|
||||
app.custom_draft = Some((id, crate::CustomDraft { props: doc.custom_info(), ..Default::default() }));
|
||||
}
|
||||
let mut apply = false;
|
||||
let mut split_now: Option<crate::SplitPlan> = None;
|
||||
@@ -114,6 +116,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
(PropsTab::InitialView, tl!("Initial View")),
|
||||
(PropsTab::Security, tl!("Security")),
|
||||
(PropsTab::Fonts, tl!("Fonts")),
|
||||
(PropsTab::Custom, tl!("Custom")),
|
||||
(PropsTab::Advanced, tl!("Advanced")),
|
||||
] {
|
||||
if widgets::mode_tab(ui, label, tab == tb).clicked() {
|
||||
@@ -345,6 +348,89 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
row(ui, &f.name, detail);
|
||||
}
|
||||
}
|
||||
PropsTab::Custom => {
|
||||
// Add takes a new name, Update changes the value of the listed property the
|
||||
// Name field names, Delete removes it; OK writes the changes as one step.
|
||||
let editable = doc.allows_modification();
|
||||
let Some((_, d)) = app.custom_draft.as_mut() else { return };
|
||||
let l = ui.label(egui::RichText::new(tl!("Name:")).color(t.text_muted));
|
||||
ui.add_enabled(
|
||||
editable,
|
||||
widgets::line(&mut d.name).desired_width(420.0).background_color(t.field).id_salt("custom-name"),
|
||||
)
|
||||
.labelled_by(l.id);
|
||||
ui.end_row();
|
||||
let l = ui.label(egui::RichText::new(tl!("Value:")).color(t.text_muted));
|
||||
ui.add_enabled(
|
||||
editable,
|
||||
widgets::line(&mut d.value).desired_width(420.0).background_color(t.field).id_salt("custom-value"),
|
||||
)
|
||||
.labelled_by(l.id);
|
||||
ui.end_row();
|
||||
// Untrimmed: a file's `/Project#20` is not `/Project`, and a typed space is refused.
|
||||
let name = d.name.clone();
|
||||
let value = d.value.trim().to_owned();
|
||||
let listed = d.props.iter().position(|(k, _)| *k == name);
|
||||
// An entry the list leaves out (not text, only padding, or past its 256) keeps its value.
|
||||
let file_props = doc.custom_info();
|
||||
let unlisted = doc.has_info(&name) && !file_props.iter().any(|(k, _)| *k == name);
|
||||
let refused = pdfcraft_engine::check_custom_key(&name).err().filter(|_| !name.is_empty()).map(|e| e.to_string());
|
||||
ui.label("");
|
||||
// A file can hold a custom name that `check_custom_key` refuses, such as one
|
||||
// with a space: the tab lists it, and Add, Update and Delete stay off for it.
|
||||
let why = |b: egui::Response| match &refused {
|
||||
Some(why) => b.on_disabled_hover_text(crate::i18n::words(why)),
|
||||
None => b,
|
||||
};
|
||||
// A name that isn't UTF-8 is listed with U+FFFD and can't be written back as it is.
|
||||
let editable = editable && refused.is_none() && !name.contains(char::REPLACEMENT_CHARACTER);
|
||||
// `custom_info` lists at most 256 properties, and a new name goes after the file's
|
||||
// entries, so Add is off once the draft or the file's own list holds 256.
|
||||
let room = d.props.len() < 256 && file_props.len() < 256;
|
||||
ui.horizontal(|ui| {
|
||||
let add = editable && room && listed.is_none() && !unlisted && !name.is_empty() && !value.is_empty();
|
||||
if why(ui.add_enabled(add, egui::Button::new(tl!("Add")))).clicked() {
|
||||
d.props.push((name.clone(), value.clone()));
|
||||
d.name.clear();
|
||||
d.value.clear();
|
||||
}
|
||||
let update = editable && !value.is_empty() && listed.and_then(|n| d.props.get(n)).is_some_and(|(_, v)| *v != value);
|
||||
if why(ui.add_enabled(update, egui::Button::new(tl!("Update")))).clicked()
|
||||
&& let Some(p) = listed.and_then(|n| d.props.get_mut(n))
|
||||
{
|
||||
p.1 = value.clone();
|
||||
}
|
||||
if why(ui.add_enabled(editable && listed.is_some(), egui::Button::new(tl!("Delete")))).clicked()
|
||||
&& let Some(n) = listed.filter(|n| *n < d.props.len())
|
||||
{
|
||||
d.props.remove(n);
|
||||
d.name.clear();
|
||||
d.value.clear();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
if d.props.is_empty() {
|
||||
ui.label("");
|
||||
ui.label(egui::RichText::new(tl!("None")).color(t.text_faint));
|
||||
ui.end_row();
|
||||
}
|
||||
// A click on a property fills the fields with it; values are document data.
|
||||
let mut picked = None;
|
||||
for (k, v) in &d.props {
|
||||
if ui.selectable_label(*k == name, k.as_str()).clicked() {
|
||||
picked = Some((k.clone(), v.clone()));
|
||||
}
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_width(420.0);
|
||||
ui.add(egui::Label::new(v.as_str()).wrap());
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
if let Some((k, v)) = picked {
|
||||
d.name = k;
|
||||
d.value = v;
|
||||
}
|
||||
}
|
||||
PropsTab::Advanced => {
|
||||
row(ui, "PDF version", i.pdf_version.clone());
|
||||
row(ui, "Location", crate::bidi::visual(doc.path.as_deref().unwrap_or_default()).into_owned());
|
||||
@@ -1443,6 +1529,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
app.dialog = None;
|
||||
app.props_draft = None;
|
||||
app.view_draft = None;
|
||||
app.custom_draft = None;
|
||||
app.bulk_field_props = None;
|
||||
} else {
|
||||
app.dialog = Some(next);
|
||||
@@ -1494,6 +1581,18 @@ fn draft_changes(app: &PdfCraftApp) -> Option<Vec<Edit>> {
|
||||
{
|
||||
edits.push(Edit::SetInitialView(Box::new(v.clone())));
|
||||
}
|
||||
// Custom: deleted properties are cleared, then added and changed ones are set.
|
||||
if let Some((cid, d)) = &app.custom_draft
|
||||
&& cid == id
|
||||
{
|
||||
let before = doc.custom_info();
|
||||
for (k, _) in before.iter().filter(|(k, _)| !d.props.iter().any(|(n, _)| n == k)) {
|
||||
edits.push(Edit::SetInfo { key: k.clone(), value: String::new() });
|
||||
}
|
||||
for (k, v) in d.props.iter().filter(|(k, v)| !before.iter().any(|(n, w)| n == k && w == v)) {
|
||||
edits.push(Edit::SetInfo { key: k.clone(), value: v.clone() });
|
||||
}
|
||||
}
|
||||
Some(edits)
|
||||
}
|
||||
|
||||
|
||||
@@ -342,11 +342,37 @@ fn column_bar(ui: &mut egui::Ui, d: &mut FieldTableDraft, t: &theme::Tokens) {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let n = d.table.columns.len();
|
||||
let ends = edges(&d.shares());
|
||||
let active = column_dividers(ui, d, bar, &ends);
|
||||
|
||||
let painter = ui.painter_at(bar);
|
||||
// Input may have resized a pair; paint the shares after handling it.
|
||||
let shares = d.shares();
|
||||
let mut left = bar.left();
|
||||
for (c, (&right, share)) in edges(&shares).iter().zip(&shares).enumerate() {
|
||||
// The last column ends at the bar's edge, whatever rounding says.
|
||||
let right = if c + 1 == n { bar.right() } else { right.min(bar.right()) };
|
||||
let column = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom()));
|
||||
painter.rect_filled(column, CornerRadius::ZERO, SELECT_BLUE.gamma_multiply(if c % 2 == 0 { 0.11 } else { 0.055 }));
|
||||
if column.width() > 32.0 {
|
||||
painter.text(column.center(), egui::Align2::CENTER_CENTER, format!("{:.0}%", share * 100.0), theme::medium(11.0), t.text);
|
||||
}
|
||||
left = right;
|
||||
}
|
||||
painter.rect_stroke(bar, CornerRadius::same(3), Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
|
||||
for (i, &x) in edges(&shares).iter().enumerate().take(n.saturating_sub(1)) {
|
||||
let stroke = if active == Some(i) { Stroke::new(3.0, SELECT_BLUE) } else { Stroke::new(1.5, t.border) };
|
||||
painter.line_segment([pos2(x, bar.top() + 1.0), pos2(x, bar.bottom() - 1.0)], stroke);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle input at the pre-interaction edges and return the hovered, dragged or focused divider.
|
||||
fn column_dividers(ui: &mut egui::Ui, d: &mut FieldTableDraft, bar: Rect, ends: &[f32]) -> Option<usize> {
|
||||
let n = d.table.columns.len();
|
||||
// Wide enough to grab, never reaching past the middle of a column.
|
||||
let reach = (bar.width() / n.max(1) as f32 / 2.0).clamp(2.0, 8.0);
|
||||
let mut active = None;
|
||||
let ends = edges(&d.shares());
|
||||
for (i, &x) in ends.iter().enumerate().take(n.saturating_sub(1)) {
|
||||
let hit = Rect::from_min_max(pos2(x - reach, bar.top()), pos2(x + reach, bar.bottom()));
|
||||
let resp = ui.interact(hit, ui.id().with(("field table divider", i)), Sense::click_and_drag());
|
||||
@@ -374,24 +400,7 @@ fn column_bar(ui: &mut egui::Ui, d: &mut FieldTableDraft, t: &theme::Tokens) {
|
||||
}
|
||||
}
|
||||
|
||||
let painter = ui.painter_at(bar);
|
||||
let shares = d.shares();
|
||||
let mut left = bar.left();
|
||||
for (c, (&right, share)) in edges(&shares).iter().zip(&shares).enumerate() {
|
||||
// The last column ends at the bar's edge, whatever rounding says.
|
||||
let right = if c + 1 == n { bar.right() } else { right.min(bar.right()) };
|
||||
let column = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom()));
|
||||
painter.rect_filled(column, CornerRadius::ZERO, SELECT_BLUE.gamma_multiply(if c % 2 == 0 { 0.11 } else { 0.055 }));
|
||||
if column.width() > 32.0 {
|
||||
painter.text(column.center(), egui::Align2::CENTER_CENTER, format!("{:.0}%", share * 100.0), theme::medium(11.0), t.text);
|
||||
}
|
||||
left = right;
|
||||
}
|
||||
painter.rect_stroke(bar, CornerRadius::same(3), Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
|
||||
for (i, &x) in edges(&shares).iter().enumerate().take(n.saturating_sub(1)) {
|
||||
let stroke = if active == Some(i) { Stroke::new(3.0, SELECT_BLUE) } else { Stroke::new(1.5, t.border) };
|
||||
painter.line_segment([pos2(x, bar.top() + 1.0), pos2(x, bar.bottom() - 1.0)], stroke);
|
||||
}
|
||||
active
|
||||
}
|
||||
|
||||
/// The table being set up, on its page: each cell with its name, or the table's outline in red
|
||||
@@ -401,7 +410,7 @@ pub(crate) fn paint_preview(painter: &egui::Painter, xf: &PageXform, page: usize
|
||||
if preview.page != page {
|
||||
return;
|
||||
}
|
||||
let zoom = (xf.rect.width() / xf.pw.max(1.0)).clamp(0.5, 3.0);
|
||||
let zoom = xf.zoom().clamp(0.5, 3.0);
|
||||
let font = theme::regular((9.0 * zoom).clamp(7.0, 13.0));
|
||||
let on_screen = |r: [f64; 4]| xf.view_rect([r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);
|
||||
let outline = on_screen(preview.laid.table.rect);
|
||||
@@ -448,6 +457,62 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
fn bar_frame(ctx: &egui::Context, d: &mut FieldTableDraft, key: Option<egui::Key>, focus: Option<usize>) -> egui::FullOutput {
|
||||
let events = key
|
||||
.into_iter()
|
||||
.flat_map(|key| {
|
||||
[true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE })
|
||||
})
|
||||
.collect();
|
||||
ctx.run_ui(
|
||||
egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 160.0))), events, ..Default::default() },
|
||||
|ui| {
|
||||
let other = ui.button("Other control");
|
||||
if let Some(i) = focus {
|
||||
ui.memory_mut(|memory| memory.request_focus(ui.id().with(("field table divider", i))));
|
||||
} else {
|
||||
other.request_focus();
|
||||
}
|
||||
column_bar(ui, d, &theme::Tokens::get(ctx));
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_resize_only_the_focused_pair_and_paint_its_new_widths() {
|
||||
for columns in [3, 30] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(theme::font_definitions());
|
||||
let mut d = draft(columns);
|
||||
let before: Vec<f64> = d.table.columns.iter().map(|c| c.width).collect();
|
||||
let total: f64 = before.iter().sum();
|
||||
bar_frame(&ctx, &mut d, None, Some(0)).drop_without_applying_deltas();
|
||||
let output = bar_frame(&ctx, &mut d, Some(egui::Key::ArrowRight), Some(0));
|
||||
assert!((d.table.columns[0].width - before[0] - total * 0.01).abs() < 1e-9);
|
||||
assert!((d.table.columns[1].width - before[1] + total * 0.01).abs() < 1e-9);
|
||||
assert_eq!(d.table.columns.iter().skip(2).map(|c| c.width).collect::<Vec<_>>(), before[2..]);
|
||||
let painted: Vec<Rect> = output
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match &shape.shape {
|
||||
egui::Shape::Rect(r) if r.fill == SELECT_BLUE.gamma_multiply(0.11) || r.fill == SELECT_BLUE.gamma_multiply(0.055) => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(painted.len(), columns);
|
||||
let width: f32 = painted.iter().map(Rect::width).sum();
|
||||
assert!((f64::from(painted[0].width() / width) - d.shares()[0]).abs() < 1e-6, "paint the changed shares in the same frame");
|
||||
output.drop_without_applying_deltas();
|
||||
bar_frame(&ctx, &mut d, Some(egui::Key::ArrowLeft), Some(0)).drop_without_applying_deltas();
|
||||
assert!(d.table.columns.iter().zip(&before).all(|(c, w)| (c.width - w).abs() < 1e-9), "left reverses right on the focused divider");
|
||||
bar_frame(&ctx, &mut d, Some(egui::Key::ArrowRight), None).drop_without_applying_deltas();
|
||||
assert!(
|
||||
d.table.columns.iter().zip(&before).all(|(c, w)| (c.width - w).abs() < 1e-9),
|
||||
"arrows on another control leave the columns alone"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Thirty even columns leave each pair less than twice the least share a divider keeps: the
|
||||
/// two bounds crossed, and `f64::clamp` panicked on the first drag.
|
||||
#[test]
|
||||
|
||||
@@ -712,7 +712,7 @@ pub(crate) fn type_box(ctx: &egui::Context, view: &mut DocView, info: &DocInfo,
|
||||
let xf = view.page_xform(tb.page)?;
|
||||
let v = info.pages.get(tb.page)?.user_to_view(tb.at[0] as f32, tb.at[1] as f32);
|
||||
let pos = xf.norm_to_screen(v[0] / xf.pw, v[1] / xf.ph);
|
||||
let zoom = xf.rect.width() / xf.pw.max(1.0);
|
||||
let zoom = xf.zoom();
|
||||
let mut commit = false;
|
||||
let mut cancel = false;
|
||||
// Shown at once, like the paragraph editor: a fade-in shows the page's copy through it.
|
||||
|
||||
@@ -577,7 +577,7 @@ pub(crate) fn overlay(
|
||||
return None;
|
||||
};
|
||||
let rect = widget_rect(&xf, info, page, w.rect);
|
||||
let zoom = xf.rect.width() / xf.pw.max(1.0);
|
||||
let zoom = xf.zoom();
|
||||
let t = Tokens::get(ctx);
|
||||
let mut edit = None;
|
||||
let mut close = false;
|
||||
|
||||
@@ -374,9 +374,19 @@ pub enum PropsTab {
|
||||
InitialView,
|
||||
Security,
|
||||
Fonts,
|
||||
Custom,
|
||||
Advanced,
|
||||
}
|
||||
|
||||
/// Document Properties ▸ Custom being edited: the properties as they will be after OK, in order,
|
||||
/// and the Name and Value fields.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CustomDraft {
|
||||
pub props: Vec<(String, String)>,
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// Duplicate Field: the field and the pages (all, or a range, 1-based).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DuplicateDraft {
|
||||
@@ -782,6 +792,8 @@ pub struct PdfCraftApp {
|
||||
pub props_draft: Option<(DocId, [String; 4])>,
|
||||
/// Document Properties ▸ Initial View (and reading options) being edited.
|
||||
pub view_draft: Option<(DocId, pdfcraft_engine::InitialView)>,
|
||||
/// Document Properties ▸ Custom being edited.
|
||||
pub custom_draft: Option<(DocId, CustomDraft)>,
|
||||
/// Files picked asynchronously for combine / insert (web).
|
||||
pub requests: files::Requests,
|
||||
/// Native file pickers in flight (they never block the frame; see `pickers`).
|
||||
@@ -1161,6 +1173,7 @@ impl PdfCraftApp {
|
||||
save_override: None,
|
||||
props_draft: None,
|
||||
view_draft: None,
|
||||
custom_draft: None,
|
||||
requests: Default::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pickers: Default::default(),
|
||||
@@ -1284,14 +1297,19 @@ impl PdfCraftApp {
|
||||
}
|
||||
|
||||
/// Open a document the way it asks to be opened: navigation panel, layout, magnification,
|
||||
/// page (Document Properties ▸ Initial View). With Always use my default zoom and page
|
||||
/// layout on, the layout and magnification stay at the defaults the view opened with.
|
||||
/// page and the place on it (Document Properties ▸ Initial View, `/OpenAction`). With Always
|
||||
/// use my default zoom and page layout on, the layout and magnification stay at the defaults
|
||||
/// the view opened with, and the view goes to the opening page's top.
|
||||
fn apply_initial_view(&mut self, index: usize, v: &pdfcraft_engine::InitialView) {
|
||||
use pdfcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N};
|
||||
let pages = self.session.get(self.views[index].id).map_or(0, |d| d.info.pages.len());
|
||||
// A right panel the user closed stays closed, whatever the document asks for (#2884).
|
||||
// A document that asks for full screen gets the panel it names for outside it
|
||||
// (`/NonFullScreenPageMode`, Table 147), there when the prompt is declined or full
|
||||
// screen is left.
|
||||
let navigation = if v.full_screen { v.non_full_screen } else { v.navigation };
|
||||
if self.active == Some(index) && !self.right_panel_closed {
|
||||
match v.navigation {
|
||||
match navigation {
|
||||
N::PageOnly => {}
|
||||
N::Bookmarks => self.right = Some(RightPanel::Bookmarks),
|
||||
N::Pages => self.right = Some(RightPanel::Pages),
|
||||
@@ -1325,8 +1343,19 @@ impl PdfCraftApp {
|
||||
M::FitHeight => view.fit = canvas::Fit::Height,
|
||||
}
|
||||
}
|
||||
if v.page > 0 && v.page < pages {
|
||||
view.go_to_page(v.page);
|
||||
// The opening destination (`/OpenAction`, named destinations resolved): its page, and
|
||||
// where on it and how large, as a bookmark or link to it would (ISO 32000-2 Table 149).
|
||||
// With the default view kept, only the page.
|
||||
let info = self.session.get(view.id).map(|d| &d.info);
|
||||
match info.and_then(|i| i.open_dest.filter(|(page, _)| *page < pages).map(|d| (i, d))) {
|
||||
Some((info, (page, dest))) if !self.always_default_view => view.go_to_dest(page, dest, info),
|
||||
Some((_, (page, _))) => {
|
||||
if page > 0 {
|
||||
view.go_to_page(page);
|
||||
}
|
||||
}
|
||||
None if v.page > 0 && v.page < pages => view.go_to_page(v.page),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1526,16 +1555,18 @@ impl PdfCraftApp {
|
||||
// Read mode opens with the panes closed; the rail still opens them (#932). A right panel
|
||||
// the user closed stays closed (#1590).
|
||||
let opening_mode = self.mode_override.unwrap_or(self.default_mode);
|
||||
let initial = doc.initial_view();
|
||||
if activate && self.right.is_none() && !self.right_panel_closed && opening_mode != Mode::Read {
|
||||
self.right = if !doc.info.annotations.is_empty() {
|
||||
Some(RightPanel::Comments)
|
||||
} else if !doc.info.outline.is_empty() {
|
||||
// A full-screen document names its panel for outside full screen, and with
|
||||
// `/NonFullScreenPageMode /UseNone` (the default) no outline is visible (Table 147).
|
||||
} else if !doc.info.outline.is_empty() && !initial.full_screen {
|
||||
Some(RightPanel::Bookmarks)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
let initial = doc.initial_view();
|
||||
let view = DocView::new(id, &doc.info, self.view_defaults);
|
||||
self.views.push(view);
|
||||
if activate {
|
||||
@@ -2867,6 +2898,7 @@ impl PdfCraftApp {
|
||||
"properties" => Some(Dialog::Properties(PropsTab::Description)),
|
||||
"security" => Some(Dialog::Properties(PropsTab::Security)),
|
||||
"fonts" => Some(Dialog::Properties(PropsTab::Fonts)),
|
||||
"custom" => Some(Dialog::Properties(PropsTab::Custom)),
|
||||
"advanced" => Some(Dialog::Properties(PropsTab::Advanced)),
|
||||
"shortcuts" => Some(Dialog::Shortcuts),
|
||||
"split" => Some(Dialog::Split),
|
||||
|
||||
@@ -7,7 +7,7 @@ use egui::{Align, Color32, CornerRadius, Layout, Rect, Stroke, pos2, vec2};
|
||||
use pdfcraft_engine::{Backdrop, Background, DocId, Edit, FontFamily, HeaderFooter, MarkKind, Watermark};
|
||||
|
||||
use crate::theme::{self, Tokens};
|
||||
use crate::{PdfCraftApp, widgets};
|
||||
use crate::{PdfCraftApp, icons, widgets};
|
||||
|
||||
/// How far a watermark may be moved from the page centre, in points.
|
||||
const MAX_OFFSET: f64 = 20_000.0;
|
||||
@@ -199,6 +199,9 @@ pub struct MarksDraft {
|
||||
pub file_page: usize,
|
||||
/// Background: pages that paint their own backdrop.
|
||||
pub backdrops: BackdropCheck,
|
||||
/// The page (0-based) the preview was stepped to; `None` previews the current page. Reset
|
||||
/// each time the dialog opens.
|
||||
pub preview: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for MarksDraft {
|
||||
@@ -217,6 +220,7 @@ impl Default for MarksDraft {
|
||||
file: None,
|
||||
file_page: 1,
|
||||
backdrops: BackdropCheck::default(),
|
||||
preview: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,6 +286,24 @@ fn preview_page(range: &PageRange, current: usize, count: usize) -> usize {
|
||||
if pages.contains(¤t) { current } else { pages.first().copied().unwrap_or(current) }
|
||||
}
|
||||
|
||||
/// [`preview_page`] for the page stepped to (`stepped`), or the current page if none. A page
|
||||
/// stepped to that the range leaves out is replaced by the page shown, so widening the range again
|
||||
/// keeps that page rather than jumping back.
|
||||
fn shown_preview(range: &PageRange, stepped: &mut Option<usize>, current: usize, count: usize) -> usize {
|
||||
let shown = preview_page(range, stepped.unwrap_or(current), count);
|
||||
if stepped.is_some() {
|
||||
*stepped = Some(shown);
|
||||
}
|
||||
shown
|
||||
}
|
||||
|
||||
/// The page the preview steps to from `shown`: the range's next page after it (`forward`) or the
|
||||
/// last one before it, or `None` at either end.
|
||||
fn step_preview(range: &PageRange, shown: usize, count: usize, forward: bool) -> Option<usize> {
|
||||
let pages = range.pages(count);
|
||||
if forward { pages.into_iter().find(|&p| p > shown) } else { pages.into_iter().rev().find(|&p| p < shown) }
|
||||
}
|
||||
|
||||
/// The dialog for `kind`; returns (apply, cancel).
|
||||
pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: MarkKind) -> (bool, bool) {
|
||||
let Some((i, id)) = app.active_ids() else { return (false, true) };
|
||||
@@ -456,10 +478,10 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M
|
||||
ui.label(egui::RichText::new(tl!("Page Range Options")).font(theme::semibold(12.5)));
|
||||
d.range.ui(ui, count);
|
||||
ui.add_space(8.0);
|
||||
// The preview: the current page, or the first one the range selects if it leaves that out,
|
||||
// drawn from its thumbnail at its displayed size (after /Rotate), the frame the engine lays
|
||||
// the marks out in.
|
||||
let target = preview_page(&d.range, current, count);
|
||||
// The preview: the current page (or the page stepped to), or the first one the range selects
|
||||
// if it leaves that out, drawn from its thumbnail at its displayed size (after /Rotate), the
|
||||
// frame the engine lays the marks out in.
|
||||
let target = shown_preview(&d.range, &mut d.preview, current, count);
|
||||
let page = doc.info.pages.get(target).map(|p| (p.width as f64, p.height as f64)).unwrap_or((612.0, 792.0));
|
||||
let picture = app.views.get_mut(i).and_then(|view| {
|
||||
view.need_thumbnail(target, true);
|
||||
@@ -538,14 +560,24 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M
|
||||
MarkKind::Background => {}
|
||||
});
|
||||
ui.vertical(|ui| {
|
||||
ui.label(
|
||||
egui::RichText::new(crate::i18n::fmt(
|
||||
tl!("Preview: page {p} of {n}"),
|
||||
&[("p", &(target + 1).to_string()), ("n", &count.to_string())],
|
||||
))
|
||||
.small()
|
||||
.color(t.text_faint),
|
||||
);
|
||||
ui.horizontal(|ui| {
|
||||
// Steps through the pages the range selects.
|
||||
let (back, next) = (step_preview(&d.range, target, count, false), step_preview(&d.range, target, count, true));
|
||||
if ui.add_enabled_ui(back.is_some(), |ui| icons::button(ui, "chevron-left", 22.0, false, tl!("Previous page"))).inner.clicked() {
|
||||
d.preview = back.or(d.preview);
|
||||
}
|
||||
ui.label(
|
||||
egui::RichText::new(crate::i18n::fmt(
|
||||
tl!("Preview: page {p} of {n}"),
|
||||
&[("p", &(target + 1).to_string()), ("n", &count.to_string())],
|
||||
))
|
||||
.small()
|
||||
.color(t.text_faint),
|
||||
);
|
||||
if ui.add_enabled_ui(next.is_some(), |ui| icons::button(ui, "chevron-right", 22.0, false, tl!("Next page"))).inner.clicked() {
|
||||
d.preview = next.or(d.preview);
|
||||
}
|
||||
});
|
||||
let n = d.range.pages(count).len();
|
||||
let applies =
|
||||
if n == 1 { tl!("Applies to 1 page").to_string() } else { crate::i18n::fmt(tl!("Applies to {n} pages"), &[("n", &n.to_string())]) };
|
||||
@@ -751,6 +783,40 @@ mod tests {
|
||||
assert_eq!(preview_page(&all, 0, 0), 0, "no pages at all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_steps_through_the_pages_the_range_selects() {
|
||||
let odd = PageRange { all: true, subset: Subset::Odd, ..PageRange::default() };
|
||||
// Pages 1, 3 and 5 (0-based 0, 2, 4) of 5.
|
||||
assert_eq!(step_preview(&odd, 0, 5, true), Some(2));
|
||||
assert_eq!(step_preview(&odd, 2, 5, true), Some(4));
|
||||
assert_eq!(step_preview(&odd, 4, 5, true), None, "the last page has no next");
|
||||
assert_eq!(step_preview(&odd, 4, 5, false), Some(2));
|
||||
assert_eq!(step_preview(&odd, 0, 5, false), None, "the first page has no previous");
|
||||
// From a page the range leaves out, to the nearest one it selects on that side.
|
||||
assert_eq!(step_preview(&odd, 1, 5, true), Some(2));
|
||||
assert_eq!(step_preview(&odd, 1, 5, false), Some(0));
|
||||
assert_eq!(step_preview(&odd, 0, 0, true), None, "no pages at all");
|
||||
// A page stepped to is previewed while the range selects it, and the range's first page
|
||||
// once a new range leaves it out.
|
||||
assert_eq!(preview_page(&odd, 2, 5), 2);
|
||||
let later = PageRange { all: false, from: 4, to: 5, subset: Subset::All };
|
||||
assert_eq!(preview_page(&later, 2, 5), 3);
|
||||
// Narrowing the range past the page stepped to keeps the page shown instead, also once
|
||||
// the range is widened again.
|
||||
let mut stepped = Some(4);
|
||||
let first_two = PageRange { all: false, from: 1, to: 2, subset: Subset::All };
|
||||
assert_eq!(shown_preview(&first_two, &mut stepped, 1, 5), 0);
|
||||
assert_eq!(stepped, Some(0));
|
||||
assert_eq!(shown_preview(&PageRange::default(), &mut stepped, 1, 5), 0);
|
||||
// A page stepped to inside the range stays; with none stepped to, the current page shows.
|
||||
let mut stepped = Some(2);
|
||||
assert_eq!(shown_preview(&odd, &mut stepped, 0, 5), 2);
|
||||
assert_eq!(stepped, Some(2));
|
||||
let mut stepped = None;
|
||||
assert_eq!(shown_preview(&odd, &mut stepped, 4, 5), 4);
|
||||
assert_eq!(stepped, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_tints_the_page_it_is_behind() {
|
||||
assert_eq!(behind([1.0, 0.0, 0.0], 1.0), Color32::from_rgb(255, 0, 0));
|
||||
|
||||
@@ -208,7 +208,7 @@ pub(crate) fn page_input(
|
||||
if state.paths.as_ref().is_none_or(|(p, g, _)| *p != page || *g != doc.edit_generation()) {
|
||||
state.paths = Some((page, doc.edit_generation(), doc.measurement_paths(page)));
|
||||
}
|
||||
let pixels_per_unit = (xf.rect.width() / xf.pw).max(1e-6);
|
||||
let pixels_per_unit = xf.zoom().max(1e-6);
|
||||
if let Some((_, _, Err(e))) = &state.paths {
|
||||
state.error = Some(e.clone());
|
||||
}
|
||||
|
||||
@@ -1139,7 +1139,10 @@ fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineIte
|
||||
if let Some(levels) = cx.expand {
|
||||
ui.data_mut(|d| d.insert_temp(id, depth < levels));
|
||||
}
|
||||
let mut open = cx.searching || ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(item.open || depth == 0);
|
||||
// A bookmark opens as the file says at every level: a positive /Count is open, a negative
|
||||
// one (or none) closed (ISO 32000-2 §12.3.3, Table 151). The reader's own toggles and a
|
||||
// search override it.
|
||||
let mut open = cx.searching || ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(item.open);
|
||||
let x_text = indent + 20.0;
|
||||
if let Some((rpath, text)) = cx.rename.as_mut()
|
||||
&& rpath.as_slice() == path
|
||||
|
||||
@@ -543,7 +543,7 @@ pub(crate) fn paint_page(ui: &egui::Ui, painter: &egui::Painter, xf: &PageXform,
|
||||
let prep = &view.prepare;
|
||||
let pointer = ui.input(|i| i.pointer.hover_pos());
|
||||
let grab = prep.grab.filter(|(gp, ..)| *gp == page);
|
||||
let zoom = (xf.rect.width() / xf.pw.max(1.0)).clamp(0.5, 3.0);
|
||||
let zoom = xf.zoom().clamp(0.5, 3.0);
|
||||
for f in form {
|
||||
for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {
|
||||
let mut r = screen_rect(xf, info, page, w.rect);
|
||||
|
||||
@@ -77,6 +77,7 @@ fn new_rename_reorder_indent_delete_and_undo() {
|
||||
|
||||
menu(&mut h, "Results", "Indent");
|
||||
assert_eq!(outline(&h), [("Intro".into(), Some(0), 0), ("Results".into(), Some(2), 1)]);
|
||||
h.get_by_label("Results"); // its new parent opened, so it still shows
|
||||
menu(&mut h, "Results", "Outdent");
|
||||
menu(&mut h, "Results", "Move up");
|
||||
assert_eq!(outline(&h)[0].0, "Results");
|
||||
@@ -310,3 +311,60 @@ fn style_and_colour_from_the_bookmark_menu() {
|
||||
h.run_steps(3);
|
||||
assert!(look(&h).0, "undoable");
|
||||
}
|
||||
|
||||
/// Top-level bookmarks open as the file says, like every other level: a positive /Count shows
|
||||
/// the children, a negative one hides them until the reader opens it (ISO 32000-2 §12.3.3,
|
||||
/// Table 151). They used to open regardless.
|
||||
#[test]
|
||||
fn a_closed_top_level_bookmark_opens_closed() {
|
||||
const OUTLINED: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /Outlines 10 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
|
||||
10 0 obj << /Type /Outlines /First 11 0 R /Last 13 0 R /Count 5 >> endobj
|
||||
11 0 obj << /Title (Closed parent) /Parent 10 0 R /Next 12 0 R /First 21 0 R /Last 22 0 R /Count -2 /Dest [3 0 R /Fit] >> endobj
|
||||
12 0 obj << /Title (Open parent) /Parent 10 0 R /Prev 11 0 R /Next 13 0 R /First 23 0 R /Last 24 0 R /Count 2 /Dest [3 0 R /Fit] >> endobj
|
||||
13 0 obj << /Title (Uncounted parent) /Parent 10 0 R /Prev 12 0 R /First 25 0 R /Last 25 0 R /Dest [3 0 R /Fit] >> endobj
|
||||
21 0 obj << /Title (Closed child A) /Parent 11 0 R /Next 22 0 R /Dest [3 0 R /Fit] >> endobj
|
||||
22 0 obj << /Title (Closed child B) /Parent 11 0 R /Prev 21 0 R /Dest [3 0 R /Fit] >> endobj
|
||||
23 0 obj << /Title (Open child A) /Parent 12 0 R /Next 24 0 R /Dest [3 0 R /Fit] >> endobj
|
||||
24 0 obj << /Title (Open child B) /Parent 12 0 R /Prev 23 0 R /Dest [3 0 R /Fit] >> endobj
|
||||
25 0 obj << /Title (Uncounted child) /Parent 13 0 R /Dest [3 0 R /Fit] >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
let mut h = harness();
|
||||
h.state_mut().open_bytes("outlined.pdf", None, OUTLINED.to_vec()).unwrap();
|
||||
h.run_steps(4);
|
||||
let shown = |h: &Harness<'static, PdfCraftApp>, t: &str| h.query_by_label(t).is_some();
|
||||
assert!(shown(&h, "Closed parent") && shown(&h, "Open parent") && shown(&h, "Uncounted parent"));
|
||||
assert!(!shown(&h, "Closed child A") && !shown(&h, "Closed child B"), "a negative /Count opens closed");
|
||||
assert!(shown(&h, "Open child A") && shown(&h, "Open child B"), "a positive /Count opens open");
|
||||
assert!(!shown(&h, "Uncounted child"), "only a positive /Count opens a bookmark");
|
||||
|
||||
// The disclosure triangle at the row's left still opens and closes it.
|
||||
let toggle = |h: &mut Harness<'static, PdfCraftApp>, title: &str| {
|
||||
let row = h.get_by_label(title).rect();
|
||||
let at = egui::pos2(row.left() + 8.0, row.top() + 14.0);
|
||||
h.hover_at(at);
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(3);
|
||||
};
|
||||
toggle(&mut h, "Closed parent");
|
||||
assert!(shown(&h, "Closed child A") && shown(&h, "Closed child B"), "opened by the reader");
|
||||
toggle(&mut h, "Closed parent");
|
||||
assert!(!shown(&h, "Closed child A"), "closed again");
|
||||
toggle(&mut h, "Open parent");
|
||||
assert!(!shown(&h, "Open child A"), "an open bookmark closes");
|
||||
|
||||
// A search still shows the matches inside a closed bookmark, and clearing it restores it.
|
||||
h.get_by_label("Search").click();
|
||||
h.run_steps(1);
|
||||
h.get_by_label("Search").type_text("child B");
|
||||
h.run_steps(3);
|
||||
assert!(shown(&h, "Closed child B") && shown(&h, "Open child B"));
|
||||
h.get_by_label("Clear").click();
|
||||
h.run_steps(3);
|
||||
assert!(!shown(&h, "Closed child B") && !shown(&h, "Open child B"), "search leaves the open state alone");
|
||||
}
|
||||
|
||||
@@ -1153,6 +1153,216 @@ fn cancelling_properties_discards_the_draft() {
|
||||
assert!(h.state().props_draft.is_none());
|
||||
}
|
||||
|
||||
fn custom_properties(h: &Harness<'static, PdfCraftApp>) -> Vec<(String, String)> {
|
||||
let app = h.state();
|
||||
app.session.get(app.views[0].id).unwrap().custom_info()
|
||||
}
|
||||
|
||||
fn type_into(h: &mut Harness<'static, PdfCraftApp>, label: &str, text: &str) {
|
||||
let field = h.get_by_role_and_label(Role::TextInput, label);
|
||||
field.focus();
|
||||
field.type_text(text);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn clear(h: &mut Harness<'static, PdfCraftApp>, label: &str) {
|
||||
h.get_by_role_and_label(Role::TextInput, label).focus();
|
||||
h.run_steps(1);
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
|
||||
h.key_press(Key::Backspace);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_properties_are_added_in_the_custom_tab_as_one_undoable_step() {
|
||||
let mut h = harness(1, |app| app.set_option("dialog", "custom").unwrap());
|
||||
h.get_by_label("None");
|
||||
type_into(&mut h, "Name:", "Project");
|
||||
type_into(&mut h, "Value:", "Apollo");
|
||||
h.get_by_role_and_label(Role::Button, "Add").click();
|
||||
h.run_steps(3);
|
||||
assert!(custom_properties(&h).is_empty(), "nothing is written before OK");
|
||||
h.get_by_label("Project");
|
||||
type_into(&mut h, "Name:", "Revision");
|
||||
type_into(&mut h, "Value:", "4");
|
||||
h.get_by_role_and_label(Role::Button, "Add").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(custom_properties(&h), [("Project".to_string(), "Apollo".to_string()), ("Revision".to_string(), "4".to_string())]);
|
||||
let app = h.state();
|
||||
assert_eq!(app.session.get(app.views[0].id).unwrap().can_undo(), Some("Change document properties"));
|
||||
assert!(app.dialog.is_none() && app.custom_draft.is_none());
|
||||
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
|
||||
h.run_steps(3);
|
||||
assert!(custom_properties(&h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_properties_are_changed_and_deleted_in_the_custom_tab() {
|
||||
let mut h = harness(1, |app| {
|
||||
for (key, value) in [("Project", "Apollo"), ("Revision", "4")] {
|
||||
assert!(app.apply_edit(pdfcraft_engine::Edit::SetInfo { key: key.into(), value: value.into() }));
|
||||
}
|
||||
app.set_option("dialog", "custom").unwrap();
|
||||
});
|
||||
h.get_by_label("Revision").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::Button, "Delete").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Project").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.get_by_role_and_label(Role::Button, "Update").accesskit_node().is_disabled(), "the value is unchanged");
|
||||
clear(&mut h, "Value:");
|
||||
type_into(&mut h, "Value:", "Apollo 2");
|
||||
h.get_by_role_and_label(Role::Button, "Update").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(custom_properties(&h), [("Project".to_string(), "Apollo 2".to_string())]);
|
||||
let app = h.state();
|
||||
let doc = app.session.get(app.views[0].id).unwrap();
|
||||
assert_eq!(doc.info_value("Revision"), None);
|
||||
assert_eq!(doc.can_undo(), Some("Change document properties"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_custom_tab_refuses_names_a_custom_property_cannot_have() {
|
||||
let mut h = harness(1, |app| {
|
||||
assert!(app.apply_edit(pdfcraft_engine::Edit::SetInfo { key: "Project".into(), value: "Apollo".into() }));
|
||||
app.set_option("dialog", "custom").unwrap();
|
||||
});
|
||||
type_into(&mut h, "Value:", "x");
|
||||
let add_disabled = |h: &Harness<'static, PdfCraftApp>| h.get_by_role_and_label(Role::Button, "Add").accesskit_node().is_disabled();
|
||||
assert!(add_disabled(&h), "no name");
|
||||
// A standard name, a name with a space, a delimiter, and a name already listed.
|
||||
for name in ["Title", "Client name", "R&D/2", "Project"] {
|
||||
type_into(&mut h, "Name:", name);
|
||||
assert!(add_disabled(&h), "{name} is refused");
|
||||
clear(&mut h, "Name:");
|
||||
}
|
||||
type_into(&mut h, "Name:", "Client");
|
||||
assert!(!add_disabled(&h));
|
||||
assert!(h.get_by_role_and_label(Role::Button, "Delete").accesskit_node().is_disabled(), "Client is not listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_property_whose_name_the_tools_refuse_is_listed_and_left_alone() {
|
||||
// `/Client#20name` and `/Project#20` are valid PDF names with a space in them, which a new custom
|
||||
// property can't have; `/Project#20` is not `/Project`. `/Dept#E9` is not UTF-8 and is listed as
|
||||
// "Dept\u{FFFD}". `/Revision` is a number, so it isn't listed.
|
||||
let pdf = String::from_utf8(fixture(1)).unwrap().replace(
|
||||
"/Root 1 0 R >>\nstartxref",
|
||||
"/Root 1 0 R /Info << /Client#20name (Acme) /Project#20 (Padded) /Dept#E9 (Sales) /Project (Apollo) /Revision 4 >> >>\nstartxref",
|
||||
);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("doc.pdf", None, pdf.into_bytes()).expect("fixture opens");
|
||||
app.set_option("dialog", "custom").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
for name in ["Client name", "Project ", "Dept\u{FFFD}"] {
|
||||
h.get_by_label(name).click();
|
||||
h.run_steps(3);
|
||||
for button in ["Update", "Delete"] {
|
||||
assert!(h.get_by_role_and_label(Role::Button, button).accesskit_node().is_disabled(), "{button} is off for {name:?}");
|
||||
}
|
||||
}
|
||||
clear(&mut h, "Name:");
|
||||
type_into(&mut h, "Name:", "Revision");
|
||||
assert!(h.get_by_role_and_label(Role::Button, "Add").accesskit_node().is_disabled(), "Add would overwrite the number");
|
||||
assert_eq!(h.state().custom_draft.as_ref().map(|(_, d)| d.value.as_str()), Some("Sales"));
|
||||
h.get_by_label("Project").click();
|
||||
h.run_steps(3);
|
||||
clear(&mut h, "Value:");
|
||||
type_into(&mut h, "Value:", "Gemini");
|
||||
h.get_by_role_and_label(Role::Button, "Update").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(
|
||||
custom_properties(&h),
|
||||
[
|
||||
("Client name".to_string(), "Acme".to_string()),
|
||||
("Project ".to_string(), "Padded".to_string()),
|
||||
("Dept\u{FFFD}".to_string(), "Sales".to_string()),
|
||||
("Project".to_string(), "Gemini".to_string())
|
||||
]
|
||||
);
|
||||
let app = h.state();
|
||||
let doc = app.session.get(app.views[0].id).unwrap();
|
||||
assert!(doc.has_info("Revision") && doc.info_value("Revision").is_none(), "the number is kept");
|
||||
assert!(app.dialog.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_property_is_deleted_from_an_info_dictionary_in_the_trailer() {
|
||||
let pdf = String::from_utf8(fixture(1))
|
||||
.unwrap()
|
||||
.replace("/Root 1 0 R >>\nstartxref", "/Root 1 0 R /Info << /Project (Apollo) /Revision (4) >> >>\nstartxref");
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("doc.pdf", None, pdf.into_bytes()).expect("fixture opens");
|
||||
app.set_option("dialog", "custom").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Project").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::Button, "Delete").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(custom_properties(&h), [("Revision".to_string(), "4".to_string())]);
|
||||
let app = h.state();
|
||||
assert_eq!(app.session.get(app.views[0].id).unwrap().can_undo(), Some("Change document properties"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_stops_at_the_256_custom_properties_the_tab_lists() {
|
||||
let with_props = |count: usize| {
|
||||
let entries: String = (0..count).map(|n| format!("/P{n:03} (v) ")).collect();
|
||||
let pdf =
|
||||
String::from_utf8(fixture(1)).unwrap().replace("/Root 1 0 R >>\nstartxref", &format!("/Root 1 0 R /Info << {entries}>> >>\nstartxref"));
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("doc.pdf", None, pdf.into_bytes()).expect("fixture opens");
|
||||
app.set_option("dialog", "custom").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
h
|
||||
};
|
||||
let add_disabled = |h: &Harness<'static, PdfCraftApp>| h.get_by_role_and_label(Role::Button, "Add").accesskit_node().is_disabled();
|
||||
|
||||
// 255 in the file: one more fits, a second does not.
|
||||
let mut h = with_props(255);
|
||||
type_into(&mut h, "Name:", "Client");
|
||||
type_into(&mut h, "Value:", "Acme");
|
||||
assert!(!add_disabled(&h));
|
||||
h.get_by_role_and_label(Role::Button, "Add").click();
|
||||
h.run_steps(3);
|
||||
type_into(&mut h, "Name:", "Other");
|
||||
type_into(&mut h, "Value:", "x");
|
||||
assert!(add_disabled(&h), "the draft holds 256");
|
||||
assert_eq!(h.state().custom_draft.as_ref().map(|(_, d)| d.props.len()), Some(256));
|
||||
|
||||
// 257 in the file: after a Delete a new name would still be past the 256 listed.
|
||||
let mut h = with_props(257);
|
||||
h.get_by_label("P000").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::Button, "Delete").click();
|
||||
h.run_steps(3);
|
||||
type_into(&mut h, "Name:", "Client");
|
||||
type_into(&mut h, "Value:", "Acme");
|
||||
assert!(add_disabled(&h), "the file lists 256");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_menu_names_the_step_to_undo() {
|
||||
let mut h = harness(2, |app| {
|
||||
|
||||
@@ -237,6 +237,51 @@ fn fill_text_size_resizes_the_selected_text() {
|
||||
assert!(after > before * 2.0, "36 pt text has a taller box than 10 pt text: {before} -> {after}");
|
||||
}
|
||||
|
||||
/// The font sizes of the texts `text` drawn in the last frame.
|
||||
fn drawn_sizes(h: &Harness<'static, PdfCraftApp>, text: &str) -> Vec<f32> {
|
||||
fn walk(shape: &egui::Shape, text: &str, out: &mut Vec<f32>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, text, out)),
|
||||
egui::Shape::Text(t) if t.galley.text() == text => {
|
||||
out.extend(t.galley.job.sections.first().map(|s| s.format.font_id.size));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for clipped in &h.output().shapes {
|
||||
walk(&clipped.shape, text, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The type box draws its text at the page's zoom whichever way the view is turned. With the
|
||||
/// view turned a quarter, the page's width runs down the screen: reading the zoom off the screen
|
||||
/// rectangle's width instead made the typed text a height-over-width too large (here 4/3).
|
||||
#[test]
|
||||
fn the_type_box_text_matches_the_page_zoom_in_a_turned_view() {
|
||||
for rotate in ["0", "90"] {
|
||||
let mut h = harness();
|
||||
h.state_mut().set_option("rotate", rotate).unwrap();
|
||||
h.run_steps(3);
|
||||
h.state_mut().execute("sign.fill.text");
|
||||
click(&mut h, 50.0, 250.0);
|
||||
h.event(egui::Event::Text("Ada".into()));
|
||||
h.run_steps(2);
|
||||
let s = h.state();
|
||||
let page = &s.session.get(s.views[0].id).unwrap().info.pages[0];
|
||||
let rect = s.views[0].page_screen_rect(0).expect("on screen");
|
||||
// Screen pixels per page point: the page's width lies across, or down when turned.
|
||||
let zoom = if rotate == "90" { rect.height() } else { rect.width() } / page.width;
|
||||
let size = s.views[0].fill_text.as_ref().expect("an open type box").size as f32;
|
||||
let drawn = drawn_sizes(&h, "Ada");
|
||||
assert!(!drawn.is_empty(), "{rotate}°: the typed text is drawn");
|
||||
for d in drawn {
|
||||
assert!((d - size * zoom).abs() < 0.5, "{rotate}°: drawn at {d}, the page shows it at {}", size * zoom);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_box_grows_as_text_is_typed() {
|
||||
let mut h = harness();
|
||||
|
||||
@@ -50,6 +50,7 @@ mod links;
|
||||
mod marks;
|
||||
mod object_selection;
|
||||
mod ocr;
|
||||
mod open_action;
|
||||
mod organize_drag;
|
||||
mod pageboxes;
|
||||
mod panel_snapshots;
|
||||
|
||||
@@ -372,6 +372,35 @@ fn the_preview_shows_the_page_the_range_selects_under_the_marks() {
|
||||
assert_eq!(tint, egui::Color32::from_rgb(red, green, blue), "the default background colour, opaque");
|
||||
}
|
||||
|
||||
/// The preview's page stepper, beside its "page N of M" label: the dialog's own button, not the
|
||||
/// page navigation's of the same name.
|
||||
fn preview_step(h: &mut Harness<'static, PdfCraftApp>, label: &str, now: &str) {
|
||||
let row = h.get_by_label(now).rect().center().y;
|
||||
h.query_all_by_label(label).find(|n| (n.rect().center().y - row).abs() < 15.0).unwrap_or_else(|| panic!("{label} beside {now:?}")).click();
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_steps_through_the_pages_and_starts_at_the_current_one() {
|
||||
let mut h = harness();
|
||||
h.state_mut().views[0].go_to_page(1);
|
||||
h.run_steps(2);
|
||||
assert!(h.state_mut().execute("edit.watermark"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Preview: page 2 of 3");
|
||||
preview_step(&mut h, "Next page", "Preview: page 2 of 3");
|
||||
h.get_by_label("Preview: page 3 of 3");
|
||||
preview_step(&mut h, "Previous page", "Preview: page 3 of 3");
|
||||
preview_step(&mut h, "Previous page", "Preview: page 2 of 3");
|
||||
h.get_by_label("Preview: page 1 of 3");
|
||||
// Opened again, the preview is back at the current page.
|
||||
h.get_by_label("Cancel").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state_mut().execute("edit.watermark"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Preview: page 2 of 3");
|
||||
}
|
||||
|
||||
/// Pages from 1 to 1 stays one page: the dialog used to turn "to" back into the last page on
|
||||
/// every frame while both were 1, so only page 1 could not be chosen alone. The field starts on
|
||||
/// the last page.
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! A document opens where its `/OpenAction` says (ISO 32000-2 §12.3.2.2 Table 149, §12.3.2.4):
|
||||
//! the page, and the place on it, of an explicit destination, a go-to action's or a named one;
|
||||
//! and a full-screen document's `/NonFullScreenPageMode` panel (Table 147).
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use pdfcraft_render::DestView;
|
||||
use pdfcraft_ui_egui::canvas::Fit;
|
||||
use pdfcraft_ui_egui::{PdfCraftApp, RightPanel};
|
||||
|
||||
/// Six Letter (612×792) pages, objects 3 to 8; `catalog` is added to the catalog dictionary.
|
||||
/// Object 9 is an outline (one bookmark, object 10) that `/Outlines 9 0 R` can use.
|
||||
fn fixture(catalog: &str) -> Vec<u8> {
|
||||
let n = 6;
|
||||
let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 3 + i)).collect();
|
||||
let mut objs = vec![format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"), format!("<< /Type /Pages /Kids [{}] /Count {n} >>", kids.join(" "))];
|
||||
for _ in 0..n {
|
||||
objs.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_string());
|
||||
}
|
||||
objs.push("<< /Type /Outlines /First 10 0 R /Last 10 0 R /Count 1 >>".to_string());
|
||||
objs.push("<< /Title (Chapter) /Parent 9 0 R /Dest [6 0 R /Fit] >>".to_string());
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn harness(catalog: &str) -> Harness<'static, PdfCraftApp> {
|
||||
let bytes = fixture(catalog);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.open_bytes("open.pdf", None, bytes).expect("opens");
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
settle(&mut h);
|
||||
h
|
||||
}
|
||||
|
||||
/// Run frames until rendering has finished and the layout holds still.
|
||||
fn settle(h: &mut Harness<'static, PdfCraftApp>) {
|
||||
for _ in 0..200 {
|
||||
h.run_steps(2);
|
||||
if !h.state().render_pending() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
/// The page at the top of the window and the user-space height there: where a bookmark made now
|
||||
/// (⌘B) goes.
|
||||
fn window_top(h: &mut Harness<'static, PdfCraftApp>) -> (usize, f32) {
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::B);
|
||||
h.run_steps(3);
|
||||
let id = h.state().views[0].id;
|
||||
let outline = &h.state().session.get(id).unwrap().info.outline;
|
||||
let made = outline.iter().find(|b| b.title == "Untitled").expect("the new bookmark");
|
||||
match made.view {
|
||||
DestView::Xyz { top: Some(top), .. } => (made.page.expect("a page"), top),
|
||||
other => panic!("expected /XYZ with a top, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The left edge of `page` on screen and its scale (screen points per user-space point).
|
||||
fn page_left(h: &Harness<'static, PdfCraftApp>, page: usize) -> (f32, f32) {
|
||||
let rects = h.state().views[0].visible_page_rects();
|
||||
let (_, r) = rects.iter().find(|(p, _)| *p == page).expect("the page is shown");
|
||||
(r.left(), r.width() / 612.0)
|
||||
}
|
||||
|
||||
fn near(got: f32, want: f32, what: &str) {
|
||||
assert!((got - want).abs() < 2.0, "{what}: {got} vs {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_xyz_open_action_puts_its_point_at_the_window_top_left() {
|
||||
let mut h = harness("/OpenAction [5 0 R /XYZ 100 500 2]");
|
||||
assert_eq!(h.state().views[0].current, 2);
|
||||
assert_eq!((h.state().views[0].fit, h.state().views[0].zoom), (Fit::None, 2.0));
|
||||
// `left`: the page sits 100 user points further left than one opened at left 0.
|
||||
let (left, scale) = page_left(&h, 2);
|
||||
let (left0, _) = page_left(&harness("/OpenAction [5 0 R /XYZ 0 500 2]"), 2);
|
||||
near(left0 - left, 100.0 * scale, "the page moved left by `left`");
|
||||
let (page, top) = window_top(&mut h);
|
||||
assert_eq!(page, 2);
|
||||
near(top, 500.0, "y 500 is at the window's top edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fith_open_action_puts_its_top_at_the_window_top() {
|
||||
let mut h = harness("/OpenAction [4 0 R /FitH 400]");
|
||||
assert_eq!(h.state().views[0].current, 1);
|
||||
assert_eq!(h.state().views[0].fit, Fit::Width);
|
||||
let (page, top) = window_top(&mut h);
|
||||
assert_eq!(page, 1);
|
||||
near(top, 400.0, "y 400 is at the window's top edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_open_destination_opens_its_page() {
|
||||
for catalog in [
|
||||
// PDF 1.1: a name, through the catalog's /Dests.
|
||||
"/OpenAction << /S /GoTo /D /there >> /Dests << /there [7 0 R /XYZ 0 792 0] >>",
|
||||
// A string, through the /Names /Dests name tree.
|
||||
"/OpenAction << /S /GoTo /D (there) >> /Names << /Dests << /Names [(there) [7 0 R /XYZ 0 792 0]] >> >>",
|
||||
// The destination given as a name, without an action.
|
||||
"/OpenAction /there /Dests << /there [7 0 R /XYZ 0 792 0] >>",
|
||||
] {
|
||||
let mut h = harness(catalog);
|
||||
assert_eq!(h.state().views[0].current, 4, "{catalog}");
|
||||
// A zoom of 0 keeps the default zoom.
|
||||
assert_eq!(h.state().views[0].fit, Fit::Width, "{catalog}");
|
||||
let (page, top) = window_top(&mut h);
|
||||
assert_eq!(page, 4, "{catalog}");
|
||||
near(top, 792.0, "the page's top is at the window's top edge");
|
||||
}
|
||||
// A name nothing defines opens on the first page.
|
||||
let h = harness("/OpenAction << /S /GoTo /D /missing >> /Dests << /there [7 0 R /Fit] >>");
|
||||
assert_eq!(h.state().views[0].current, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_my_default_view_keeps_the_zoom_and_goes_to_the_page_top() {
|
||||
let bytes = fixture("/OpenAction [5 0 R /XYZ 100 500 2]");
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.always_default_view = true;
|
||||
app.open_bytes("open.pdf", None, bytes).expect("opens");
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
settle(&mut h);
|
||||
assert_eq!(h.state().views[0].current, 2);
|
||||
assert_eq!(h.state().views[0].fit, Fit::Width);
|
||||
let (page, top) = window_top(&mut h);
|
||||
assert_eq!(page, 2);
|
||||
near(top, 792.0, "the page's top");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_screen_document_shows_its_non_full_screen_panel_outside_full_screen() {
|
||||
for (mode, want) in [("UseThumbs", Some(RightPanel::Pages)), ("UseOC", Some(RightPanel::Layers)), ("UseNone", None)] {
|
||||
let mut h = harness(&format!("/PageMode /FullScreen /ViewerPreferences << /NonFullScreenPageMode /{mode} >>"));
|
||||
assert!(h.state().pending_full_screen.is_some(), "{mode}: full screen is asked for");
|
||||
assert_eq!(h.state().right, want, "{mode}: the panel behind the prompt");
|
||||
// Declining it leaves that panel.
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().resolve_full_screen_prompt(&ctx, false);
|
||||
h.run_steps(2);
|
||||
assert_eq!((h.state().full_screen, h.state().right), (false, want), "{mode}: declined");
|
||||
// Entering and leaving full screen comes back to it.
|
||||
h.state_mut().apply_full_screen(true);
|
||||
h.run_steps(2);
|
||||
h.state_mut().apply_full_screen(false);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().right, want, "{mode}: after full screen");
|
||||
}
|
||||
// Without /PageMode /FullScreen the entry means nothing.
|
||||
let h = harness("/ViewerPreferences << /NonFullScreenPageMode /UseThumbs >>");
|
||||
assert_eq!(h.state().right, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_screen_document_with_an_outline_shows_it_only_when_it_asks_to() {
|
||||
// UseNone (and its absence, the default) shows no outline outside full screen; UseOutlines does.
|
||||
for (prefs, want) in [
|
||||
("", None),
|
||||
("/ViewerPreferences << /NonFullScreenPageMode /UseNone >>", None),
|
||||
("/ViewerPreferences << /NonFullScreenPageMode /UseOutlines >>", Some(RightPanel::Bookmarks)),
|
||||
] {
|
||||
let h = harness(&format!("/Outlines 9 0 R /PageMode /FullScreen {prefs}"));
|
||||
assert_eq!(h.state().right, want, "{prefs}");
|
||||
}
|
||||
// Not in full screen, a document with an outline still opens on it.
|
||||
let h = harness("/Outlines 9 0 R");
|
||||
assert_eq!(h.state().right, Some(RightPanel::Bookmarks));
|
||||
}
|
||||
@@ -14,7 +14,10 @@ use base64::Engine;
|
||||
|
||||
use crate::XfaError;
|
||||
use crate::data::{DataNode, data_date_letters, data_path, data_to_iso, date_letters, is_on, iso_to_pattern};
|
||||
use crate::model::*;
|
||||
use crate::model::{
|
||||
Access, Area, Border, Common, Draw, ExclGroup, Field, Font, HAlign, Layout, Margin, Node, Occur, PageArea, PageRole, Para, Placement, Presence,
|
||||
Rect, Script, SomIndices, Stroke, Subform, Template, Ui, VAlign, Value,
|
||||
};
|
||||
use crate::text::{self, Block, Face, Span};
|
||||
|
||||
/// Most pages a form may lay out to.
|
||||
@@ -1325,6 +1328,10 @@ impl Layouter<'_> {
|
||||
if cap.value.is_empty() && cap.reserve.is_none() {
|
||||
return None;
|
||||
}
|
||||
// A check box has no text for an inline caption to run with: it is not shown.
|
||||
if f.ui == Ui::CheckButton && cap.placement == Placement::Inline {
|
||||
return None;
|
||||
}
|
||||
let placement = if cap.placement == Placement::Inline { Placement::Left } else { cap.placement };
|
||||
let font = ctx.font.apply(&cap.font);
|
||||
let para = ctx.para.apply(&cap.para);
|
||||
@@ -1365,13 +1372,18 @@ impl Layouter<'_> {
|
||||
};
|
||||
match self.caption_reserve(f, inner_w, ctx) {
|
||||
Some((Placement::Top | Placement::Bottom, r)) => ui + r,
|
||||
Some((_, r)) => {
|
||||
Some((placement, r)) => {
|
||||
// A check box's caption without a reserve is drawn in all the box leaves.
|
||||
let w = match auto_check_reserve(f, placement, inner_w, None) {
|
||||
Some(auto) => auto,
|
||||
None => inner_w - r,
|
||||
};
|
||||
let cap = f.caption.as_ref().map(|c| {
|
||||
let rich = match &c.value {
|
||||
Value::Rich(r) => r.clone(),
|
||||
other => text::plain(&other.plain().unwrap_or_default()),
|
||||
};
|
||||
text::measure_height(&rich, (inner_w - r).max(1.0), &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id, max| {
|
||||
text::measure_height(&rich, w.max(1.0), &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id, max| {
|
||||
self.embed(id, max)
|
||||
})
|
||||
});
|
||||
@@ -1838,6 +1850,7 @@ impl Layouter<'_> {
|
||||
let inner = rect.inset(&f.common.margin);
|
||||
let (mut ui, mut cap_rect) = (inner, None);
|
||||
if let Some((placement, reserve)) = self.caption_reserve(f, inner.w, ctx) {
|
||||
let reserve = auto_check_reserve(f, placement, inner.w, Some(inner.h)).unwrap_or(reserve);
|
||||
let r = reserve.max(0.0);
|
||||
match placement {
|
||||
Placement::Top => {
|
||||
@@ -1975,12 +1988,21 @@ impl Layouter<'_> {
|
||||
let (kind, rect, border, value, tooltip) = match f.ui {
|
||||
Ui::CheckButton => {
|
||||
let s = f.check_size.unwrap_or(10.0).min(ui.w.max(1.0)).min(ui.h.max(1.0));
|
||||
let y = match fctx.para.v_align {
|
||||
VAlign::Top => ui.y + f.ui_margin.top,
|
||||
VAlign::Middle => ui.y + (ui.h - s) / 2.0,
|
||||
VAlign::Bottom => ui.bottom() - s - f.ui_margin.bottom,
|
||||
// Without a caption the box sits at the right of the content area, as if a
|
||||
// caption on its left took the rest, so the paragraph's alignment has no room to
|
||||
// act on; beside a caption that alignment places it. The box's own margin doesn't
|
||||
// move it.
|
||||
let x = match (cap_rect, fctx.para.h_align) {
|
||||
(None, _) | (Some(_), HAlign::Right) => ui.right() - s,
|
||||
(Some(_), HAlign::Center) => ui.x + (ui.w - s) / 2.0,
|
||||
(Some(_), HAlign::Left | HAlign::Justify) => ui.x,
|
||||
};
|
||||
let r = Rect::new(ui.x + f.ui_margin.left, y, s, s);
|
||||
let y = match fctx.para.v_align {
|
||||
VAlign::Top => ui.y,
|
||||
VAlign::Middle => ui.y + (ui.h - s) / 2.0,
|
||||
VAlign::Bottom => ui.bottom() - s,
|
||||
};
|
||||
let r = Rect::new(x, y, s, s);
|
||||
let on = f.items.first().cloned().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "1".into());
|
||||
let (kind, tip, checked) = match radio {
|
||||
Some((group, on_value, tip, chosen)) => (
|
||||
@@ -2069,6 +2091,22 @@ impl Layouter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The room a caption without a reserve takes beside a check box: all the box leaves of a
|
||||
/// content area `w` wide (and `h` tall, when known), the box at the size it can be drawn there.
|
||||
/// `None` for any other field, or a caption with a reserve of its own.
|
||||
fn auto_check_reserve(f: &Field, placement: Placement, w: f64, h: Option<f64>) -> Option<f64> {
|
||||
if f.ui != Ui::CheckButton || f.caption.as_ref().is_none_or(|c| c.reserve.is_some()) {
|
||||
return None;
|
||||
}
|
||||
let s = f.check_size.unwrap_or(10.0).min(w.max(1.0)).min(h.map_or(f64::INFINITY, |h| h.max(1.0)));
|
||||
let rest = match (placement, h) {
|
||||
(Placement::Top | Placement::Bottom, Some(h)) => h - s,
|
||||
(Placement::Top | Placement::Bottom, None) => return None,
|
||||
_ => w - s,
|
||||
};
|
||||
Some(rest.max(0.0))
|
||||
}
|
||||
|
||||
/// The widget's own border from the `<ui>` border element. Without one, a check box gets a
|
||||
/// solid box, as Designer draws it, and any other field has no box of its own.
|
||||
fn widget_border(b: Option<&Border>, check: bool) -> WidgetBorder {
|
||||
|
||||
@@ -5,7 +5,11 @@ use base64::Engine;
|
||||
use roxmltree::Node as XmlNode;
|
||||
|
||||
use crate::XfaError;
|
||||
use crate::model::*;
|
||||
use crate::model::{
|
||||
Access, Anchor, Area, Border, Caption, ChoiceList, Color, Common, Corner, Draw, Edge, ExclGroup, Field, FontSpec, HAlign, Layout, Margin, Node,
|
||||
Occur, PageArea, PageRole, PageSet, ParaSpec, Paragraph, Placement, Presence, Rect, RichText, Run, Script, Stroke, Subform, Template, Ui, VAlign,
|
||||
Value,
|
||||
};
|
||||
|
||||
/// Deepest element nesting followed (templates are shallow; hostile ones are not).
|
||||
const MAX_DEPTH: usize = 64;
|
||||
@@ -424,7 +428,9 @@ fn parse_caption(n: Option<XmlNode>, warnings: &mut Vec<String>) -> Option<Capti
|
||||
Some("inline") => Placement::Inline,
|
||||
_ => Placement::Left,
|
||||
},
|
||||
reserve: attr_measure(n, "reserve").filter(|r| *r >= 0.0),
|
||||
// A reserve of zero or less sizes the caption to its content, as none does (XFA 3.3,
|
||||
// the caption's reserve).
|
||||
reserve: attr_measure(n, "reserve").filter(|r| *r > 0.0),
|
||||
presence: Presence::parse(n.attribute("presence")),
|
||||
value: parse_value(child(n, "value"), warnings),
|
||||
font: parse_font(child(n, "font")),
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
use pdfcraft_cos::{Dict, Document, Object, PdfString};
|
||||
|
||||
use crate::data::{DataNode, data_path, parse_datasets};
|
||||
use crate::model::*;
|
||||
use crate::model::{Access, Field, Node, Presence, Script, SomIndices, Template};
|
||||
use crate::{Report, XfaError};
|
||||
|
||||
/// Private key on the AcroForm: presence scripts set, by SOM path.
|
||||
|
||||
@@ -2757,6 +2757,258 @@ fn a_text_field_without_a_border_of_its_own_has_no_box() {
|
||||
assert_eq!(shapes, [BorderShape::None, BorderShape::Full, BorderShape::Full]);
|
||||
}
|
||||
|
||||
/// One measured check box: its name, width, box size, check box children, field children, and
|
||||
/// where its box was drawn (x and y in inches from the field's top left).
|
||||
type CheckCase<'a> = (&'a str, &'a str, Option<&'a str>, String, String, f64, f64);
|
||||
|
||||
/// A check box field for the placement tests: `extra` holds its margin, paragraph and caption,
|
||||
/// `ui` the check box's own children, and `size` its box size (none for the default 10pt).
|
||||
fn placed_check(name: &str, x: f64, y: f64, w: &str, size: Option<&str>, ui: &str, extra: &str) -> String {
|
||||
let size = size.map(|s| format!(r#" size="{s}""#)).unwrap_or_default();
|
||||
format!(
|
||||
r#"<field name="{name}" x="{x}in" y="{y}in" w="{w}" h="0.6in"><ui><checkButton{size}>{ui}</checkButton></ui><font typeface="Arial" size="9pt"/>{extra}<items><integer>1</integer><integer>0</integer></items></field>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Where a check box is drawn inside its field, measured in inches from the field's top left in
|
||||
/// another viewer on synthetic probes: with no caption the box sits at the right of the content
|
||||
/// area whatever the paragraph's alignment, beside a reserved caption the alignment places it,
|
||||
/// a caption without a reserve takes all the box leaves, and the box's own margin doesn't move it.
|
||||
#[test]
|
||||
fn a_check_box_sits_where_its_margins_caption_and_alignment_put_it() {
|
||||
let m = |a: &str| format!("<margin {a}/>");
|
||||
let p = |a: &str| format!("<para {a}/>");
|
||||
let cap = |a: &str, text: &str| format!(r#"<caption {a}><font typeface="Arial" size="9pt"/><value><text>{text}</text></value></caption>"#);
|
||||
// (name, width, box size, check box children, field children, box x and y in inches)
|
||||
let cases: Vec<CheckCase> = vec![
|
||||
("none", "1.2in", Some("0.25in"), String::new(), String::new(), 0.95, 0.0),
|
||||
("left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#), 0.95, 0.0),
|
||||
("right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#), 0.65, 0.0),
|
||||
("both_margins", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.1in" rightInset="0.4in""#), 0.55, 0.0),
|
||||
("h_left", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="left""#), 0.95, 0.0),
|
||||
("h_center", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="center""#), 0.95, 0.0),
|
||||
("h_right", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="right""#), 0.95, 0.0),
|
||||
("h_justify", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="justify""#), 0.95, 0.0),
|
||||
("center_right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#) + &p(r#"hAlign="center""#), 0.65, 0.0),
|
||||
("left_left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#) + &p(r#"hAlign="left""#), 0.95, 0.0),
|
||||
("v_top_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.15in""#) + &p(r#"vAlign="top""#), 0.95, 0.15),
|
||||
("v_middle_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.2in""#) + &p(r#"vAlign="middle""#), 0.95, 0.275),
|
||||
("v_bottom_margin", "1.2in", Some("0.25in"), String::new(), m(r#"bottomInset="0.15in""#) + &p(r#"vAlign="bottom""#), 0.95, 0.2),
|
||||
("v_bottom", "1.2in", Some("0.25in"), String::new(), p(r#"vAlign="bottom""#), 0.95, 0.35),
|
||||
("cap_left_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" reserve="0.5in""#, "Cap"), 0.5, 0.0),
|
||||
("cap_right_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right" reserve="0.5in""#, "Cap"), 0.0, 0.0),
|
||||
(
|
||||
"cap_left_reserve_center",
|
||||
"1.5in",
|
||||
Some("0.25in"),
|
||||
String::new(),
|
||||
cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#),
|
||||
0.875,
|
||||
0.0,
|
||||
),
|
||||
(
|
||||
"cap_left_reserve_right",
|
||||
"1.5in",
|
||||
Some("0.25in"),
|
||||
String::new(),
|
||||
cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="right""#),
|
||||
1.25,
|
||||
0.0,
|
||||
),
|
||||
(
|
||||
"cap_left_reserve_middle",
|
||||
"1.5in",
|
||||
Some("0.25in"),
|
||||
String::new(),
|
||||
cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"vAlign="middle""#),
|
||||
0.5,
|
||||
0.175,
|
||||
),
|
||||
(
|
||||
"cap_right_reserve_center",
|
||||
"1.5in",
|
||||
Some("0.25in"),
|
||||
String::new(),
|
||||
cap(r#"placement="right" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#),
|
||||
0.375,
|
||||
0.0,
|
||||
),
|
||||
("cap_top_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top" reserve="0.25in""#, "Cap"), 0.0, 0.25),
|
||||
("cap_bottom_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom" reserve="0.25in""#, "Cap"), 0.0, 0.0),
|
||||
(
|
||||
"cap_hidden_reserve",
|
||||
"1.5in",
|
||||
Some("0.25in"),
|
||||
String::new(),
|
||||
cap(r#"placement="left" reserve="0.5in" presence="hidden""#, "Cap"),
|
||||
1.25,
|
||||
0.0,
|
||||
),
|
||||
("cap_empty_reserve", "1.5in", Some("0.25in"), String::new(), r#"<caption placement="left" reserve="0.5in"/>"#.to_string(), 0.5, 0.0),
|
||||
("cap_left_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap"), 1.25, 0.0),
|
||||
("cap_left_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap") + &p(r#"hAlign="center""#), 1.25, 0.0),
|
||||
("cap_right_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap"), 0.0, 0.0),
|
||||
("cap_right_auto_middle", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap") + &p(r#"vAlign="middle""#), 0.0, 0.175),
|
||||
("cap_top_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap"), 0.0, 0.35),
|
||||
("cap_top_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap") + &p(r#"hAlign="center""#), 0.625, 0.35),
|
||||
("cap_bottom_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom""#, "Cap"), 0.0, 0.0),
|
||||
("cap_inline", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="inline""#, "Cap"), 1.25, 0.0),
|
||||
("cap_hidden_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" presence="hidden""#, "Cap"), 1.25, 0.0),
|
||||
("box_margin_left", "1.5in", Some("0.25in"), m(r#"leftInset="0.1in""#), String::new(), 1.25, 0.0),
|
||||
(
|
||||
"box_margin_all",
|
||||
"1.5in",
|
||||
Some("0.25in"),
|
||||
m(r#"leftInset="0.1in" rightInset="0.1in" topInset="0.1in" bottomInset="0.1in""#),
|
||||
String::new(),
|
||||
1.25,
|
||||
0.0,
|
||||
),
|
||||
("default_size", "1.2in", None, String::new(), String::new(), 1.2 - 10.0 / 72.0, 0.0),
|
||||
("default_size_center", "1.2in", None, String::new(), p(r#"hAlign="center""#), 1.2 - 10.0 / 72.0, 0.0),
|
||||
];
|
||||
let fields: String = cases
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, w, size, ui, extra, _, _))| placed_check(name, (i % 4) as f64 * 1.8, (i / 4) as f64 * 0.8, w, *size, ui, extra))
|
||||
.collect();
|
||||
// The form in the measured case the probes started from (DD Form 2946's checklist boxes).
|
||||
let cell = r#"<field name="cell" x="0in" y="8in" w="12.7mm" h="0.6in"><ui><checkButton size="4.9389mm"><border><edge/><fill/></border></checkButton></ui><margin leftInset="0mm" rightInset="3.556mm"/><para vAlign="middle"/><items><integer>1</integer><integer>0</integer></items></field>"#;
|
||||
let body = format!(r#"<subform name="body" layout="position" w="7.5in" h="9in">{fields}{cell}</subform>"#);
|
||||
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
|
||||
let laid = widgets(&form.pages[0]);
|
||||
let at = |name: &str| laid.iter().find(|w| w.name == name).map(|w| w.rect).unwrap_or_else(|| panic!("no widget {name}"));
|
||||
// The content area starts half an inch in.
|
||||
for (i, (name, _, size, _, _, x, y)) in cases.iter().enumerate() {
|
||||
let r = at(name);
|
||||
let (fx, fy) = (36.0 + (i % 4) as f64 * 1.8 * 72.0, 36.0 + (i / 4) as f64 * 0.8 * 72.0);
|
||||
let s = if size.is_some() { 18.0 } else { 10.0 };
|
||||
assert!((r.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (r.x - fx) / 72.0);
|
||||
assert!((r.y - fy - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (r.y - fy) / 72.0);
|
||||
assert!((r.w - s).abs() < 0.01 && (r.h - s).abs() < 0.01, "{name}: box size {}x{}", r.w, r.h);
|
||||
}
|
||||
// Its box sits 4.2mm in, against its 3.556mm right margin, and in the middle of its height.
|
||||
let r = at("cell");
|
||||
let mm = 72.0 / 25.4;
|
||||
assert!((r.x - 36.0 - (12.7 - 3.556 - 4.9389) * mm).abs() < 0.01, "cell box x {}", r.x - 36.0);
|
||||
assert!((r.y - 36.0 - 8.0 * 72.0 - (0.6 * 72.0 - 4.9389 * mm) / 2.0).abs() < 0.01, "cell box y {}", r.y - 36.0 - 8.0 * 72.0);
|
||||
}
|
||||
|
||||
/// Radio buttons in an exclusion group sit as check boxes do: at the right without a caption,
|
||||
/// moved in by a right margin, and placed by the alignment or the caption beside a caption.
|
||||
#[test]
|
||||
fn a_radio_button_sits_where_a_check_box_would() {
|
||||
let radio = |name: &str, x: f64, extra: &str| {
|
||||
format!(
|
||||
r#"<field name="{name}" x="{x}in" y="0in" w="1.5in" h="0.6in"><ui><checkButton size="0.25in" shape="round"/></ui><font typeface="Arial" size="9pt"/>{extra}<items><text>{name}</text></items></field>"#
|
||||
)
|
||||
};
|
||||
let cap = |a: &str| format!(r#"<caption {a}><font typeface="Arial" size="9pt"/><value><text>Cap</text></value></caption>"#);
|
||||
// (name, field children, box x and y in inches from the field's top left)
|
||||
let cases = [
|
||||
("plain", String::new(), 1.25, 0.0),
|
||||
("right_margin", r#"<margin rightInset="0.3in"/>"#.to_string(), 0.95, 0.0),
|
||||
("centered", r#"<para hAlign="center"/>"#.to_string(), 1.25, 0.0),
|
||||
("cap_right_center", cap(r#"placement="right" reserve="0.5in""#) + r#"<para hAlign="center"/>"#, 0.375, 0.0),
|
||||
("cap_left_auto", cap(r#"placement="left""#), 1.25, 0.0),
|
||||
("cap_top_auto", cap(r#"placement="top""#), 0.0, 0.35),
|
||||
];
|
||||
let fields: String = cases.iter().enumerate().map(|(i, (name, extra, _, _))| radio(name, i as f64 * 1.6, extra)).collect();
|
||||
let body = format!(
|
||||
r#"<subform name="body" layout="position" w="7.5in" h="9in"><exclGroup name="group" x="0in" y="0in" w="9.6in" h="0.6in" layout="position">{fields}</exclGroup></subform>"#
|
||||
);
|
||||
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
|
||||
let laid = widgets(&form.pages[0]);
|
||||
for (i, (name, _, x, y)) in cases.iter().enumerate() {
|
||||
let w = laid.iter().find(|w| w.name == *name).unwrap_or_else(|| panic!("no radio button {name}"));
|
||||
assert!(matches!(w.kind, WidgetKind::Radio { .. }), "{name} is a radio button");
|
||||
let fx = 36.0 + i as f64 * 1.6 * 72.0;
|
||||
assert!((w.rect.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (w.rect.x - fx) / 72.0);
|
||||
assert!((w.rect.y - 36.0 - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (w.rect.y - 36.0) / 72.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A caption without a reserve leaves room for the box at the size it is drawn, a box larger than
|
||||
/// its field shrinking to fit; and a field without a height is as tall as that caption drawn in
|
||||
/// all the box leaves, not at some narrower width.
|
||||
#[test]
|
||||
fn a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn() {
|
||||
let cap =
|
||||
r#"<caption placement="left"><font typeface="Arial" size="9pt"/><value><text>Caption text running on one line</text></value></caption>"#;
|
||||
let tall = r#"<field name="tall" x="0in" y="0in" w="1.5in" h="0.25in"><ui><checkButton size="0.75in"/></ui><font typeface="Arial" size="9pt"/>"#
|
||||
.to_string()
|
||||
+ cap
|
||||
+ "<items><integer>1</integer><integer>0</integer></items></field>";
|
||||
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="position" w="7.5in" h="1in">{tall}</subform>"#)))
|
||||
.unwrap();
|
||||
let r = widgets(&form.pages[0]).iter().find(|w| w.name == "tall").map(|w| w.rect).unwrap();
|
||||
assert!((r.w - 18.0).abs() < 0.01, "the box shrinks to the field's height: {}", r.w);
|
||||
assert!((r.x - 36.0 - 1.25 * 72.0).abs() < 0.01, "and still sits at the right: {} in", (r.x - 36.0) / 72.0);
|
||||
|
||||
let grows = r#"<field name="grows" w="3in"><ui><checkButton size="0.25in"/></ui><font typeface="Arial" size="9pt"/>"#.to_string()
|
||||
+ cap
|
||||
+ r#"<items><integer>1</integer><integer>0</integer></items></field><field name="next" w="3in" h="0.3in"><ui><textEdit/></ui></field>"#;
|
||||
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="tb" w="7.5in">{grows}</subform>"#))).unwrap();
|
||||
let next = widgets(&form.pages[0]).iter().find(|w| w.name == "next").map(|w| w.rect).unwrap();
|
||||
assert!((next.y - 36.0 - 18.0).abs() < 0.01, "a one-line caption beside the box keeps the field the box's height: {}", next.y - 36.0);
|
||||
}
|
||||
|
||||
/// A caption without a reserve beside a check box takes all the room the box leaves, and starts
|
||||
/// right after it; an inline caption has no text to run with and is not drawn.
|
||||
#[test]
|
||||
fn a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field() {
|
||||
let cap = |place: &str, text: &str| {
|
||||
format!(r#"<caption placement="{place}"><font typeface="Arial" size="9pt"/><value><text>{text}</text></value></caption>"#)
|
||||
};
|
||||
let body = format!(
|
||||
r#"<subform name="body" layout="position" w="7.5in" h="9in">{}{}{}{}</subform>"#,
|
||||
placed_check("after", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap("right", "Right")),
|
||||
placed_check("before", 2.0, 0.0, "1.5in", Some("0.25in"), "", &cap("left", "Left")),
|
||||
placed_check("below", 4.0, 0.0, "1.5in", Some("0.25in"), "", &cap("bottom", "Below")),
|
||||
placed_check("inline", 0.0, 1.0, "1.5in", Some("0.25in"), "", &cap("inline", "Inline")),
|
||||
);
|
||||
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
|
||||
let span = |t: &str| {
|
||||
form.pages[0].items.iter().find_map(|i| match i {
|
||||
Item::Text(s) if s.text == t => Some(s.clone()),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let right = span("Right").expect("the right caption is drawn");
|
||||
assert!((right.x - 36.0 - 18.0).abs() < 0.01, "a right caption starts after the box: {}", right.x - 36.0);
|
||||
let left = span("Left").expect("the left caption is drawn");
|
||||
assert!((left.x - 36.0 - 2.0 * 72.0).abs() < 0.01, "a left caption starts at the field's left: {}", left.x - 36.0);
|
||||
let below = span("Below").expect("the bottom caption is drawn");
|
||||
assert!(below.baseline - 36.0 > 18.0, "a bottom caption is below the box: {}", below.baseline - 36.0);
|
||||
assert!(span("Inline").is_none(), "an inline caption beside a check box is not drawn");
|
||||
}
|
||||
|
||||
/// A caption reserve of zero sizes the caption to its content, as no reserve does: beside a check
|
||||
/// box it takes the rest of the field, and before a text field it is as wide as its text.
|
||||
#[test]
|
||||
fn a_zero_caption_reserve_sizes_the_caption_as_none_does() {
|
||||
let cap = |reserve: &str| {
|
||||
format!(r#"<caption placement="right"{reserve}><font typeface="Arial" size="9pt"/><value><text>Right</text></value></caption>"#)
|
||||
};
|
||||
let text = |name: &str, y: &str, reserve: &str| {
|
||||
format!(
|
||||
r#"<field name="{name}" x="0in" y="{y}" w="3in" h="0.3in"><ui><textEdit/></ui><font typeface="Arial" size="9pt"/><caption placement="left"{reserve}><font typeface="Arial" size="9pt"/><value><text>Name</text></value></caption></field>"#
|
||||
)
|
||||
};
|
||||
let body = format!(
|
||||
r#"<subform name="body" layout="position" w="7.5in" h="9in">{}{}{}</subform>"#,
|
||||
placed_check("zero", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap(r#" reserve="0""#)),
|
||||
text("withZero", "1in", r#" reserve="0in""#),
|
||||
text("without", "2in", ""),
|
||||
);
|
||||
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
|
||||
let right = form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { (s.text == "Right").then_some(s.x) } else { None });
|
||||
assert!(right.is_some_and(|x| (x - 36.0 - 18.0).abs() < 0.01), "the caption starts after the box: {right:?}");
|
||||
let x_of = |name: &str| widgets(&form.pages[0]).iter().find(|w| w.name == name).map(|w| w.rect.x).unwrap();
|
||||
assert!(x_of("withZero") > 36.0 + 1.0, "the caption takes its text's width: {}", x_of("withZero"));
|
||||
assert!((x_of("withZero") - x_of("without")).abs() < 0.01, "as without a reserve: {} {}", x_of("withZero"), x_of("without"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signed_signature_box_shows_the_signature_the_file_holds() {
|
||||
let mut doc = Document::open(Arc::new(crate::fixtures::signed_shell())).unwrap();
|
||||
|
||||
@@ -271,8 +271,10 @@ fn text_of(doc: &Document, d: &Dict, k: &[u8]) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The numbers of a list; empty when any entry is non-finite (`nan`, `inf`), so the list is unusable as a whole.
|
||||
fn csv(list: &str) -> Vec<f64> {
|
||||
list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect()
|
||||
let v: Vec<f64> = list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect();
|
||||
if v.iter().all(|x| x.is_finite()) { v } else { Vec::new() }
|
||||
}
|
||||
|
||||
fn arr(v: &[f64]) -> Object {
|
||||
|
||||
@@ -1874,3 +1874,62 @@ fn a_comment_locked_by_an_indirect_flag_is_not_replaced_by_an_import() {
|
||||
assert!(annots.contains(&Object::Ref(note)), "the locked comment was replaced");
|
||||
assert_eq!(doc.get(note), before, "the locked comment was changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_skips_annotations_with_non_finite_coordinates() {
|
||||
for rect in ["nan,10,100,100", "0,inf,100,100", "0,10,infinity,100", "0,10,100,-inf"] {
|
||||
let mut doc = blank();
|
||||
let xfdf = format!(
|
||||
r#"<xfdf xmlns="http://ns.adobe.com/xfdf/"><annots><square page="0" rect="0,0,50,50" name="good"/><square page="0" rect="{rect}" name="bad"/></annots></xfdf>"#
|
||||
);
|
||||
let r = import(&mut doc, xfdf.as_bytes()).unwrap();
|
||||
assert_eq!(r.comments, 1, "rect {rect}: {r:?}");
|
||||
let names = annots_of(&doc);
|
||||
assert_eq!(names.len(), 1, "rect {rect}: {names:?}");
|
||||
assert_eq!(names[0].get(b"NM"), Some(&PdfString::literal(b"good".to_vec()).into()), "rect {rect}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_drops_non_finite_numbers_from_every_coordinate_list() {
|
||||
let xfdf = r#"<xfdf xmlns="http://ns.adobe.com/xfdf/"><annots>
|
||||
<line page="0" rect="0,0,50,50" name="line" start="nan,0" end="10,10"/>
|
||||
<polygon page="0" rect="0,0,50,50" name="poly"><vertices>1,2;inf,4;5,6</vertices></polygon>
|
||||
<ink page="0" rect="0,0,50,50" name="ink"><inklist><gesture>1,2;3,-inf</gesture></inklist></ink>
|
||||
<freetext page="0" rect="0,0,50,50" name="callout" callout="1,2,nan,4,5,6"/>
|
||||
<highlight page="0" rect="0,0,50,50" name="hl" coords="0,0,infinity,0,0,10,10,10"/>
|
||||
</annots></xfdf>"#;
|
||||
let mut doc = blank();
|
||||
let r = import(&mut doc, xfdf.as_bytes()).unwrap();
|
||||
assert_eq!(r.comments, 5, "{r:?}");
|
||||
fn finite(doc: &Document, o: &Object) -> bool {
|
||||
match &*doc.resolve(o) {
|
||||
Object::Real(x) => x.is_finite(),
|
||||
Object::Array(a) => a.iter().all(|e| finite(doc, e)),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
let annots = annots_of(&doc);
|
||||
assert_eq!(annots.len(), 5);
|
||||
for d in &annots {
|
||||
for (k, v) in d.iter() {
|
||||
if k.as_slice() != b"P" {
|
||||
assert!(finite(&doc, v), "{d:?}");
|
||||
}
|
||||
}
|
||||
assert!(d.get(b"L").is_none() && d.get(b"CL").is_none() && d.get(b"Vertices").is_none(), "{d:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn annots_of(doc: &Document) -> Vec<Dict> {
|
||||
let page = &pdfcraft_model::pages(doc)[0];
|
||||
page.dict
|
||||
.get(b"Annots")
|
||||
.map(|a| doc.resolve(a))
|
||||
.and_then(|a| a.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|a| doc.resolve(a).as_dict().cloned().unwrap())
|
||||
.filter(|d| d.get(b"Subtype") != Some(&Object::name("Widget")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
+4
-2
@@ -90,8 +90,10 @@ config works across the suite) keep the agent to the folders you give it:
|
||||
nearest existing folder's links are followed and the rest must be plain names, so `..` below a
|
||||
folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would
|
||||
create its target). The result is compared with the root by whole folder names: `/work2/x` is not
|
||||
inside `/work`. On Windows case is ignored, UNC paths are resolved like drive-letter ones, and
|
||||
device names (`CON`, `NUL`, `COM1`...) are refused.
|
||||
inside `/work`. On Windows case is ignored, device names (`CON`, `NUL`, `COM1`...) are refused,
|
||||
and a path on another network share or in a device namespace than the root's (`\\host\share`,
|
||||
`\\?\UNC\...`, `\\.\...`) is refused by name, before it is resolved, so the host is never
|
||||
contacted. A root on a share accepts the paths on that share.
|
||||
- A refused path is an ordinary tool error the agent can read and correct, for example
|
||||
`automation path rejected: outside the write root /work/project/out: /etc/x.pdf` or
|
||||
`automation filesystem access is not granted: write authority is absent: /work/project/out/x.pdf`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# PDF specification and standards parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (§12.4.4: page transitions and display times read) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (§14.3: custom properties edited in Document Properties) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
|
||||
How much of ISO 32000-2 (PDF 2.0) and the PDF subset standards PdfCraft implements, set against
|
||||
what Acrobat Pro implements. This is PdfCraft's equivalent of a "geometry" or "codec" checklist:
|
||||
@@ -44,7 +44,7 @@ are borrowed; PDF 2.0 additions and most subset standards are missing. **150–2
|
||||
| §12.9 | Measurement and geospatial | full | 2D measuring with viewports and calibration; no geospatial | `comment.geospatial` planned |
|
||||
| §12.10 | Document requirements | yes | none | |
|
||||
| §13 | Multimedia: sound, movies, screen, rich media, 3D (U3D, PRC) | yes | preserved untouched; not played or shown | `misc.rich-media-*`, `misc.3d-view` planned (P3) |
|
||||
| §14.3 | Metadata: info dictionary, XMP | full, XMP editor | info dictionary edited, with its XMP counterparts (title, author, subject, keywords, creator tool, producer) kept in step; XMP written for PDF/A; no XMP editor or custom properties | `organize.xmp-editor` planned |
|
||||
| §14.3 | Metadata: info dictionary, XMP | full, XMP editor | info dictionary edited, with its XMP counterparts (title, author, subject, keywords, creator tool, producer) kept in step; XMP written for PDF/A; custom properties listed, added, changed and deleted (Document Properties ▸ Custom, `doc_info`, `doc_set_info`); no XMP editor | `organize.custom-properties` partial, `organize.xmp-editor` planned |
|
||||
| §14.6–14.8 | Marked content, logical structure, tagged PDF | full, with editing tools | read (checker, bookmarks from structure, redaction of tags); no tag editing or autotag | gap 11 |
|
||||
| §14.9 | Accessibility support: alt text, ActualText, language | full | alt text figure by figure, language, title | `a11y.alt-text-workflow` |
|
||||
| §14.10 | Web capture | yes | none | |
|
||||
|
||||
@@ -121,7 +121,7 @@ fi
|
||||
|
||||
# ---- .deb / .rpm --------------------------------------------------------------------------------
|
||||
if has deb || has rpm; then
|
||||
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
|
||||
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/docs/install/)" >&2; exit 1; }
|
||||
export VERSION
|
||||
export RELEASE="1${PDFCRAFT_BUILD_LABEL:+.$PDFCRAFT_BUILD_LABEL}"
|
||||
export NFPM_ARCH="$DEB_ARCH"
|
||||
|
||||
File diff suppressed because one or more lines are too long
Vendored
+2
-1
File diff suppressed because one or more lines are too long
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
authors = ["Laurenz Stampfl <laurenz.stampfl@gmail.com>"]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "A lightweight PostScript scanner."
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://github.com/LaurenzV/hayro"
|
||||
resolver = "2"
|
||||
|
||||
[lib]
|
||||
name = "hayro_postscript"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[example]]
|
||||
name = "tokenize"
|
||||
path = "examples/tokenize.rs"
|
||||
|
||||
[lints.clippy]
|
||||
collection_is_never_read = "warn"
|
||||
dbg_macro = "warn"
|
||||
debug_assert_with_mut_call = "warn"
|
||||
default_trait_access = "warn"
|
||||
doc_markdown = "warn"
|
||||
fn_to_numeric_cast_any = "warn"
|
||||
infinite_loop = "warn"
|
||||
large_stack_arrays = "warn"
|
||||
mismatching_type_param_order = "warn"
|
||||
negative_feature_names = "warn"
|
||||
redundant_feature_names = "warn"
|
||||
same_functions_in_if_condition = "warn"
|
||||
semicolon_if_nothing_returned = "warn"
|
||||
todo = "warn"
|
||||
too_many_arguments = "allow"
|
||||
unseparated_literal_suffix = "warn"
|
||||
use_self = "warn"
|
||||
wildcard_dependencies = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
keyword_idents_2024 = "forbid"
|
||||
missing_docs = "warn"
|
||||
non_ascii_idents = "forbid"
|
||||
non_local_definitions = "forbid"
|
||||
trivial_numeric_casts = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
unsafe_op_in_unsafe_fn = "forbid"
|
||||
unused_import_braces = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_macro_rules = "warn"
|
||||
unused_qualifications = "warn"
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
description = "A lightweight PostScript scanner."
|
||||
authors = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
license = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
Copyright (c) The Hayro Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
# hayro-postscript
|
||||
|
||||
[](https://crates.io/crates/hayro-postscript)
|
||||
[](https://docs.rs/hayro-postscript)
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
A lightweight PostScript scanner.
|
||||
|
||||
This crate provides a scanner for tokenizing PostScript programs into typed objects.
|
||||
It currently only implements a very small subset of the PostScript language,
|
||||
with the main goal of being enough to parse CMAP files, but the scope _might_
|
||||
be expanded upon in the future.
|
||||
|
||||
The supported types include integers and real numbers, name objects, strings and arrays.
|
||||
Unsupported is anything else, including dictionaries, procedures, etc. An error
|
||||
will be returned in case any of these is encountered.
|
||||
|
||||
### Safety
|
||||
This crate forbids unsafe code via a crate-level attribute.
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
//! A small example that shows how to tokenize a PostScript program.
|
||||
|
||||
#![allow(missing_docs)]
|
||||
|
||||
use hayro_postscript::{Number, Object, Scanner};
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::process;
|
||||
|
||||
fn main() {
|
||||
let path = match env::args().nth(1) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
eprintln!("Usage: tokenize <file>");
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let data = match fs::read(&path) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("Error reading {path}: {e}");
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut scanner = Scanner::new(&data);
|
||||
|
||||
while !scanner.at_end() {
|
||||
match scanner.parse_object() {
|
||||
Ok(object) => {
|
||||
print_object(&object);
|
||||
println!();
|
||||
}
|
||||
Err(e) => eprintln!("Error: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_object(object: &Object<'_>) {
|
||||
match object {
|
||||
Object::Number(Number::Integer(n)) => print!("Integer({n})"),
|
||||
Object::Number(Number::Real(n)) => print!("Real({n})"),
|
||||
Object::Name(name) => {
|
||||
let kind = if name.is_literal() {
|
||||
"literal"
|
||||
} else {
|
||||
"executable"
|
||||
};
|
||||
let text = name.as_str().unwrap_or("<non-ascii name>");
|
||||
print!("Name({text}, {kind})");
|
||||
}
|
||||
Object::String(s) => {
|
||||
let decoded = s.decode().unwrap_or_else(|_| Vec::new());
|
||||
print!("String({})", String::from_utf8_lossy(&decoded));
|
||||
}
|
||||
Object::Array(arr) => {
|
||||
print!("[");
|
||||
let mut inner = arr.objects();
|
||||
let mut first = true;
|
||||
while !inner.at_end() {
|
||||
if !first {
|
||||
print!(" ");
|
||||
}
|
||||
first = false;
|
||||
match inner.parse_object() {
|
||||
Ok(obj) => print_object(&obj),
|
||||
Err(e) => print!("Error({e})"),
|
||||
}
|
||||
}
|
||||
print!("]");
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+127
@@ -0,0 +1,127 @@
|
||||
use crate::error::{Error, Result};
|
||||
use crate::object;
|
||||
use crate::reader::Reader;
|
||||
use crate::string;
|
||||
|
||||
/// A PostScript array object.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Array<'a> {
|
||||
data: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Array<'a> {
|
||||
pub(crate) fn new(data: &'a [u8]) -> Self {
|
||||
Self { data }
|
||||
}
|
||||
|
||||
/// Return a [`Scanner`](crate::Scanner) that iterates over the objects inside
|
||||
/// this array.
|
||||
pub fn objects(&self) -> crate::Scanner<'a> {
|
||||
crate::Scanner::new(self.data)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse<'a>(r: &mut Reader<'a>) -> Result<&'a [u8]> {
|
||||
r.forward_tag(b"[").ok_or(Error::SyntaxError)?;
|
||||
|
||||
let start = r.offset();
|
||||
skip_array(r)?;
|
||||
let end = r.offset() - 1;
|
||||
|
||||
r.range(start..end).ok_or(Error::SyntaxError)
|
||||
}
|
||||
|
||||
fn skip_array(r: &mut Reader<'_>) -> Result<()> {
|
||||
let mut depth = 1_u32;
|
||||
|
||||
while depth > 0 {
|
||||
match r.peek_byte().ok_or(Error::SyntaxError)? {
|
||||
b'[' => {
|
||||
r.forward();
|
||||
depth += 1;
|
||||
}
|
||||
b']' => {
|
||||
r.forward();
|
||||
depth -= 1;
|
||||
}
|
||||
b'(' => {
|
||||
let _ = string::parse_literal(r).ok_or(Error::SyntaxError)?;
|
||||
}
|
||||
b'<' => {
|
||||
if r.peek_bytes(2) == Some(b"<~") {
|
||||
let _ = string::parse_ascii85(r).ok_or(Error::SyntaxError)?;
|
||||
} else if r.peek_bytes(2) == Some(b"<<") {
|
||||
r.forward();
|
||||
r.forward();
|
||||
} else {
|
||||
let _ = string::parse_hex(r).ok_or(Error::SyntaxError)?;
|
||||
}
|
||||
}
|
||||
b'%' => object::skip_whitespace_and_comments(r),
|
||||
_ => {
|
||||
r.forward();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_array(input: &[u8]) -> Result<&[u8]> {
|
||||
let mut r = Reader::new(input);
|
||||
parse(&mut r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty() {
|
||||
assert_eq!(parse_array(b"[]").unwrap(), b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simple() {
|
||||
assert_eq!(parse_array(b"[1 2 3]").unwrap(), b"1 2 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested() {
|
||||
assert_eq!(parse_array(b"[1 [2 3] 4]").unwrap(), b"1 [2 3] 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_string() {
|
||||
// The ']' inside the string should not close the array.
|
||||
assert_eq!(parse_array(b"[1 (str]) 2]").unwrap(), b"1 (str]) 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_hex_string() {
|
||||
assert_eq!(parse_array(b"[<48> /name]").unwrap(), b"<48> /name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_ascii85_string() {
|
||||
assert_eq!(parse_array(b"[<~87cURDZ~> 1]").unwrap(), b"<~87cURDZ~> 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_comment() {
|
||||
assert_eq!(
|
||||
parse_array(b"[1 % comment with ]\n2]").unwrap(),
|
||||
b"1 % comment with ]\n2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unterminated() {
|
||||
assert_eq!(parse_array(b"[1 2"), Err(Error::SyntaxError));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_an_array() {
|
||||
assert_eq!(parse_array(b"1 2]"), Err(Error::SyntaxError));
|
||||
}
|
||||
}
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
//! Error types for the PostScript scanner.
|
||||
|
||||
use core::fmt;
|
||||
|
||||
/// A specialized [`Result`] type for PostScript scanner operations.
|
||||
pub type Result<T> = core::result::Result<T, Error>;
|
||||
|
||||
/// An error encountered while scanning a PostScript token stream.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// A syntax error in the input.
|
||||
SyntaxError,
|
||||
/// A numeric value exceeded implementation limits.
|
||||
LimitCheck,
|
||||
/// An unsupported PostScript type was encountered (like dictionaries or
|
||||
/// procedures, which will be added in the future).
|
||||
UnsupportedType,
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::SyntaxError => f.write_str("syntaxerror"),
|
||||
Self::LimitCheck => f.write_str("limitcheck"),
|
||||
Self::UnsupportedType => f.write_str("unsupported type"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::error::Error for Error {}
|
||||
Vendored
+179
@@ -0,0 +1,179 @@
|
||||
/*!
|
||||
A lightweight PostScript scanner.
|
||||
|
||||
This crate provides a scanner for tokenizing PostScript programs into typed objects.
|
||||
It currently only implements a very small subset of the PostScript language,
|
||||
with the main goal of being enough to parse CMAP files, but the scope _might_
|
||||
be expanded upon in the future.
|
||||
|
||||
The supported types include integers and real numbers, name objects, strings and arrays.
|
||||
Unsupported is anything else, including dictionaries, procedures, etc. An error
|
||||
will be returned in case any of these is encountered.
|
||||
|
||||
## Safety
|
||||
This crate forbids unsafe code via a crate-level attribute.
|
||||
*/
|
||||
|
||||
#![no_std]
|
||||
#![forbid(unsafe_code)]
|
||||
#![allow(missing_docs)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
mod array;
|
||||
mod error;
|
||||
mod name;
|
||||
mod number;
|
||||
mod object;
|
||||
mod reader;
|
||||
mod string;
|
||||
|
||||
pub use array::Array;
|
||||
pub use error::{Error, Result};
|
||||
pub use name::Name;
|
||||
pub use number::Number;
|
||||
pub use object::Object;
|
||||
pub use string::String;
|
||||
|
||||
use reader::Reader;
|
||||
|
||||
/// A PostScript scanner that parses [`Object`]s from a byte stream.
|
||||
pub struct Scanner<'a> {
|
||||
reader: Reader<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Scanner<'a> {
|
||||
/// Create a new scanner over the given bytes of a PostScript program.
|
||||
pub fn new(data: &'a [u8]) -> Self {
|
||||
Self {
|
||||
reader: Reader::new(data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if there are no more objects to parse.
|
||||
pub fn at_end(&mut self) -> bool {
|
||||
object::at_end(&mut self.reader)
|
||||
}
|
||||
|
||||
/// Parse the next object.
|
||||
pub fn parse_object(&mut self) -> Result<Object<'a>> {
|
||||
object::read(&mut self.reader)
|
||||
}
|
||||
|
||||
/// Parse the next object as a [`Number`].
|
||||
pub fn parse_number(&mut self) -> Result<Number> {
|
||||
match self.parse_object()? {
|
||||
Object::Number(n) => Ok(n),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the next object as a [`Name`].
|
||||
pub fn parse_name(&mut self) -> Result<Name<'a>> {
|
||||
match self.parse_object()? {
|
||||
Object::Name(n) => Ok(n),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the next object as a [`String`].
|
||||
pub fn parse_string(&mut self) -> Result<String<'a>> {
|
||||
match self.parse_object()? {
|
||||
Object::String(s) => Ok(s),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the next object as an [`Array`].
|
||||
pub fn parse_array(&mut self) -> Result<Array<'a>> {
|
||||
match self.parse_object()? {
|
||||
Object::Array(a) => Ok(a),
|
||||
_ => Err(Error::SyntaxError),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cmap_snippet() {
|
||||
let input = br#"/CIDInit /ProcSet findresource begin
|
||||
12 dict begin
|
||||
begincmap
|
||||
/CMapName /Test-H def
|
||||
1 begincodespacerange
|
||||
<00> <FF>
|
||||
endcodespacerange
|
||||
2 beginbfchar
|
||||
<03> <0041>
|
||||
<04> <0042>
|
||||
endbfchar
|
||||
endcmap"#;
|
||||
|
||||
let mut s = Scanner::new(input);
|
||||
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"CIDInit", true));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"ProcSet", true));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"findresource", false));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false));
|
||||
assert_eq!(s.parse_number().unwrap(), Number::Integer(12));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"dict", false));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"begincmap", false));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"CMapName", true));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"Test-H", true));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"def", false));
|
||||
assert_eq!(s.parse_number().unwrap(), Number::Integer(1));
|
||||
assert_eq!(
|
||||
s.parse_name().unwrap(),
|
||||
Name::new(b"begincodespacerange", false)
|
||||
);
|
||||
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"00"));
|
||||
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"FF"));
|
||||
assert_eq!(
|
||||
s.parse_name().unwrap(),
|
||||
Name::new(b"endcodespacerange", false)
|
||||
);
|
||||
assert_eq!(s.parse_number().unwrap(), Number::Integer(2));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"beginbfchar", false));
|
||||
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"03"));
|
||||
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0041"));
|
||||
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"04"));
|
||||
assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0042"));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"endbfchar", false));
|
||||
assert_eq!(s.parse_name().unwrap(), Name::new(b"endcmap", false));
|
||||
assert!(s.at_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_round_trip() {
|
||||
let input = b"[123 /abc (xyz)]";
|
||||
let mut scanner = Scanner::new(input);
|
||||
let arr = scanner.parse_array().unwrap();
|
||||
assert!(scanner.at_end());
|
||||
|
||||
let mut inner = arr.objects();
|
||||
assert_eq!(inner.parse_number().unwrap(), Number::Integer(123));
|
||||
assert_eq!(inner.parse_name().unwrap(), Name::new(b"abc", true));
|
||||
assert_eq!(inner.parse_string().unwrap(), String::from_literal(b"xyz"));
|
||||
assert!(inner.at_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_skipped() {
|
||||
let input = b"% comment\n42 % another\n/Name";
|
||||
let mut scanner = Scanner::new(input);
|
||||
|
||||
assert_eq!(scanner.parse_number().unwrap(), Number::Integer(42));
|
||||
assert_eq!(scanner.parse_name().unwrap(), Name::new(b"Name", true));
|
||||
assert!(scanner.at_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_type_is_error() {
|
||||
let mut scanner = Scanner::new(b"42 ");
|
||||
assert!(scanner.parse_name().is_err());
|
||||
}
|
||||
}
|
||||
Vendored
+191
@@ -0,0 +1,191 @@
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::reader::{Reader, is_regular};
|
||||
use crate::string::ascii_hex::decode_hex_digit;
|
||||
|
||||
/// A PostScript name object.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Name<'a> {
|
||||
data: &'a [u8],
|
||||
literal: bool,
|
||||
}
|
||||
|
||||
impl<'a> Name<'a> {
|
||||
pub(crate) fn new(data: &'a [u8], literal: bool) -> Self {
|
||||
Self { data, literal }
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a literal name.
|
||||
pub fn is_literal(&self) -> bool {
|
||||
self.literal
|
||||
}
|
||||
|
||||
/// Returns the name as a string if it is valid UTF-8, or
|
||||
/// `None` if it contains non-ASCII bytes.
|
||||
pub fn as_str(&self) -> Option<&'a str> {
|
||||
core::str::from_utf8(self.data).ok()
|
||||
}
|
||||
|
||||
/// Decode the name into `out`, replacing any previous contents.
|
||||
pub fn decode_into(&self, out: &mut Vec<u8>) -> Result<()> {
|
||||
out.clear();
|
||||
|
||||
// Fast path: no escape sequences.
|
||||
if !self.data.contains(&b'#') {
|
||||
out.extend_from_slice(self.data);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Slow path: Process escape sequences.
|
||||
let mut inner = Reader::new(self.data);
|
||||
|
||||
while let Some(b) = inner.read_byte() {
|
||||
if b == b'#' {
|
||||
let hex = inner.read_bytes(2).ok_or(Error::SyntaxError)?;
|
||||
let hi = decode_hex_digit(hex[0]).ok_or(Error::SyntaxError)?;
|
||||
let lo = decode_hex_digit(hex[1]).ok_or(Error::SyntaxError)?;
|
||||
out.push(hi << 4 | lo);
|
||||
} else {
|
||||
out.push(b);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode the name.
|
||||
pub fn decode(&self) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
self.decode_into(&mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
|
||||
r.forward_tag(b"/")?;
|
||||
let start = r.offset();
|
||||
while r.eat(is_regular).is_some() {}
|
||||
r.range(start..r.offset())
|
||||
}
|
||||
|
||||
pub(crate) fn parse_executable<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
|
||||
let start = r.offset();
|
||||
r.forward_while(is_regular);
|
||||
if r.offset() == start {
|
||||
return None;
|
||||
}
|
||||
r.range(start..r.offset())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn read_literal(input: &[u8]) -> Option<Name<'_>> {
|
||||
let mut r = Reader::new(input);
|
||||
parse_literal(&mut r).map(|d| Name::new(d, true))
|
||||
}
|
||||
|
||||
fn read_executable(input: &[u8]) -> Option<Name<'_>> {
|
||||
let mut r = Reader::new(input);
|
||||
parse_executable(&mut r).map(|d| Name::new(d, false))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_simple() {
|
||||
let n = read_literal(b"/Name1").unwrap();
|
||||
assert_eq!(n.as_str().unwrap(), "Name1");
|
||||
assert!(n.is_literal());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_empty_name() {
|
||||
let n = read_literal(b"/").unwrap();
|
||||
assert_eq!(n.as_str().unwrap(), "");
|
||||
assert!(n.is_literal());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_with_hex_escape() {
|
||||
let n = read_literal(b"/lime#20Green").unwrap();
|
||||
assert_eq!(n.as_str().unwrap(), "lime#20Green");
|
||||
assert_eq!(n.decode().unwrap(), b"lime Green");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_multiple_hex_escapes() {
|
||||
let n = read_literal(b"/paired#28#29parentheses").unwrap();
|
||||
assert_eq!(n.decode().unwrap(), b"paired()parentheses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_special_chars() {
|
||||
let n = read_literal(b"/A;Name_With-Various***Characters?").unwrap();
|
||||
assert_eq!(n.as_str().unwrap(), "A;Name_With-Various***Characters?");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_stops_at_delimiter() {
|
||||
let mut r = Reader::new(b"/Name(rest");
|
||||
let data = parse_literal(&mut r).unwrap();
|
||||
assert_eq!(data, b"Name");
|
||||
assert_eq!(r.peek_byte(), Some(b'('));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_stops_at_whitespace() {
|
||||
let mut r = Reader::new(b"/Name rest");
|
||||
let data = parse_literal(&mut r).unwrap();
|
||||
assert_eq!(data, b"Name");
|
||||
assert_eq!(r.peek_byte(), Some(b' '));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_not_a_name() {
|
||||
assert!(read_literal(b"Name").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_simple() {
|
||||
let n = read_executable(b"beginbfchar ").unwrap();
|
||||
assert_eq!(n.as_str().unwrap(), "beginbfchar");
|
||||
assert!(!n.is_literal());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_stops_at_delimiter() {
|
||||
let mut r = Reader::new(b"def/name");
|
||||
let data = parse_executable(&mut r).unwrap();
|
||||
assert_eq!(data, b"def");
|
||||
assert_eq!(r.peek_byte(), Some(b'/'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_at_eof() {
|
||||
let n = read_executable(b"endcmap").unwrap();
|
||||
assert_eq!(n.as_str().unwrap(), "endcmap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_empty() {
|
||||
assert!(read_executable(b"").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_starts_at_delimiter() {
|
||||
assert!(read_executable(b"(foo)").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_no_escapes() {
|
||||
let n = Name::new(b"simple", true);
|
||||
assert_eq!(n.decode().unwrap(), b"simple");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_with_escapes() {
|
||||
let n = Name::new(b"lime#20Green", true);
|
||||
assert_eq!(n.decode().unwrap(), b"lime Green");
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
use crate::error::{Error, Result};
|
||||
use crate::reader::{Reader, is_delimiter, is_whitespace};
|
||||
|
||||
/// A PostScript number object (integer or real).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Number {
|
||||
Integer(i32),
|
||||
Real(f32),
|
||||
}
|
||||
|
||||
impl Number {
|
||||
/// Return the value as an `i32`. Reals are truncated.
|
||||
pub fn as_i32(self) -> i32 {
|
||||
match self {
|
||||
Self::Integer(v) => v,
|
||||
Self::Real(v) => v as i32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the value as an `f32`.
|
||||
pub fn as_f32(self) -> f32 {
|
||||
match self {
|
||||
Self::Integer(v) => v as f32,
|
||||
Self::Real(v) => v,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the value as an `f64`.
|
||||
pub fn as_f64(self) -> f64 {
|
||||
match self {
|
||||
Self::Integer(v) => v as f64,
|
||||
Self::Real(v) => v as f64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_terminated(r: &Reader<'_>) -> bool {
|
||||
match r.peek_byte() {
|
||||
None => true,
|
||||
Some(b) => is_whitespace(b) || is_delimiter(b),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read(r: &mut Reader<'_>) -> Result<Number> {
|
||||
let saved = r.offset();
|
||||
|
||||
// Optional sign.
|
||||
let first = r.peek_byte().ok_or(Error::SyntaxError)?;
|
||||
let has_sign = first == b'+' || first == b'-';
|
||||
|
||||
if has_sign {
|
||||
r.forward();
|
||||
}
|
||||
|
||||
// Consume leading digits.
|
||||
let digit_start = r.offset();
|
||||
r.forward_while(|b| b.is_ascii_digit());
|
||||
let has_digits = r.offset() > digit_start;
|
||||
|
||||
// Check if number is a radix number.
|
||||
if !has_sign && has_digits && r.peek_byte() == Some(b'#') {
|
||||
let base_bytes = r.range(digit_start..r.offset()).ok_or(Error::SyntaxError)?;
|
||||
let base_str = core::str::from_utf8(base_bytes).map_err(|_| Error::SyntaxError)?;
|
||||
let base = base_str.parse::<u32>().map_err(|_| Error::SyntaxError)?;
|
||||
|
||||
if !(2..=36).contains(&base) {
|
||||
return Err(Error::SyntaxError);
|
||||
}
|
||||
|
||||
// Skip `#`.
|
||||
r.forward();
|
||||
|
||||
let num_start = r.offset();
|
||||
r.forward_while(|b| b.is_ascii_alphanumeric());
|
||||
|
||||
if r.offset() == num_start || !is_terminated(r) {
|
||||
return Err(Error::SyntaxError);
|
||||
}
|
||||
|
||||
let num_bytes = r.range(num_start..r.offset()).ok_or(Error::SyntaxError)?;
|
||||
let num_str = core::str::from_utf8(num_bytes).map_err(|_| Error::SyntaxError)?;
|
||||
let value = i32::from_str_radix(num_str, base).map_err(|_| Error::SyntaxError)?;
|
||||
|
||||
return Ok(Number::Integer(value));
|
||||
}
|
||||
|
||||
// Check for real number indicators: `.` or `e`/`E`.
|
||||
let has_dot = r.peek_byte() == Some(b'.');
|
||||
|
||||
if has_dot {
|
||||
r.forward(); // skip '.'
|
||||
r.forward_while(|b| b.is_ascii_digit());
|
||||
}
|
||||
|
||||
// At this point we need at least some digits (before or after the dot).
|
||||
if !has_digits && !has_dot {
|
||||
return Err(Error::SyntaxError);
|
||||
}
|
||||
|
||||
let has_exponent = matches!(r.peek_byte(), Some(b'e' | b'E'));
|
||||
if has_exponent {
|
||||
r.forward();
|
||||
|
||||
// Optional exponent sign.
|
||||
if matches!(r.peek_byte(), Some(b'+' | b'-')) {
|
||||
r.forward();
|
||||
}
|
||||
|
||||
r.forward_while(|b| b.is_ascii_digit());
|
||||
}
|
||||
|
||||
if !is_terminated(r) {
|
||||
return Err(Error::SyntaxError);
|
||||
}
|
||||
|
||||
let token = r.range(saved..r.offset()).ok_or(Error::SyntaxError)?;
|
||||
let str = core::str::from_utf8(token).map_err(|_| Error::SyntaxError)?;
|
||||
|
||||
if has_dot || has_exponent {
|
||||
let value = str.parse::<f32>().map_err(|_| Error::SyntaxError)?;
|
||||
|
||||
Ok(Number::Real(value))
|
||||
} else {
|
||||
if !has_digits {
|
||||
return Err(Error::SyntaxError);
|
||||
}
|
||||
|
||||
let value = str.parse::<i32>().map_err(|_| Error::SyntaxError)?;
|
||||
|
||||
Ok(Number::Integer(value))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn read_num(input: &[u8]) -> Result<Number> {
|
||||
let mut r = Reader::new(input);
|
||||
read(&mut r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_integers() {
|
||||
assert_eq!(read_num(b"123 ").unwrap(), Number::Integer(123));
|
||||
assert_eq!(read_num(b"-98 ").unwrap(), Number::Integer(-98));
|
||||
assert_eq!(read_num(b"43445 ").unwrap(), Number::Integer(43445));
|
||||
assert_eq!(read_num(b"0 ").unwrap(), Number::Integer(0));
|
||||
assert_eq!(read_num(b"+17 ").unwrap(), Number::Integer(17));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_numbers() {
|
||||
assert_eq!(read_num(b"-.002 ").unwrap(), Number::Real(-0.002));
|
||||
assert_eq!(read_num(b"34.5 ").unwrap(), Number::Real(34.5));
|
||||
assert_eq!(read_num(b"-3.62 ").unwrap(), Number::Real(-3.62));
|
||||
assert_eq!(read_num(b"123.6e10 ").unwrap(), Number::Real(123.6e10));
|
||||
assert_eq!(read_num(b"1.0E-5 ").unwrap(), Number::Real(1.0E-5));
|
||||
assert_eq!(read_num(b"1E6 ").unwrap(), Number::Real(1E6));
|
||||
assert_eq!(read_num(b"-1. ").unwrap(), Number::Real(-1.0));
|
||||
assert_eq!(read_num(b"0.0 ").unwrap(), Number::Real(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radix_numbers() {
|
||||
assert_eq!(read_num(b"8#1777 ").unwrap(), Number::Integer(0o1777));
|
||||
assert_eq!(read_num(b"16#FFFE ").unwrap(), Number::Integer(0xFFFE));
|
||||
assert_eq!(read_num(b"2#1000 ").unwrap(), Number::Integer(0b1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid() {
|
||||
assert!(read_num(b"abc").is_err());
|
||||
assert!(read_num(b"+abc").is_err());
|
||||
assert!(read_num(b"1a").is_err());
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
use crate::array::{self, Array};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::name::{self, Name};
|
||||
use crate::number::{self, Number};
|
||||
use crate::reader::Reader;
|
||||
use crate::string::{self, String};
|
||||
|
||||
/// A PostScript object.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Object<'a> {
|
||||
/// A number object.
|
||||
Number(Number),
|
||||
/// A name object.
|
||||
Name(Name<'a>),
|
||||
/// A string object.
|
||||
String(String<'a>),
|
||||
/// An array object.
|
||||
Array(Array<'a>),
|
||||
}
|
||||
|
||||
pub(crate) fn read<'a>(r: &mut Reader<'a>) -> Result<Object<'a>> {
|
||||
// PdfCraft patch: `<<` and `>>` are skipped by looping instead of
|
||||
// recursing once per delimiter, so a long run cannot overflow the stack.
|
||||
loop {
|
||||
skip_whitespace_and_comments(r);
|
||||
|
||||
let b = r.peek_byte().ok_or(Error::SyntaxError)?;
|
||||
|
||||
return match b {
|
||||
b'(' => string::parse_literal(r)
|
||||
.map(|s| Object::String(String::from_literal(s)))
|
||||
.ok_or(Error::SyntaxError),
|
||||
b'<' => {
|
||||
if r.peek_bytes(2) == Some(b"<~") {
|
||||
string::parse_ascii85(r)
|
||||
.map(|s| Object::String(String::from_ascii85(s)))
|
||||
.ok_or(Error::SyntaxError)
|
||||
} else if r.peek_bytes(2) == Some(b"<<") {
|
||||
// TODO: Proper dict support. For now, skip `<<` and return
|
||||
// the next object so callers see the inner tokens.
|
||||
r.forward();
|
||||
r.forward();
|
||||
continue;
|
||||
} else {
|
||||
string::parse_hex(r)
|
||||
.map(|s| Object::String(String::from_hex(s)))
|
||||
.ok_or(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
b'/' => name::parse_literal(r)
|
||||
.map(|s| Object::Name(Name::new(s, true)))
|
||||
.ok_or(Error::SyntaxError),
|
||||
b'[' => array::parse(r).map(|d| Object::Array(Array::new(d))),
|
||||
b'>' => {
|
||||
if r.peek_bytes(2) == Some(b">>") {
|
||||
// TODO: Proper dict support. Skip `>>` closing delimiter.
|
||||
r.forward();
|
||||
r.forward();
|
||||
continue;
|
||||
} else {
|
||||
Err(Error::SyntaxError)
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
r.forward();
|
||||
Err(Error::UnsupportedType)
|
||||
}
|
||||
b'.' | b'+' | b'-' | b'0'..=b'9' => number::read(r).map(Object::Number),
|
||||
_ => name::parse_executable(r)
|
||||
.map(|s| Object::Name(Name::new(s, false)))
|
||||
.ok_or(Error::SyntaxError),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn at_end(r: &mut Reader<'_>) -> bool {
|
||||
skip_whitespace_and_comments(r);
|
||||
r.peek_byte().is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn skip_whitespace_and_comments(r: &mut Reader<'_>) {
|
||||
loop {
|
||||
match r.peek_byte() {
|
||||
Some(b) if crate::reader::is_whitespace(b) => {
|
||||
r.forward();
|
||||
}
|
||||
Some(b'%') => {
|
||||
r.forward();
|
||||
r.forward_while(|b| !crate::reader::is_eol(b));
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn read_one(input: &[u8]) -> Result<Object<'_>> {
|
||||
let mut r = Reader::new(input);
|
||||
read(&mut r)
|
||||
}
|
||||
|
||||
fn read_ok(input: &[u8]) -> Object<'_> {
|
||||
read_one(input).unwrap()
|
||||
}
|
||||
|
||||
fn read_err(input: &[u8]) -> Error {
|
||||
read_one(input).unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer() {
|
||||
assert_eq!(read_ok(b"42 "), Object::Number(Number::Integer(42)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_integer() {
|
||||
assert_eq!(read_ok(b"-7 "), Object::Number(Number::Integer(-7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_name() {
|
||||
assert_eq!(
|
||||
read_ok(b"/CMapName "),
|
||||
Object::Name(Name::new(b"CMapName", true))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_name() {
|
||||
let obj = read_ok(b"beginbfchar ");
|
||||
assert_eq!(obj, Object::Name(Name::new(b"beginbfchar", false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_string() {
|
||||
assert_eq!(
|
||||
read_ok(b"(Hello)"),
|
||||
Object::String(String::from_literal(b"Hello"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_string() {
|
||||
assert_eq!(
|
||||
read_ok(b"<48656C6C6F>"),
|
||||
Object::String(String::from_hex(b"48656C6C6F"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii85_string() {
|
||||
assert_eq!(
|
||||
read_ok(b"<~87cURDZ~>"),
|
||||
Object::String(String::from_ascii85(b"87cURDZ"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_simple() {
|
||||
let obj = read_ok(b"[1 2 3]");
|
||||
assert_eq!(obj, Object::Array(Array::new(b"1 2 3")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stray_close_bracket() {
|
||||
assert_eq!(read_err(b"]"), Error::SyntaxError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stray_gt() {
|
||||
assert_eq!(read_err(b">x"), Error::SyntaxError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_whitespace() {
|
||||
assert_eq!(read_ok(b" \t\n 42 "), Object::Number(Number::Integer(42)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_comments() {
|
||||
assert_eq!(
|
||||
read_ok(b"% this is a comment\n42 "),
|
||||
Object::Number(Number::Integer(42))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof() {
|
||||
assert!(read_one(b"").is_err());
|
||||
assert!(read_one(b" ").is_err());
|
||||
assert!(read_one(b"% comment only\n").is_err());
|
||||
}
|
||||
|
||||
// PdfCraft patch: `<<` and `>>` runs are skipped without recursion.
|
||||
#[test]
|
||||
fn long_open_dict_run_does_not_overflow() {
|
||||
let input = alloc::vec![b'<'; 1_000_000];
|
||||
assert_eq!(read_err(&input), Error::SyntaxError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_close_dict_run_does_not_overflow() {
|
||||
let input = b">>".repeat(500_000);
|
||||
assert_eq!(read_err(&input), Error::SyntaxError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dict_delimiters_are_skipped() {
|
||||
let mut r = Reader::new(b"<< /A 1 >>");
|
||||
assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"A", true))));
|
||||
assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(1))));
|
||||
assert_eq!(read(&mut r), Err(Error::SyntaxError));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_dict_delimiters_are_skipped() {
|
||||
let mut r = Reader::new(b"<<<< /X >>>> 7 <<\n% c\n<< >> 8");
|
||||
assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"X", true))));
|
||||
assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(7))));
|
||||
assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(8))));
|
||||
assert!(at_end(&mut r));
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
use core::ops::Range;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Reader<'a> {
|
||||
pub(crate) data: &'a [u8],
|
||||
pub(crate) offset: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
#[inline]
|
||||
pub(crate) fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, offset: 0 }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn jump(&mut self, offset: usize) {
|
||||
self.offset = offset;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn range(&self, range: Range<usize>) -> Option<&'a [u8]> {
|
||||
self.data.get(range)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn offset(&self) -> usize {
|
||||
self.offset
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
|
||||
let v = self.peek_bytes(len)?;
|
||||
self.offset += len;
|
||||
Some(v)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn read_byte(&mut self) -> Option<u8> {
|
||||
let v = self.peek_byte()?;
|
||||
self.offset += 1;
|
||||
Some(v)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> {
|
||||
self.data.get(self.offset..self.offset + len)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn peek_byte(&self) -> Option<u8> {
|
||||
self.data.get(self.offset).copied()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn eat(&mut self, f: impl Fn(u8) -> bool) -> Option<u8> {
|
||||
let val = self.peek_byte()?;
|
||||
if f(val) {
|
||||
self.forward();
|
||||
Some(val)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn forward(&mut self) {
|
||||
self.offset += 1;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn forward_while(&mut self, f: impl Fn(u8) -> bool) {
|
||||
while let Some(b) = self.peek_byte() {
|
||||
if f(b) {
|
||||
self.forward();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn forward_tag(&mut self, tag: &[u8]) -> Option<()> {
|
||||
self.peek_tag(tag)?;
|
||||
self.offset += tag.len();
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn peek_tag(&self, tag: &[u8]) -> Option<()> {
|
||||
let mut cloned = self.clone();
|
||||
|
||||
for b in tag.iter().copied() {
|
||||
if cloned.peek_byte() == Some(b) {
|
||||
cloned.forward();
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn skip_eol(&mut self) {
|
||||
while let Some(b) = self.peek_byte() {
|
||||
if is_eol(b) {
|
||||
self.forward();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn is_whitespace(b: u8) -> bool {
|
||||
matches!(b, 0x00 | 0x09 | 0x0a | 0x0c | 0x0d | 0x20)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn is_delimiter(b: u8) -> bool {
|
||||
matches!(
|
||||
b,
|
||||
b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
|
||||
)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn is_regular(b: u8) -> bool {
|
||||
!is_whitespace(b) && !is_delimiter(b)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn is_eol(b: u8) -> bool {
|
||||
matches!(b, 0x0a | 0x0d)
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
mod ascii_85;
|
||||
pub(crate) mod ascii_hex;
|
||||
mod literal;
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::reader::Reader;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum StringInner<'a> {
|
||||
Literal(&'a [u8]),
|
||||
Hex(&'a [u8]),
|
||||
Ascii85(&'a [u8]),
|
||||
}
|
||||
|
||||
/// A PostScript string object.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct String<'a> {
|
||||
inner: StringInner<'a>,
|
||||
}
|
||||
|
||||
impl<'a> String<'a> {
|
||||
pub(crate) const fn from_literal(data: &'a [u8]) -> Self {
|
||||
Self {
|
||||
inner: StringInner::Literal(data),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn from_hex(data: &'a [u8]) -> Self {
|
||||
Self {
|
||||
inner: StringInner::Hex(data),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn from_ascii85(data: &'a [u8]) -> Self {
|
||||
Self {
|
||||
inner: StringInner::Ascii85(data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode the string content into `out`, replacing any previous contents.
|
||||
pub fn decode_into(&self, out: &mut Vec<u8>) -> Result<()> {
|
||||
out.clear();
|
||||
match self.inner {
|
||||
StringInner::Literal(data) => literal::decode_into(data, out),
|
||||
StringInner::Hex(data) => ascii_hex::decode_into(data, out),
|
||||
StringInner::Ascii85(data) => ascii_85::decode_into(data, out),
|
||||
}
|
||||
.ok_or(Error::SyntaxError)
|
||||
}
|
||||
|
||||
/// Decode the string content.
|
||||
pub fn decode(&self) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
self.decode_into(&mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
|
||||
let start = r.offset();
|
||||
skip_literal(r)?;
|
||||
let end = r.offset();
|
||||
// Exclude outer parentheses.
|
||||
r.range(start + 1..end - 1)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_hex<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
|
||||
r.forward_tag(b"<")?;
|
||||
let start = r.offset();
|
||||
while let Some(b) = r.read_byte() {
|
||||
if b == b'>' {
|
||||
return r.range(start..r.offset() - 1);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn parse_ascii85<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
|
||||
r.forward_tag(b"<~")?;
|
||||
let start = r.offset();
|
||||
loop {
|
||||
let b = r.read_byte()?;
|
||||
if b == b'~' {
|
||||
let end = r.offset() - 1;
|
||||
r.forward_tag(b">")?;
|
||||
return r.range(start..end);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_literal(r: &mut Reader<'_>) -> Option<()> {
|
||||
r.forward_tag(b"(")?;
|
||||
let mut depth = 1_u32;
|
||||
|
||||
while depth > 0 {
|
||||
let byte = r.read_byte()?;
|
||||
match byte {
|
||||
b'\\' => {
|
||||
let _ = r.read_byte()?;
|
||||
}
|
||||
b'(' => depth += 1,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn decode_literal(input: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut r = Reader::new(input);
|
||||
let data = parse_literal(&mut r).ok_or(Error::SyntaxError)?;
|
||||
String::from_literal(data).decode()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_empty() {
|
||||
assert_eq!(decode_literal(b"()").unwrap(), b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_simple() {
|
||||
assert_eq!(decode_literal(b"(Hello)").unwrap(), b"Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_nested_parens() {
|
||||
assert_eq!(
|
||||
decode_literal(b"(Hi (()) there)").unwrap(),
|
||||
b"Hi (()) there"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_n() {
|
||||
assert_eq!(decode_literal(b"(a\\nb)").unwrap(), b"a\nb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_r() {
|
||||
assert_eq!(decode_literal(b"(a\\rb)").unwrap(), b"a\rb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_t() {
|
||||
assert_eq!(decode_literal(b"(a\\tb)").unwrap(), b"a\tb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_b() {
|
||||
assert_eq!(decode_literal(b"(a\\bb)").unwrap(), &[b'a', 0x08, b'b']);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_f() {
|
||||
assert_eq!(decode_literal(b"(a\\fb)").unwrap(), &[b'a', 0x0C, b'b']);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_backslash() {
|
||||
assert_eq!(decode_literal(b"(a\\\\b)").unwrap(), b"a\\b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_escape_parens() {
|
||||
assert_eq!(decode_literal(b"(Hi \\()").unwrap(), b"Hi (");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_octal_three_digits() {
|
||||
assert_eq!(decode_literal(b"(\\053)").unwrap(), b"+");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_octal_two_digits() {
|
||||
assert_eq!(decode_literal(b"(\\36)").unwrap(), b"\x1e");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_octal_one_digit() {
|
||||
assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_line_continuation_lf() {
|
||||
assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_line_continuation_cr() {
|
||||
assert_eq!(decode_literal(b"(Hi \\\rthere)").unwrap(), b"Hi there");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_line_continuation_crlf() {
|
||||
assert_eq!(decode_literal(b"(Hi \\\r\nthere)").unwrap(), b"Hi there");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_bare_eol_lf() {
|
||||
assert_eq!(decode_literal(b"(a\nb)").unwrap(), b"a\nb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_bare_eol_cr() {
|
||||
assert_eq!(decode_literal(b"(a\rb)").unwrap(), b"a\nb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_bare_eol_crlf() {
|
||||
assert_eq!(decode_literal(b"(a\r\nb)").unwrap(), b"a\nb");
|
||||
}
|
||||
|
||||
fn decode_hex(input: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut r = Reader::new(input);
|
||||
let data = parse_hex(&mut r).ok_or(Error::SyntaxError)?;
|
||||
String::from_hex(data).decode()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_simple() {
|
||||
assert_eq!(decode_hex(b"<48656C6C6F>").unwrap(), b"Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_with_whitespace() {
|
||||
assert_eq!(decode_hex(b"<48 65 6C 6C 6F>").unwrap(), b"Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_odd_nibble() {
|
||||
assert_eq!(decode_hex(b"<ABC>").unwrap(), &[0xAB, 0xC0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_empty() {
|
||||
assert_eq!(decode_hex(b"<>").unwrap(), b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_lowercase() {
|
||||
assert_eq!(decode_hex(b"<abcd>").unwrap(), &[0xAB, 0xCD]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_mixed_case() {
|
||||
assert_eq!(decode_hex(b"<aB3E>").unwrap(), &[0xAB, 0x3E]);
|
||||
}
|
||||
|
||||
fn decode_a85(input: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut r = Reader::new(input);
|
||||
let data = parse_ascii85(&mut r).ok_or(Error::SyntaxError)?;
|
||||
String::from_ascii85(data).decode()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii85_simple() {
|
||||
// "Hello" in ASCII85 is "87cURDZ"
|
||||
assert_eq!(decode_a85(b"<~87cURDZ~>").unwrap(), b"Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii85_empty() {
|
||||
assert_eq!(decode_a85(b"<~~>").unwrap(), b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii85_z_shorthand() {
|
||||
assert_eq!(decode_a85(b"<~z~>").unwrap(), &[0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii85_partial_group() {
|
||||
let result = decode_a85(b"<~87~>").unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii85_with_whitespace() {
|
||||
assert_eq!(decode_a85(b"<~87cU RDZ~>").unwrap(), b"Hello");
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// Keep in sync with `hayro-syntax/src/filter/ascii_85.rs`.
|
||||
|
||||
use crate::reader::{Reader, is_whitespace};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
|
||||
const POW_85: [u32; 5] = [52200625, 614125, 7225, 85, 1];
|
||||
|
||||
let mut reader = Reader::new(data);
|
||||
|
||||
let mut read_byte = || -> Option<u8> {
|
||||
loop {
|
||||
let b = reader.read_byte()?;
|
||||
|
||||
// White space characters should be ignored.
|
||||
if !is_whitespace(b) {
|
||||
return Some(b);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let flush_group = |group: &mut Vec<u8>, decoded: &mut Vec<u8>| -> Option<()> {
|
||||
let (digits, output_len): ([u32; 5], usize) = match group.len() {
|
||||
0 => return Some(()),
|
||||
1 => return None, // A single character is not valid.
|
||||
2 => (
|
||||
[group[0], group[1], b'u', b'u', b'u'].map(|b| (b - b'!') as u32),
|
||||
1,
|
||||
),
|
||||
3 => (
|
||||
[group[0], group[1], group[2], b'u', b'u'].map(|b| (b - b'!') as u32),
|
||||
2,
|
||||
),
|
||||
4 => (
|
||||
[group[0], group[1], group[2], group[3], b'u'].map(|b| (b - b'!') as u32),
|
||||
3,
|
||||
),
|
||||
5 => (
|
||||
[group[0], group[1], group[2], group[3], group[4]].map(|b| (b - b'!') as u32),
|
||||
4,
|
||||
),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let value = digits[0]
|
||||
.checked_mul(POW_85[0])?
|
||||
.checked_add(digits[1].checked_mul(POW_85[1])?)?
|
||||
.checked_add(digits[2].checked_mul(POW_85[2])?)?
|
||||
.checked_add(digits[3].checked_mul(POW_85[3])?)?
|
||||
.checked_add(digits[4])?;
|
||||
|
||||
decoded.extend_from_slice(&value.to_be_bytes()[..output_len]);
|
||||
group.clear();
|
||||
Some(())
|
||||
};
|
||||
|
||||
out.reserve(data.len() * 4 / 5);
|
||||
let mut group = Vec::with_capacity(5);
|
||||
|
||||
loop {
|
||||
let Some(b) = read_byte() else {
|
||||
// Be lenient and accept what we have (see PDFBOX-5910).
|
||||
flush_group(&mut group, out)?;
|
||||
|
||||
return Some(());
|
||||
};
|
||||
|
||||
match b {
|
||||
b'!'..=b'u' => {
|
||||
group.push(b);
|
||||
|
||||
if group.len() == 5 {
|
||||
flush_group(&mut group, out)?;
|
||||
}
|
||||
}
|
||||
b'z' => {
|
||||
flush_group(&mut group, out)?;
|
||||
out.extend_from_slice(&[0, 0, 0, 0]);
|
||||
}
|
||||
b'~' => {
|
||||
// Technically requires a '>', but there is a PDF where it isn't
|
||||
// appended and decodes fine in other viewers.
|
||||
flush_group(&mut group, out)?;
|
||||
|
||||
return Some(());
|
||||
}
|
||||
_ => return None, // Invalid character.
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
// Keep in sync with `hayro-syntax/src/filter/ascii_hex.rs`.
|
||||
|
||||
use crate::reader::is_whitespace;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
|
||||
let has_whitespace = data.iter().any(|&b| is_whitespace(b));
|
||||
|
||||
out.reserve(data.len().div_ceil(2));
|
||||
|
||||
if !has_whitespace {
|
||||
// Fast path, don't need to worry about white spaces.
|
||||
let mut i = 0;
|
||||
while i + 1 < data.len() {
|
||||
out.push(decode_hex_digit(data[i])? << 4 | decode_hex_digit(data[i + 1])?);
|
||||
i += 2;
|
||||
}
|
||||
if i < data.len() {
|
||||
out.push(decode_hex_digit(data[i])? << 4);
|
||||
}
|
||||
} else {
|
||||
// Slow path, need to strip white spaces.
|
||||
let mut iter = data.iter().copied();
|
||||
let mut read_byte = || -> Option<u8> {
|
||||
loop {
|
||||
let b = iter.next()?;
|
||||
if !is_whitespace(b) {
|
||||
return Some(b);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
match (read_byte(), read_byte()) {
|
||||
(Some(hi), Some(lo)) => {
|
||||
out.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?);
|
||||
}
|
||||
(Some(hi), None) => {
|
||||
out.push(decode_hex_digit(hi)? << 4);
|
||||
|
||||
break;
|
||||
}
|
||||
(None, _) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn decode_hex_digit(c: u8) -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
// Keep in sync with `hayro-syntax/src/object/string.rs` (`read_literal`).
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use crate::reader::Reader;
|
||||
|
||||
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
|
||||
let mut r = Reader::new(data);
|
||||
|
||||
while let Some(byte) = r.read_byte() {
|
||||
match byte {
|
||||
b'\\' => {
|
||||
let next = r.read_byte()?;
|
||||
|
||||
if is_octal_digit(next) {
|
||||
let second = r.read_byte();
|
||||
let third = r.read_byte();
|
||||
|
||||
let bytes = match (second, third) {
|
||||
(Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) {
|
||||
(true, true) => [next, n1, n2],
|
||||
(true, _) => {
|
||||
r.jump(r.offset() - 1);
|
||||
[b'0', next, n1]
|
||||
}
|
||||
_ => {
|
||||
r.jump(r.offset() - 2);
|
||||
[b'0', b'0', next]
|
||||
}
|
||||
},
|
||||
(Some(n1), None) => {
|
||||
if is_octal_digit(n1) {
|
||||
[b'0', next, n1]
|
||||
} else {
|
||||
r.jump(r.offset() - 1);
|
||||
[b'0', b'0', next]
|
||||
}
|
||||
}
|
||||
_ => [b'0', b'0', next],
|
||||
};
|
||||
|
||||
let str = core::str::from_utf8(&bytes).unwrap();
|
||||
|
||||
if let Ok(num) = u8::from_str_radix(str, 8) {
|
||||
out.push(num);
|
||||
}
|
||||
} else {
|
||||
match next {
|
||||
b'n' => out.push(0xA),
|
||||
b'r' => out.push(0xD),
|
||||
b't' => out.push(0x9),
|
||||
b'b' => out.push(0x8),
|
||||
b'f' => out.push(0xC),
|
||||
b'(' => out.push(b'('),
|
||||
b')' => out.push(b')'),
|
||||
b'\\' => out.push(b'\\'),
|
||||
b'\n' | b'\r' => {
|
||||
// "If the \ is followed immediately by a newline
|
||||
// (CR, LF, or CR-LF pair), the scanner ignores
|
||||
// both the initial \ and the newline; this breaks
|
||||
// a string into multiple lines without including
|
||||
// the newline character as part of the string."
|
||||
r.skip_eol();
|
||||
}
|
||||
_ => out.push(next),
|
||||
}
|
||||
}
|
||||
}
|
||||
b'(' | b')' => out.push(byte),
|
||||
// "But if a newline appears without a preceding \, the result is
|
||||
// equivalent to \n."
|
||||
b'\n' | b'\r' => {
|
||||
out.push(b'\n');
|
||||
r.skip_eol();
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn is_octal_digit(byte: u8) -> bool {
|
||||
matches!(byte, b'0'..=b'7')
|
||||
}
|
||||
Vendored
+1
-1
@@ -61,7 +61,7 @@ use vello_cpu::{Level, Pixmap, RenderMode};
|
||||
|
||||
mod renderer;
|
||||
/// PdfCraft patch: exported for its regression test.
|
||||
pub use renderer::{image_resampling_size, tiling_cell_scale, usable_cell_scale};
|
||||
pub use renderer::{image_resampling_size, tiling_cell_pixels, tiling_cell_scale, usable_cell_scale};
|
||||
/// PdfCraft patch: exported for its regression test.
|
||||
#[doc(hidden)]
|
||||
pub use renderer::set_skip_offscreen_paths;
|
||||
|
||||
Vendored
+39
-11
@@ -1302,13 +1302,18 @@ impl Renderer {
|
||||
xs = tiling_cell_scale(xs, t.x_step, MAX_PIXMAP_SIZE);
|
||||
ys = tiling_cell_scale(ys, t.y_step, MAX_PIXMAP_SIZE);
|
||||
|
||||
let x_step = xs * t.x_step;
|
||||
let y_step = ys * t.y_step;
|
||||
// PdfCraft patch (25): the cell pixmap repeats every `pix_width` pixels,
|
||||
// so one step must be exactly that many pixels. The cell is drawn at the
|
||||
// scale that makes it so, and the paint transform below maps the pixmap
|
||||
// back onto pattern space: cells sit at whole multiples of the step at
|
||||
// any device scale. Drawing at the unrounded scale repeated the cell a
|
||||
// fraction of a pixel too early or late, and the error grew with every
|
||||
// step away from the pattern's origin.
|
||||
let (pix_width, xs) = tiling_cell_pixels(xs, t.x_step, MAX_PIXMAP_SIZE);
|
||||
let (pix_height, ys) = tiling_cell_pixels(ys, t.y_step, MAX_PIXMAP_SIZE);
|
||||
|
||||
let scaled_width = bbox.width() as f32 * xs;
|
||||
let scaled_height = bbox.height() as f32 * ys;
|
||||
let pix_width = x_step.abs().round() as u16;
|
||||
let pix_height = y_step.abs().round() as u16;
|
||||
let scaled_width = bbox.width() * xs;
|
||||
let scaled_height = bbox.height() * ys;
|
||||
|
||||
let mut renderer = Self {
|
||||
ctx: RenderContext::new_with(
|
||||
@@ -1332,7 +1337,7 @@ impl Renderer {
|
||||
preview: self.preview,
|
||||
image_transparency_stack: Vec::new(),
|
||||
};
|
||||
let mut initial_transform = Affine::scale_non_uniform(xs as f64, ys as f64)
|
||||
let mut initial_transform = Affine::scale_non_uniform(xs, ys)
|
||||
* Affine::translate((-bbox.x0, -bbox.y0));
|
||||
t.interpret(&mut renderer, initial_transform, is_stroke);
|
||||
let mut pix = Pixmap::new(pix_width, pix_height);
|
||||
@@ -1341,14 +1346,14 @@ impl Renderer {
|
||||
renderer.ctx.render_to_pixmap(&mut resources, &mut pix);
|
||||
|
||||
// TODO: Fix these
|
||||
if x_step < 0.0 {
|
||||
if t.x_step < 0.0 {
|
||||
initial_transform *=
|
||||
Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width as f64, 0.0]);
|
||||
Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width, 0.0]);
|
||||
}
|
||||
|
||||
if y_step < 0.0 {
|
||||
if t.y_step < 0.0 {
|
||||
initial_transform *=
|
||||
Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height as f64]);
|
||||
Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height]);
|
||||
}
|
||||
|
||||
paint_transform =
|
||||
@@ -2186,3 +2191,26 @@ pub fn tiling_cell_scale(scale: f32, step: f32, max_pixels: f32) -> f32 {
|
||||
scale
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (25): the side of a tiling cell pixmap in pixels, and the scale to draw the
|
||||
/// cell at so that one `step` spans exactly that many pixels. The pixmap repeats every whole
|
||||
/// number of pixels; drawing the cell at `scale` itself would repeat it at `round(scale × step)`
|
||||
/// instead of `scale × step`, a fraction of a pixel off at every step (ISO 32000-2 8.7.3.1: cells
|
||||
/// are displaced by multiples of `/XStep` and `/YStep`). The side is kept within 1 and
|
||||
/// `max_pixels` (itself at most `u16::MAX`). When `scale × step` isn't finite and positive,
|
||||
/// `scale` is kept and the side is `max_pixels` for an infinite product, 1 otherwise.
|
||||
pub fn tiling_cell_pixels(scale: f32, step: f32, max_pixels: f32) -> (u16, f64) {
|
||||
// A whole number of pixels; `max` and `min` (not `clamp`, which panics on NaN) make a NaN cap 1.
|
||||
let max = f64::from(max_pixels).floor().max(1.0).min(f64::from(u16::MAX));
|
||||
let (scale, step) = (f64::from(scale), f64::from(step.abs()));
|
||||
let exact = scale * step;
|
||||
if !(exact.is_finite() && exact > 0.0) {
|
||||
let pixels = if exact == f64::INFINITY { max } else { 1.0 };
|
||||
// In 1..=u16::MAX, so the cast is exact.
|
||||
return (pixels as u16, scale);
|
||||
}
|
||||
let pixels = exact.round().max(1.0).min(max);
|
||||
// `pixels` is in 1..=u16::MAX, so the cast is exact; `step` is positive and finite here
|
||||
// (`exact` is), so the division is too.
|
||||
(pixels as u16, pixels / step)
|
||||
}
|
||||
|
||||
+29
-24
@@ -182,6 +182,34 @@ impl std::fmt::Display for Violation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer and testkit rules for one dependency of `c` that is itself a workspace crate.
|
||||
fn check_workspace_dep(c: &Crate, class: Class, layer: u8, d: &Dep, out: &mut Vec<Violation>) {
|
||||
let dep_class = classify(&d.name);
|
||||
// Test support is a dev-dependency only (`Class::Testkit`) and so never reaches
|
||||
// the product graph a standalone crate publishes. Checking it against the
|
||||
// standalone allow-list would stop `cos` using the shared oracles in its own
|
||||
// tests, which is the one thing those crates exist for.
|
||||
let testkit_dev = dep_class == Some(Class::Testkit) && d.kind == DepKind::Dev;
|
||||
if matches!(class, Class::Standalone(_)) && !testkit_dev && !standalone_allowed(&c.name, &d.name) {
|
||||
out.push(Violation::StandaloneHasWorkspaceDep { krate: c.name.clone(), dep: d.name.clone() });
|
||||
return;
|
||||
}
|
||||
match dep_class {
|
||||
None => {}
|
||||
Some(Class::Testkit) if d.kind != DepKind::Dev && class != Class::Testkit => {
|
||||
out.push(Violation::TestkitAsNormalDep { krate: c.name.clone(), dep: d.name.clone() });
|
||||
}
|
||||
Some(Class::Testkit) => {}
|
||||
Some(dc) => {
|
||||
let to = dc.layer().unwrap_or(u8::MAX);
|
||||
let ok = to < layer || (to == layer && sideways_allowed(&c.name, &d.name));
|
||||
if !ok {
|
||||
out.push(Violation::Upward { krate: c.name.clone(), dep: d.name.clone(), from: layer, to: to.min(8), kind: d.kind });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(crates: &[Crate]) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for c in crates {
|
||||
@@ -198,30 +226,7 @@ pub fn check(crates: &[Crate]) -> Vec<Violation> {
|
||||
continue;
|
||||
}
|
||||
if d.workspace {
|
||||
let dep_class = classify(&d.name);
|
||||
// Test support is a dev-dependency only (`Class::Testkit`) and so never reaches
|
||||
// the product graph a standalone crate publishes. Checking it against the
|
||||
// standalone allow-list would stop `cos` using the shared oracles in its own
|
||||
// tests, which is the one thing those crates exist for.
|
||||
let testkit_dev = dep_class == Some(Class::Testkit) && d.kind == DepKind::Dev;
|
||||
if matches!(class, Class::Standalone(_)) && !testkit_dev && !standalone_allowed(&c.name, &d.name) {
|
||||
out.push(Violation::StandaloneHasWorkspaceDep { krate: c.name.clone(), dep: d.name.clone() });
|
||||
continue;
|
||||
}
|
||||
match dep_class {
|
||||
None => {}
|
||||
Some(Class::Testkit) if d.kind != DepKind::Dev && class != Class::Testkit => {
|
||||
out.push(Violation::TestkitAsNormalDep { krate: c.name.clone(), dep: d.name.clone() });
|
||||
}
|
||||
Some(Class::Testkit) => {}
|
||||
Some(dc) => {
|
||||
let to = dc.layer().unwrap_or(u8::MAX);
|
||||
let ok = to < layer || (to == layer && sideways_allowed(&c.name, &d.name));
|
||||
if !ok {
|
||||
out.push(Violation::Upward { krate: c.name.clone(), dep: d.name.clone(), from: layer, to: to.min(8), kind: d.kind });
|
||||
}
|
||||
}
|
||||
}
|
||||
check_workspace_dep(c, class, layer, d, &mut out);
|
||||
} else if layer < UI_MIN_LAYER && is_ui_crate(&d.name) && !(class == Class::Testkit || d.kind == DepKind::Dev && d.name == "egui_kittest")
|
||||
{
|
||||
out.push(Violation::UiBelowL7 { krate: c.name.clone(), dep: d.name.clone(), layer });
|
||||
|
||||
+14
-8
@@ -104,6 +104,18 @@ fn valid_milestone(m: &str) -> bool {
|
||||
m == "none" || m.strip_prefix('M').and_then(|n| n.parse::<u32>().ok()).is_some_and(|n| n <= 14)
|
||||
}
|
||||
|
||||
/// Why an `evidence` entry (`path.rs::test_fn`) does not resolve to a test in the source tree, if it doesn't.
|
||||
fn evidence_error(ev: &str, repo: &Path) -> Option<String> {
|
||||
let Some((path, func)) = ev.split_once("::") else {
|
||||
return Some(format!("evidence {ev:?} must be `path.rs::test_fn`"));
|
||||
};
|
||||
match std::fs::read_to_string(repo.join(path)) {
|
||||
Ok(src) if src.contains(&format!("fn {func}(")) => None,
|
||||
Ok(_) => Some(format!("evidence: no `fn {func}` in {path}")),
|
||||
Err(_) => Some(format!("evidence: {path} does not exist")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate features against the registry, tool table and source tree; returns the errors.
|
||||
pub fn validate(features: &[Feature], commands: &HashSet<String>, tools: &HashSet<String>, repo: &Path) -> Vec<String> {
|
||||
let mut errors = Vec::new();
|
||||
@@ -143,14 +155,8 @@ pub fn validate(features: &[Feature], commands: &HashSet<String>, tools: &HashSe
|
||||
errors.push(e("shipped features must cite at least one test in `evidence`".into()));
|
||||
}
|
||||
for ev in &f.evidence {
|
||||
let Some((path, func)) = ev.split_once("::") else {
|
||||
errors.push(e(format!("evidence {ev:?} must be `path.rs::test_fn`")));
|
||||
continue;
|
||||
};
|
||||
match std::fs::read_to_string(repo.join(path)) {
|
||||
Ok(src) if src.contains(&format!("fn {func}(")) => {}
|
||||
Ok(_) => errors.push(e(format!("evidence: no `fn {func}` in {path}"))),
|
||||
Err(_) => errors.push(e(format!("evidence: {path} does not exist"))),
|
||||
if let Some(m) = evidence_error(ev, repo) {
|
||||
errors.push(e(m));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user