Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Refactor annot for strict Clippy checks

Dylan M. Taylor7d1ed99f51b2
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs
index 508d2bee4..abc746c0d 100644
--- a/crates/annot/src/appearance.rs
+++ b/crates/annot/src/appearance.rs
@@ -373,16 +373,60 @@ fn caret_layout(d: &Dict, rect: [f64; 4]) -> ([f64; 4], Option<(f64, f64, f64)>)
(caret, Some((caret[2] + gap * scale, caret[1] + size * 0.18, size)))
}
+#[derive(Clone, Copy)]
+struct AppearanceContext<'a> {
+ dict: &'a Dict,
+ subtype: &'a [u8],
+ rect: [f64; 4],
+ cloudy: bool,
+ opacity: f64,
+ stroke: Option<Rgb>,
+ width: f64,
+}
+
+#[derive(Default)]
+struct AppearanceDrawing {
+ resources: Dict,
+ content: String,
+ tail: Vec<u8>,
+}
+
+impl AppearanceDrawing {
+ fn new(context: &AppearanceContext<'_>) -> Self {
+ let mut drawing = Self::default();
+ if let Some(gs) = ext_gstate(context.opacity, context.subtype == b"Highlight") {
+ drawing.resources.set(b"ExtGState".to_vec(), Object::Dict(gs));
+ drawing.content.push_str("/GS0 gs\n");
+ }
+ drawing
+ }
+}
+
/// Draw the normal appearance of an annotation, or `None` if this subtype/variant isn't supported.
/// Text the standard fonts can't draw comes out as `?`: [`undrawable_text`] says which, and
/// [`crate::set_appearance`] marks the annotation with it (`pdfcraft_fonts::UNDRAWN_MARK`).
pub fn build(d: &Dict) -> Option<Stream> {
+ let context = appearance_context(d)?;
+ let drawing = AppearanceDrawing::new(&context);
+ match context.subtype {
+ b"Text" => return draw_icon(&context, "Note", [1.0, 0.82, 0.0], drawing),
+ b"FileAttachment" => return draw_icon(&context, "PushPin", [0.0, 0.47, 0.84], drawing),
+ b"Stamp" => return draw_stamp(&context, drawing),
+ b"FreeText" => return draw_free_text(&context, drawing),
+ _ => {}
+ }
+ let mut drawing = drawing;
+ draw_body(&context, &mut drawing)?;
+ finish_appearance(&context, drawing)
+}
+
+fn appearance_context(d: &Dict) -> Option<AppearanceContext<'_>> {
// Imported measurement appearances may include leaders, captions and formatting that
// this builder cannot reproduce. Preserve them rather than silently losing detail.
if d.contains(b"Measure") && !d.contains(b"PCMeasureValue") {
return None;
}
- let subtype = d.name(b"Subtype")?.to_vec();
+ let subtype = d.name(b"Subtype")?;
let rect = nums(d, b"Rect").filter(|r| r.len() == 4)?;
let rect = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
// Cloudy borders (§12.5.4) are drawn for polygons only.
@@ -390,520 +434,576 @@ pub fn build(d: &Dict) -> Option<Stream> {
if cloudy && subtype != b"Polygon" {
return None;
}
- let opacity = d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0);
- let stroke = color(d, b"C")?;
- 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));
- c.push_str("/GS0 gs\n");
- }
- match subtype.as_slice() {
- b"Text" => {
- let col = stroke.unwrap_or([1.0, 0.82, 0.0]);
- let icon = d.name(b"Name").map(|n| String::from_utf8_lossy(n).into_owned()).unwrap_or_else(|| "Note".into());
- c.push_str(&note_icon(&icon, col));
- return Some(form([0.0, 0.0, NOTE_SIZE, NOTE_SIZE], c.as_bytes(), res));
- }
- b"FileAttachment" => {
- let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
- let icon = d.name(b"Name").map(|n| String::from_utf8_lossy(n).into_owned()).unwrap_or_else(|| "PushPin".into());
- c.push_str(&attach_icon(&icon, col));
- return Some(form([0.0, 0.0, NOTE_SIZE, NOTE_SIZE], c.as_bytes(), res));
- }
- _ if markup => {
- let q = nums(d, b"QuadPoints").filter(|q| !q.is_empty() && q.len() % 8 == 0)?;
- let col = stroke?;
- for quad in q.as_chunks::<8>().0.iter() {
- let p = |i: usize| (quad[2 * i], quad[2 * i + 1]);
- let (p1, p2, p3, p4) = (p(0), p(1), p(2), p(3));
- let h = (p1.0 - p3.0).hypot(p1.1 - p3.1);
- // A point a fraction `t` of the way from the bottom edge to the top edge.
- let at = |bottom: (f64, f64), top: (f64, f64), t: f64| (bottom.0 + (top.0 - bottom.0) * t, bottom.1 + (top.1 - bottom.1) * t);
- match subtype.as_slice() {
- b"Highlight" => {
- c.push_str(&rg(col));
- c.push_str(&format!(
- "{} {} m {} {} l {} {} l {} {} l h f\n",
- n(p1.0),
- n(p1.1),
- n(p2.0),
- n(p2.1),
- n(p4.0),
- n(p4.1),
- n(p3.0),
- n(p3.1)
- ));
- }
- b"Underline" | b"StrikeOut" => {
- let lw = (h * 0.07).clamp(0.5, 3.0);
- let t = if subtype == b"Underline" { 0.08 } else { 0.42 };
- let (a, b) = (at(p3, p1, t), at(p4, p2, t));
- c.push_str(&format!("{}{} w\n{} {} m {} {} l S\n", rg_stroke(col), n(lw), n(a.0), n(a.1), n(b.0), n(b.1)));
- }
- _ => {
- // Squiggly: a zigzag along the bottom of the quad.
- let lw = (h * 0.05).clamp(0.5, 2.0);
- let amp = (h * 0.06).max(0.75);
- let len = (p4.0 - p3.0).hypot(p4.1 - p3.1);
- let step = (h / 4.0).max(1.5);
- let steps = ((len / step).ceil() as usize).clamp(1, 10_000);
- c.push_str(&format!("{}{} w 1 j\n", rg_stroke(col), n(lw)));
- for i in 0..=steps {
- let t = i as f64 / steps as f64;
- let base = (p3.0 + (p4.0 - p3.0) * t, p3.1 + (p4.1 - p3.1) * t);
- let up = if i % 2 == 0 { amp * 2.0 } else { 0.0 };
- let (ux, uy) = if h > 0.0 { ((p1.0 - p3.0) / h, (p1.1 - p3.1) / h) } else { (0.0, 1.0) };
- let (x, y) = (base.0 + ux * up, base.1 + uy * up);
- c.push_str(&format!("{} {} {}\n", n(x), n(y), if i == 0 { "m" } else { "l" }));
- }
- c.push_str("S\n");
- }
- }
- }
- }
- b"Redact" => {
- // While marked: the outline of each area (the fill comes when applied).
- let q = nums(d, b"QuadPoints").filter(|q| !q.is_empty() && q.len() % 8 == 0)?;
- let col = stroke.unwrap_or([0.89, 0.13, 0.13]);
- c.push_str(&format!("{}1 w\n", rg_stroke(col)));
- for quad in q.as_chunks::<8>().0.iter() {
- c.push_str(&format!(
- "{} {} m {} {} l {} {} l {} {} l h S\n",
- n(quad[0]),
- n(quad[1]),
- n(quad[2]),
- n(quad[3]),
- n(quad[6]),
- n(quad[7]),
- n(quad[4]),
- n(quad[5])
- ));
- }
- }
- b"Square" | b"Circle" => {
- let fill = interior_color(d, None);
- if stroke.is_none() && fill.is_none() {
- return Some(form(rect, c.as_bytes(), res));
- }
- let inset = w / 2.0;
- let [x0, y0, x1, y1] = [rect[0] + inset, rect[1] + inset, rect[2] - inset, rect[3] - inset];
- if let Some(f) = fill {
- c.push_str(&rg(f));
- }
- if let Some(s) = stroke {
- c.push_str(&format!("{}{} w\n{}", rg_stroke(s), n(w), dash(d)));
- }
- if subtype == b"Square" {
- c.push_str(&format!("{} {} {} {} re\n", n(x0), n(y0), n(x1 - x0), n(y1 - y0)));
- } else {
- c.push_str(&ellipse(x0, y0, x1, y1));
- }
- c.push_str(match (fill.is_some(), stroke.is_some() && w > 0.0) {
- (true, true) => "B\n",
- (true, false) => "f\n",
- (false, true) => "S\n",
- (false, false) => "n\n",
- });
+ Some(AppearanceContext {
+ dict: d,
+ subtype,
+ rect,
+ cloudy,
+ opacity: d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0),
+ stroke: color(d, b"C")?,
+ width: border_width(d),
+ })
+}
+
+fn draw_body(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ match context.subtype {
+ b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly" => draw_markup(context, drawing),
+ b"Redact" => draw_redaction(context, drawing),
+ b"Square" | b"Circle" => draw_box(context, drawing),
+ b"Line" => draw_line(context, drawing),
+ b"Polygon" | b"PolyLine" => draw_polygon(context, drawing),
+ b"Caret" => draw_caret(context, drawing),
+ b"Ink" => draw_ink(context, drawing),
+ _ => None,
+ }
+}
+
+fn finish_appearance(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -> 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 = drawing.content.into_bytes();
+ out.extend(drawing.tail);
+ if let Some(value) = context.dict.get(b"PCMeasureValue").and_then(Object::as_string) {
+ let value = value.to_text();
+ if value.chars().count() <= 256 && matches!(context.subtype, b"Line" | b"PolyLine" | b"Polygon") {
+ let size = 10.0;
+ let x = (context.rect[0] + context.rect[2] - text_width(&value, size)) * 0.5;
+ let y = context.rect[3] - 12.0;
+ let col = context.stroke.unwrap_or([0.0, 0.47, 0.84]);
+ out.extend(format!("{}BT /Helv {} Tf {} {} Td ", rg(col), n(size), n(x), n(y)).bytes());
+ // WinAnsi bytes (e.g. 0xB2 for "²") go into the stream as-is, not through UTF-8.
+ out.extend(literal(&win_ansi(&value)));
+ out.extend_from_slice(b" Tj ET\n");
+ drawing.resources.set(b"Font".to_vec(), helvetica_resource());
}
- b"Line" => {
- let l = nums(d, b"L").filter(|l| l.len() == 4 && l.iter().all(|x| x.is_finite()))?;
- let col = stroke?;
- let ends: Vec<Vec<u8>> = match d.get(b"LE") {
- None => vec![b"None".to_vec(), b"None".to_vec()],
- Some(o) => o.as_array()?.iter().map(|e| e.as_name().map(<[u8]>::to_vec)).collect::<Option<_>>()?,
- };
- if ends.len() != 2 || ends.iter().any(|e| !known_ending(e)) {
- return None;
+ }
+ Some(form(context.rect, &out, drawing.resources))
+}
+
+fn draw_markup(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let subtype = context.subtype;
+ let stroke = context.stroke;
+ let c = &mut drawing.content;
+ let q = nums(d, b"QuadPoints").filter(|q| !q.is_empty() && q.len() % 8 == 0)?;
+ let col = stroke?;
+ for quad in q.as_chunks::<8>().0.iter() {
+ let p = |i: usize| (quad[2 * i], quad[2 * i + 1]);
+ let (p1, p2, p3, p4) = (p(0), p(1), p(2), p(3));
+ let h = (p1.0 - p3.0).hypot(p1.1 - p3.1);
+ // A point a fraction `t` of the way from the bottom edge to the top edge.
+ let at = |bottom: (f64, f64), top: (f64, f64), t: f64| (bottom.0 + (top.0 - bottom.0) * t, bottom.1 + (top.1 - bottom.1) * t);
+ match subtype {
+ b"Highlight" => {
+ c.push_str(&rg(col));
+ c.push_str(&format!("{} {} m {} {} l {} {} l {} {} l h f\n", n(p1.0), n(p1.1), n(p2.0), n(p2.1), n(p4.0), n(p4.1), n(p3.0), n(p3.1)));
}
- 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)));
- 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)));
+ b"Underline" | b"StrikeOut" => {
+ let lw = (h * 0.07).clamp(0.5, 3.0);
+ let t = if subtype == b"Underline" { 0.08 } else { 0.42 };
+ let (a, b) = (at(p3, p1, t), at(p4, p2, t));
+ c.push_str(&format!("{}{} w\n{} {} m {} {} l S\n", rg_stroke(col), n(lw), n(a.0), n(a.1), n(b.0), n(b.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;
+ _ => {
+ // Squiggly: a zigzag along the bottom of the quad.
+ let lw = (h * 0.05).clamp(0.5, 2.0);
+ let amp = (h * 0.06).max(0.75);
+ let len = (p4.0 - p3.0).hypot(p4.1 - p3.1);
+ let step = (h / 4.0).max(1.5);
+ let steps = ((len / step).ceil() as usize).clamp(1, 10_000);
+ c.push_str(&format!("{}{} w 1 j\n", rg_stroke(col), n(lw)));
+ for i in 0..=steps {
+ let t = i as f64 / steps as f64;
+ let base = (p3.0 + (p4.0 - p3.0) * t, p3.1 + (p4.1 - p3.1) * t);
+ let up = if i % 2 == 0 { amp * 2.0 } else { 0.0 };
+ let (ux, uy) = if h > 0.0 { ((p1.0 - p3.0) / h, (p1.1 - p3.1) / h) } else { (0.0, 1.0) };
+ let (x, y) = (base.0 + ux * up, base.1 + uy * up);
+ c.push_str(&format!("{} {} {}\n", n(x), n(y), if i == 0 { "m" } else { "l" }));
}
- }
- 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());
+ c.push_str("S\n");
}
}
- 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()))?;
- let pts: Vec<(f64, f64)> = v.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
- let col = stroke;
- let closed = subtype == b"Polygon";
- let fill = if closed { interior_color(d, None) } else { None };
- let ends = if subtype == b"PolyLine" {
- match d.get(b"LE") {
- None => None,
- Some(o) => {
- let names: Vec<Vec<u8>> =
- o.as_array().filter(|a| a.len() == 2)?.iter().map(|e| e.as_name().map(<[u8]>::to_vec)).collect::<Option<_>>()?;
- if names.iter().any(|e| !known_ending(e)) {
- return None;
- }
- Some(names)
- }
- }
- } else {
- None
- };
- if let Some(f) = fill {
- c.push_str(&rg(f));
- }
- if let Some(s) = col {
- c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(s), n(w), dash(d)));
- }
- if cloudy {
- let intensity = d.get(b"BE").and_then(|b| b.as_dict()).and_then(|b| b.get(b"I")).and_then(|i| i.as_f64()).unwrap_or(1.0);
- c.push_str(&cloud_path(&pts, cloud_radius(w) * intensity.clamp(0.5, 2.0)));
- } else {
- for (i, p) in pts.iter().enumerate() {
- c.push_str(&format!("{} {} {}\n", n(p.0), n(p.1), if i == 0 { "m" } else { "l" }));
- }
- if closed {
- c.push_str("h\n");
- }
- }
- c.push_str(match (fill.is_some(), col.is_some() && w > 0.0) {
- (true, true) => "B\n",
- (true, false) => "f\n",
- (false, true) => "S\n",
- (false, false) => "n\n",
- });
- if let Some(ends) = ends {
- let col = col?;
- let (Some(start), Some(end)) = (ends.first(), ends.get(1)) else { return None };
- let (Some(&tip0), Some(&from0)) = (pts.first(), pts.get(1)) else { return None };
- let (Some(&tip1), Some(&from1)) = (pts.last(), pts.get(pts.len().saturating_sub(2))) else { return None };
- let fill = interior_color(d, Some(col)).unwrap_or(col);
- c.push_str(&format!("[] 0 d\n{}", rg(fill)));
- if !line_end(&mut c, start, tip0, from0, w) || !line_end(&mut c, end, tip1, from1, w) {
+ }
+ Some(())
+}
+
+fn draw_redaction(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let stroke = context.stroke;
+ let c = &mut drawing.content;
+ // While marked: the outline of each area (the fill comes when applied).
+ let q = nums(d, b"QuadPoints").filter(|q| !q.is_empty() && q.len() % 8 == 0)?;
+ let col = stroke.unwrap_or([0.89, 0.13, 0.13]);
+ c.push_str(&format!("{}1 w\n", rg_stroke(col)));
+ for quad in q.as_chunks::<8>().0.iter() {
+ c.push_str(&format!(
+ "{} {} m {} {} l {} {} l {} {} l h S\n",
+ n(quad[0]),
+ n(quad[1]),
+ n(quad[2]),
+ n(quad[3]),
+ n(quad[6]),
+ n(quad[7]),
+ n(quad[4]),
+ n(quad[5])
+ ));
+ }
+ Some(())
+}
+
+fn draw_box(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let subtype = context.subtype;
+ let rect = context.rect;
+ let stroke = context.stroke;
+ let w = context.width;
+ let c = &mut drawing.content;
+ let fill = interior_color(d, None);
+ if stroke.is_none() && fill.is_none() {
+ return Some(());
+ }
+ let inset = w / 2.0;
+ let [x0, y0, x1, y1] = [rect[0] + inset, rect[1] + inset, rect[2] - inset, rect[3] - inset];
+ if let Some(f) = fill {
+ c.push_str(&rg(f));
+ }
+ if let Some(s) = stroke {
+ c.push_str(&format!("{}{} w\n{}", rg_stroke(s), n(w), dash(d)));
+ }
+ if subtype == b"Square" {
+ c.push_str(&format!("{} {} {} {} re\n", n(x0), n(y0), n(x1 - x0), n(y1 - y0)));
+ } else {
+ c.push_str(&ellipse(x0, y0, x1, y1));
+ }
+ c.push_str(match (fill.is_some(), stroke.is_some() && w > 0.0) {
+ (true, true) => "B\n",
+ (true, false) => "f\n",
+ (false, true) => "S\n",
+ (false, false) => "n\n",
+ });
+ Some(())
+}
+
+fn draw_line(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let stroke = context.stroke;
+ let w = context.width;
+ let c = &mut drawing.content;
+ let res = &mut drawing.resources;
+ let tail = &mut drawing.tail;
+ let l = nums(d, b"L").filter(|l| l.len() == 4 && l.iter().all(|x| x.is_finite()))?;
+ let col = stroke?;
+ let ends: Vec<Vec<u8>> = match d.get(b"LE") {
+ None => vec![b"None".to_vec(), b"None".to_vec()],
+ Some(o) => o.as_array()?.iter().map(|e| e.as_name().map(<[u8]>::to_vec)).collect::<Option<_>>()?,
+ };
+ if ends.len() != 2 || ends.iter().any(|e| !known_ending(e)) {
+ 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)));
+ 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(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());
+ }
+ Some(())
+}
+
+fn draw_polygon(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let subtype = context.subtype;
+ let stroke = context.stroke;
+ let w = context.width;
+ let cloudy = context.cloudy;
+ let c = &mut drawing.content;
+ let v = nums(d, b"Vertices").filter(|v| v.len() >= 4 && v.len() % 2 == 0 && v.iter().all(|x| x.is_finite()))?;
+ let pts: Vec<(f64, f64)> = v.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
+ let col = stroke;
+ let closed = subtype == b"Polygon";
+ let fill = if closed { interior_color(d, None) } else { None };
+ let ends = if subtype == b"PolyLine" {
+ match d.get(b"LE") {
+ None => None,
+ Some(o) => {
+ let names: Vec<Vec<u8>> =
+ o.as_array().filter(|a| a.len() == 2)?.iter().map(|e| e.as_name().map(<[u8]>::to_vec)).collect::<Option<_>>()?;
+ if names.iter().any(|e| !known_ending(e)) {
return None;
}
+ Some(names)
}
}
- b"Caret" => {
- // A filled caret: two curved flanks meeting at the top centre.
- let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
- let (caret, pilcrow) = caret_layout(d, rect);
- let [x0, y0, x1, y1] = caret;
- let (cx, h) = ((x0 + x1) / 2.0, y1 - y0);
- c.push_str(&format!(
- "{}{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c h f\n",
- rg(col),
- n(x0),
- n(y0),
- n(cx - (x1 - x0) * 0.1),
- n(y0 + h * 0.2),
- n(cx),
- n(y1 - h * 0.25),
- n(cx),
- n(y1),
- n(cx),
- n(y1 - h * 0.25),
- n(cx + (x1 - x0) * 0.1),
- n(y0 + h * 0.2),
- n(x1),
- n(y0)
- ));
- if let Some((x, y, size)) = pilcrow {
- // `/Sy /P`: a new paragraph symbol beside the caret (Table 183), in its colour.
- // 0xB6 is the pilcrow in WinAnsiEncoding.
- let mut out = c.into_bytes();
- out.extend(format!("BT /Helv {} Tf {} {} Td (", n(size), n(x), n(y)).bytes());
- out.push(0xB6);
- out.extend_from_slice(b") Tj ET\n");
- res.set(b"Font".to_vec(), helvetica_resource());
- return Some(form(rect, &out, res));
- }
+ } else {
+ None
+ };
+ if let Some(f) = fill {
+ c.push_str(&rg(f));
+ }
+ if let Some(s) = col {
+ c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(s), n(w), dash(d)));
+ }
+ if cloudy {
+ let intensity = d.get(b"BE").and_then(|b| b.as_dict()).and_then(|b| b.get(b"I")).and_then(|i| i.as_f64()).unwrap_or(1.0);
+ c.push_str(&cloud_path(&pts, cloud_radius(w) * intensity.clamp(0.5, 2.0)));
+ } else {
+ for (i, p) in pts.iter().enumerate() {
+ c.push_str(&format!("{} {} {}\n", n(p.0), n(p.1), if i == 0 { "m" } else { "l" }));
}
- b"Ink" => {
- let col = stroke?;
- let list = d.get(b"InkList")?.as_array()?;
- // `/BS` gives an ink stroke its width and dash pattern (Table 182).
- c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(col), n(w), dash(d)));
- for s in list {
- let pts: Vec<f64> = s.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<_>>()?;
- let pts: Vec<(f64, f64)> = pts.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
- let Some(first) = pts.first() else { continue };
- c.push_str(&format!("{} {} m\n", n(first.0), n(first.1)));
- match pts.as_slice() {
- [_] => c.push_str(&format!("{} {} l\n", n(first.0 + 0.01), n(first.1))),
- [_, end] => c.push_str(&format!("{} {} l\n", n(end.0), n(end.1))),
- _ => c.push_str(&smooth_curve(&pts)),
- }
- c.push_str("S\n");
- }
+ if closed {
+ c.push_str("h\n");
}
- b"Stamp" => {
- // A typed signature: filled outlines normalised to the rectangle.
- if let Some(outline) = d.get(b"PCOutline").and_then(|o| o.as_array()) {
- let [x0, y0, x1, y1] = rect;
- let (w, h) = (x1 - x0, y1 - y0);
- c.push_str(&rg(stroke.unwrap_or([0.0; 3])));
- for contour in outline {
- let v: Vec<f64> = contour.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect()).unwrap_or_default();
- for (i, p) in v.as_chunks::<2>().0.iter().enumerate() {
- c.push_str(&format!("{} {} {}\n", n(x0 + p[0] * w), n(y0 + p[1] * h), if i == 0 { "m" } else { "l" }));
- }
- if v.len() >= 6 {
- c.push_str("h\n");
- }
- }
- c.push_str("f\n");
- return Some(form(rect, c.as_bytes(), res));
- }
- // A custom stamp: its picture (an image, or a form mapped to /PCPictureSize) fills
- // the rectangle. An image signature added to a turned page (`/PCPictureRotate`) gets
- // the standard counter-rotation as its form `/Matrix`: viewers fit the turned
- // bounding box to `/Rect` (ISO 32000-2 §12.5.5), so it reads upright as displayed.
- if let Some(pic) = d.get(b"PCPicture").and_then(Object::as_ref) {
- let [x0, y0, x1, y1] = rect;
- let (w, h) = (x1 - x0, y1 - y0);
- let image = matches!(d.get(b"PCPictureImage"), Some(Object::Bool(true)));
- let place = if image {
- format!("{} 0 0 {} {} {} cm", n(w), n(h), n(x0), n(y0))
- } else {
- let size = nums(d, b"PCPictureSize").filter(|s| s.len() == 2 && s[0] > 0.0 && s[1] > 0.0)?;
- format!("{} 0 0 {} {} {} cm", n(w / size[0]), n(h / size[1]), n(x0), n(y0))
- };
- c.push_str(&format!("q {place} /Pic Do Q\n"));
- let mut xo = Dict::new();
- xo.set(b"Pic".to_vec(), Object::Ref(pic));
- res.set(b"XObject".to_vec(), Object::Dict(xo));
- let mut stream = form(rect, c.as_bytes(), res);
- let turn = picture_turn(d);
- if image && turn != 0 {
- // The page's view matrix without its offset: display axes in user space.
- let m = pdfcraft_model::view_matrix_for(turn, [0.0; 4]);
- let matrix = [m[0], m[1], m[2], m[3], 0.0, 0.0];
- stream.dict.set(b"Matrix".to_vec(), Object::Array(matrix.iter().map(|x| Object::Real(*x)).collect()));
- }
- return Some(stream);
- }
- // Only PdfCraft's own Fill & Sign marks are drawn here.
- let name = d.name(b"Name")?;
- let col = stroke.unwrap_or([0.0; 3]);
- // A mark or stamp placed on a turned page is drawn upright in its displayed box, then
- // mapped into `/Rect` the way the page maps display space into user space. Viewers
- // fit that box to `/Rect`; the page rotation then shows it the right way up.
- let turn = stamp_turn(d);
- let draw = if turn == 0 {
- rect
- } else {
- let (rw, rh) = (rect[2] - rect[0], rect[3] - rect[1]);
- let (dw, dh) = if matches!(turn, 90 | 270) { (rh, rw) } else { (rw, rh) };
- if dw < 1.0 || dh < 1.0 {
- return None;
- }
- [0.0, 0.0, dw, dh]
- };
- let turned = |mut stream: Stream| {
- if turn != 0 {
- let m = pdfcraft_model::view_matrix_for(turn, rect);
- stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
- }
- stream
- };
- let [x0, y0, x1, y1] = draw;
- let (w, h) = (x1 - x0, y1 - y0);
- let lw = w.min(h) * 0.12;
- match name {
- b"PCCheck" => c.push_str(&format!(
- "{}{} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n",
- rg_stroke(col),
- n(lw),
- n(x0 + w * 0.15),
- n(y0 + h * 0.5),
- n(x0 + w * 0.4),
- n(y0 + h * 0.2),
- n(x0 + w * 0.88),
- n(y0 + h * 0.85)
- )),
- b"PCCross" => c.push_str(&format!(
- "{}{} w 1 J\n{} {} m {} {} l {} {} m {} {} l S\n",
- rg_stroke(col),
- n(lw),
- n(x0 + w * 0.18),
- n(y0 + h * 0.18),
- n(x1 - w * 0.18),
- n(y1 - h * 0.18),
- n(x0 + w * 0.18),
- n(y1 - h * 0.18),
- n(x1 - w * 0.18),
- n(y0 + h * 0.18)
- )),
- b"PCDot" => {
- let r = w.min(h) * 0.3;
- c.push_str(&rg(col));
- c.push_str(&ellipse(x0 + w / 2.0 - r, y0 + h / 2.0 - r, x0 + w / 2.0 + r, y0 + h / 2.0 + r));
- c.push_str("f\n");
- }
- b"PCLine" => c.push_str(&format!(
- "{}{} w 1 J\n{} {} m {} {} l S\n",
- rg_stroke(col),
- n(h.clamp(0.5, 2.0)),
- n(x0),
- n(y0 + h / 2.0),
- n(x1),
- n(y0 + h / 2.0)
- )),
- other => {
- // Only stamps PdfCraft made: others keep their own artwork.
- if !matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) {
- return None;
- }
- let kind = crate::StampKind::from_name(other)?;
- let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);
- let sign_here = kind.group() == crate::StampGroup::SignHere;
- return Some(turned(stamp(kind.label(), sign_here, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
- }
- }
- if turn != 0 {
- return Some(turned(form(draw, c.as_bytes(), res)));
- }
+ }
+ c.push_str(match (fill.is_some(), col.is_some() && w > 0.0) {
+ (true, true) => "B\n",
+ (true, false) => "f\n",
+ (false, true) => "S\n",
+ (false, false) => "n\n",
+ });
+ if let Some(ends) = ends {
+ let col = col?;
+ let (Some(start), Some(end)) = (ends.first(), ends.get(1)) else { return None };
+ let (Some(&tip0), Some(&from0)) = (pts.first(), pts.get(1)) else { return None };
+ let (Some(&tip1), Some(&from1)) = (pts.last(), pts.get(pts.len().saturating_sub(2))) else { return None };
+ let fill = interior_color(d, Some(col)).unwrap_or(col);
+ c.push_str(&format!("[] 0 d\n{}", rg(fill)));
+ if !line_end(c, start, tip0, from0, w) || !line_end(c, end, tip1, from1, w) {
+ return None;
}
- b"FreeText" => {
- let (text_color, size) = parse_da(d);
- let bg = stroke;
- let bw = if d.contains(b"BS") || d.contains(b"Border") { border_width(d) } else { 0.0 };
- // A callout: the leader line (arrowhead at its first point), and the text box inside
- // `/Rect` by `/RD`.
- // Text added to a turned page is drawn upright in its displayed box, which the form
- // `/Matrix` then maps into `/Rect` (as for stamps). Callouts keep user-space axes.
- let turn = if d.contains(b"CL") { 0 } else { text_turn(d) };
- let (rect, matrix) = if turn == 0 {
- (rect, None)
- } else {
- let (rw, rh) = (rect[2] - rect[0], rect[3] - rect[1]);
- let (dw, dh) = if matches!(turn, 90 | 270) { (rh, rw) } else { (rw, rh) };
- if dw < 1.0 || dh < 1.0 {
- return None;
- }
- ([0.0, 0.0, dw, dh], Some(pdfcraft_model::view_matrix_for(turn, rect)))
- };
- let full = rect;
- let mut rect = rect;
- if d.contains(b"CL") {
- let cl = nums(d, b"CL").filter(|l| l.len() == 4 || l.len() == 6)?;
- let rd = nums(d, b"RD").filter(|r| r.len() == 4 && r.iter().all(|x| *x >= 0.0))?;
- rect = [full[0] + rd[0], full[1] + rd[1], full[2] - rd[2], full[3] - rd[3]];
- if rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
- return None;
- }
- let end = match d.get(b"LE") {
- None => b"None".to_vec(),
- Some(o) => o.as_name()?.to_vec(),
- };
- if !known_ending(&end) {
- return None;
- }
- let lw = bw.max(0.5);
- let pts: Vec<(f64, f64)> = cl.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
- if pts.len() < 2 || pts.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) {
- return None;
- }
- c.push_str(&format!("{}{}{} w 1 J 1 j\n", rg_stroke(text_color), rg(bg.unwrap_or([1.0; 3])), n(lw)));
- for (i, p) in pts.iter().enumerate() {
- c.push_str(&format!("{} {} {}\n", n(p.0), n(p.1), if i == 0 { "m" } else { "l" }));
- }
- c.push_str("S\n");
- if !line_end(&mut c, &end, pts[0], pts[1], lw) {
- return None;
- }
- }
- if let Some(bg) = bg {
- c.push_str(&format!("{}{} {} {} {} re f\n", rg(bg), n(rect[0]), n(rect[1]), n(rect[2] - rect[0]), n(rect[3] - rect[1])));
- }
- if bw > 0.0 {
- let h = bw / 2.0;
- c.push_str(&format!(
- "{}{} w\n{}{} {} {} {} re S\n[] 0 d\n",
- rg_stroke(text_color),
- n(bw),
- dash(d),
- n(rect[0] + h),
- n(rect[1] + h),
- n(rect[2] - rect[0] - bw),
- n(rect[3] - rect[1] - bw)
- ));
+ }
+ Some(())
+}
+
+fn draw_caret(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let rect = context.rect;
+ let stroke = context.stroke;
+ let c = &mut drawing.content;
+ // A filled caret: two curved flanks meeting at the top centre.
+ let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
+ let (caret, pilcrow) = caret_layout(d, rect);
+ let [x0, y0, x1, y1] = caret;
+ let (cx, h) = ((x0 + x1) / 2.0, y1 - y0);
+ c.push_str(&format!(
+ "{}{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c h f\n",
+ rg(col),
+ n(x0),
+ n(y0),
+ n(cx - (x1 - x0) * 0.1),
+ n(y0 + h * 0.2),
+ n(cx),
+ n(y1 - h * 0.25),
+ n(cx),
+ n(y1),
+ n(cx),
+ n(y1 - h * 0.25),
+ n(cx + (x1 - x0) * 0.1),
+ n(y0 + h * 0.2),
+ n(x1),
+ n(y0)
+ ));
+ if let Some((x, y, size)) = pilcrow {
+ // `/Sy /P`: a new paragraph symbol beside the caret (Table 183), in its colour.
+ // 0xB6 is the pilcrow in WinAnsiEncoding.
+ drawing.tail.extend(format!("BT /Helv {} Tf {} {} Td (", n(size), n(x), n(y)).bytes());
+ drawing.tail.push(0xB6);
+ drawing.tail.extend_from_slice(b") Tj ET\n");
+ drawing.resources.set(b"Font".to_vec(), helvetica_resource());
+ }
+ Some(())
+}
+
+fn draw_ink(context: &AppearanceContext<'_>, drawing: &mut AppearanceDrawing) -> Option<()> {
+ let d = context.dict;
+ let stroke = context.stroke;
+ let w = context.width;
+ let c = &mut drawing.content;
+ let col = stroke?;
+ let list = d.get(b"InkList")?.as_array()?;
+ // `/BS` gives an ink stroke its width and dash pattern (Table 182).
+ c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(col), n(w), dash(d)));
+ for s in list {
+ let pts: Vec<f64> = s.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<_>>()?;
+ let pts: Vec<(f64, f64)> = pts.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
+ let Some(first) = pts.first() else { continue };
+ c.push_str(&format!("{} {} m\n", n(first.0), n(first.1)));
+ match pts.as_slice() {
+ [_] => c.push_str(&format!("{} {} l\n", n(first.0 + 0.01), n(first.1))),
+ [_, end] => c.push_str(&format!("{} {} l\n", n(end.0), n(end.1))),
+ _ => c.push_str(&smooth_curve(&pts)),
+ }
+ c.push_str("S\n");
+ }
+ Some(())
+}
+
+fn draw_stamp(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -> Option<Stream> {
+ let d = context.dict;
+ let rect = context.rect;
+ let stroke = context.stroke;
+ let opacity = context.opacity;
+ let c = &mut drawing.content;
+ let mut res = std::mem::take(&mut drawing.resources);
+ // A typed signature: filled outlines normalised to the rectangle.
+ if let Some(outline) = d.get(b"PCOutline").and_then(|o| o.as_array()) {
+ let [x0, y0, x1, y1] = rect;
+ let (w, h) = (x1 - x0, y1 - y0);
+ c.push_str(&rg(stroke.unwrap_or([0.0; 3])));
+ for contour in outline {
+ let v: Vec<f64> = contour.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect()).unwrap_or_default();
+ for (i, p) in v.as_chunks::<2>().0.iter().enumerate() {
+ c.push_str(&format!("{} {} {}\n", n(x0 + p[0] * w), n(y0 + p[1] * h), if i == 0 { "m" } else { "l" }));
}
- let text = d.get(b"Contents").and_then(|o| o.as_string()).map(PdfString::to_text).unwrap_or_default();
- let pad = 2.0 + bw;
- let width = (rect[2] - rect[0] - 2.0 * pad).max(1.0);
- let q = d.int(b"Q").unwrap_or(0);
- c.push_str(&format!(
- "{} {} {} {} re W n\nBT\n/Helv {} Tf\n{}",
- n(rect[0]),
- n(rect[1]),
- n(rect[2] - rect[0]),
- n(rect[3] - rect[1]),
- n(size),
- rg(text_color)
- ));
- let mut out = c.into_bytes();
- let mut y = rect[3] - pad - size * 0.9;
- for line in wrap(&text, size, width) {
- if y < rect[1] - size {
- break;
- }
- let lw = text_width(&line, size);
- let x = match q {
- 1 => rect[0] + pad + (width - lw) / 2.0,
- 2 => rect[2] - pad - lw,
- _ => rect[0] + pad,
- };
- out.extend(format!("1 0 0 1 {} {} Tm ", n(x), n(y)).bytes());
- out.extend(literal(&win_ansi(&line)));
- out.extend_from_slice(b" Tj\n");
- y -= size * 1.2;
+ if v.len() >= 6 {
+ c.push_str("h\n");
}
- out.extend_from_slice(b"ET\n");
- res.set(b"Font".to_vec(), helvetica_resource());
- let mut stream = form(full, &out, res);
- if let Some(m) = matrix {
- stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
+ }
+ c.push_str("f\n");
+ return Some(form(rect, c.as_bytes(), res));
+ }
+ // A custom stamp: its picture (an image, or a form mapped to /PCPictureSize) fills
+ // the rectangle. An image signature added to a turned page (`/PCPictureRotate`) gets
+ // the standard counter-rotation as its form `/Matrix`: viewers fit the turned
+ // bounding box to `/Rect` (ISO 32000-2 §12.5.5), so it reads upright as displayed.
+ if let Some(pic) = d.get(b"PCPicture").and_then(Object::as_ref) {
+ let [x0, y0, x1, y1] = rect;
+ let (w, h) = (x1 - x0, y1 - y0);
+ let image = matches!(d.get(b"PCPictureImage"), Some(Object::Bool(true)));
+ let place = if image {
+ format!("{} 0 0 {} {} {} cm", n(w), n(h), n(x0), n(y0))
+ } else {
+ let size = nums(d, b"PCPictureSize").filter(|s| s.len() == 2 && s[0] > 0.0 && s[1] > 0.0)?;
+ format!("{} 0 0 {} {} {} cm", n(w / size[0]), n(h / size[1]), n(x0), n(y0))
+ };
+ c.push_str(&format!("q {place} /Pic Do Q\n"));
+ let mut xo = Dict::new();
+ xo.set(b"Pic".to_vec(), Object::Ref(pic));
+ res.set(b"XObject".to_vec(), Object::Dict(xo));
+ let mut stream = form(rect, c.as_bytes(), res);
+ let turn = picture_turn(d);
+ if image && turn != 0 {
+ // The page's view matrix without its offset: display axes in user space.
+ let m = pdfcraft_model::view_matrix_for(turn, [0.0; 4]);
+ let matrix = [m[0], m[1], m[2], m[3], 0.0, 0.0];
+ stream.dict.set(b"Matrix".to_vec(), Object::Array(matrix.iter().map(|x| Object::Real(*x)).collect()));
+ }
+ return Some(stream);
+ }
+ // Only PdfCraft's own Fill & Sign marks are drawn here.
+ let name = d.name(b"Name")?;
+ let col = stroke.unwrap_or([0.0; 3]);
+ // A mark or stamp placed on a turned page is drawn upright in its displayed box, then
+ // mapped into `/Rect` the way the page maps display space into user space. Viewers
+ // fit that box to `/Rect`; the page rotation then shows it the right way up.
+ let turn = stamp_turn(d);
+ let draw = if turn == 0 {
+ rect
+ } else {
+ let (rw, rh) = (rect[2] - rect[0], rect[3] - rect[1]);
+ let (dw, dh) = if matches!(turn, 90 | 270) { (rh, rw) } else { (rw, rh) };
+ if dw < 1.0 || dh < 1.0 {
+ return None;
+ }
+ [0.0, 0.0, dw, dh]
+ };
+ let turned = |mut stream: Stream| {
+ if turn != 0 {
+ let m = pdfcraft_model::view_matrix_for(turn, rect);
+ stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
+ }
+ stream
+ };
+ let [x0, y0, x1, y1] = draw;
+ let (w, h) = (x1 - x0, y1 - y0);
+ let lw = w.min(h) * 0.12;
+ match name {
+ b"PCCheck" => c.push_str(&format!(
+ "{}{} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n",
+ rg_stroke(col),
+ n(lw),
+ n(x0 + w * 0.15),
+ n(y0 + h * 0.5),
+ n(x0 + w * 0.4),
+ n(y0 + h * 0.2),
+ n(x0 + w * 0.88),
+ n(y0 + h * 0.85)
+ )),
+ b"PCCross" => c.push_str(&format!(
+ "{}{} w 1 J\n{} {} m {} {} l {} {} m {} {} l S\n",
+ rg_stroke(col),
+ n(lw),
+ n(x0 + w * 0.18),
+ n(y0 + h * 0.18),
+ n(x1 - w * 0.18),
+ n(y1 - h * 0.18),
+ n(x0 + w * 0.18),
+ n(y1 - h * 0.18),
+ n(x1 - w * 0.18),
+ n(y0 + h * 0.18)
+ )),
+ b"PCDot" => {
+ let r = w.min(h) * 0.3;
+ c.push_str(&rg(col));
+ c.push_str(&ellipse(x0 + w / 2.0 - r, y0 + h / 2.0 - r, x0 + w / 2.0 + r, y0 + h / 2.0 + r));
+ c.push_str("f\n");
+ }
+ b"PCLine" => c.push_str(&format!(
+ "{}{} w 1 J\n{} {} m {} {} l S\n",
+ rg_stroke(col),
+ n(h.clamp(0.5, 2.0)),
+ n(x0),
+ n(y0 + h / 2.0),
+ n(x1),
+ n(y0 + h / 2.0)
+ )),
+ other => {
+ // Only stamps PdfCraft made: others keep their own artwork.
+ if !matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) {
+ return None;
}
- return Some(stream);
+ let kind = crate::StampKind::from_name(other)?;
+ let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);
+ let sign_here = kind.group() == crate::StampGroup::SignHere;
+ return Some(turned(stamp(kind.label(), sign_here, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
}
- _ => return None,
}
- // PdfCraft measurement captions are kept separate from the comment's free-form text.
- // A restyle regenerates the path and its value together.
+ if turn != 0 {
+ return Some(turned(form(draw, c.as_bytes(), res)));
+ }
+ Some(form(rect, c.as_bytes(), res))
+}
+
+fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -> Option<Stream> {
+ let d = context.dict;
+ let rect = context.rect;
+ let stroke = context.stroke;
+ let mut c = std::mem::take(&mut drawing.content);
+ let mut res = std::mem::take(&mut drawing.resources);
+ let _tail = std::mem::take(&mut drawing.tail);
+ let (text_color, size) = parse_da(d);
+ let bg = stroke;
+ let bw = if d.contains(b"BS") || d.contains(b"Border") { border_width(d) } else { 0.0 };
+ // A callout: the leader line (arrowhead at its first point), and the text box inside
+ // `/Rect` by `/RD`.
+ // Text added to a turned page is drawn upright in its displayed box, which the form
+ // `/Matrix` then maps into `/Rect` (as for stamps). Callouts keep user-space axes.
+ let turn = if d.contains(b"CL") { 0 } else { text_turn(d) };
+ let (rect, matrix) = if turn == 0 {
+ (rect, None)
+ } else {
+ let (rw, rh) = (rect[2] - rect[0], rect[3] - rect[1]);
+ let (dw, dh) = if matches!(turn, 90 | 270) { (rh, rw) } else { (rw, rh) };
+ if dw < 1.0 || dh < 1.0 {
+ return None;
+ }
+ ([0.0, 0.0, dw, dh], Some(pdfcraft_model::view_matrix_for(turn, rect)))
+ };
+ let full = rect;
+ let mut rect = rect;
+ if d.contains(b"CL") {
+ let cl = nums(d, b"CL").filter(|l| l.len() == 4 || l.len() == 6)?;
+ let rd = nums(d, b"RD").filter(|r| r.len() == 4 && r.iter().all(|x| *x >= 0.0))?;
+ rect = [full[0] + rd[0], full[1] + rd[1], full[2] - rd[2], full[3] - rd[3]];
+ if rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
+ return None;
+ }
+ let end = match d.get(b"LE") {
+ None => b"None".to_vec(),
+ Some(o) => o.as_name()?.to_vec(),
+ };
+ if !known_ending(&end) {
+ return None;
+ }
+ let lw = bw.max(0.5);
+ let pts: Vec<(f64, f64)> = cl.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
+ if pts.len() < 2 || pts.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) {
+ return None;
+ }
+ c.push_str(&format!("{}{}{} w 1 J 1 j\n", rg_stroke(text_color), rg(bg.unwrap_or([1.0; 3])), n(lw)));
+ for (i, p) in pts.iter().enumerate() {
+ c.push_str(&format!("{} {} {}\n", n(p.0), n(p.1), if i == 0 { "m" } else { "l" }));
+ }
+ c.push_str("S\n");
+ if !line_end(&mut c, &end, pts[0], pts[1], lw) {
+ return None;
+ }
+ }
+ if let Some(bg) = bg {
+ c.push_str(&format!("{}{} {} {} {} re f\n", rg(bg), n(rect[0]), n(rect[1]), n(rect[2] - rect[0]), n(rect[3] - rect[1])));
+ }
+ if bw > 0.0 {
+ let h = bw / 2.0;
+ c.push_str(&format!(
+ "{}{} w\n{}{} {} {} {} re S\n[] 0 d\n",
+ rg_stroke(text_color),
+ n(bw),
+ dash(d),
+ n(rect[0] + h),
+ n(rect[1] + h),
+ n(rect[2] - rect[0] - bw),
+ n(rect[3] - rect[1] - bw)
+ ));
+ }
+ let text = d.get(b"Contents").and_then(|o| o.as_string()).map(PdfString::to_text).unwrap_or_default();
+ let pad = 2.0 + bw;
+ let width = (rect[2] - rect[0] - 2.0 * pad).max(1.0);
+ let q = d.int(b"Q").unwrap_or(0);
+ c.push_str(&format!(
+ "{} {} {} {} re W n\nBT\n/Helv {} Tf\n{}",
+ n(rect[0]),
+ n(rect[1]),
+ n(rect[2] - rect[0]),
+ n(rect[3] - rect[1]),
+ n(size),
+ rg(text_color)
+ ));
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") {
- let size = 10.0;
- let x = (rect[0] + rect[2] - text_width(&value, size)) * 0.5;
- let y = rect[3] - 12.0;
- let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
- out.extend(format!("{}BT /Helv {} Tf {} {} Td ", rg(col), n(size), n(x), n(y)).bytes());
- // WinAnsi bytes (e.g. 0xB2 for "²") go into the stream as-is, not through UTF-8.
- out.extend(literal(&win_ansi(&value)));
- out.extend_from_slice(b" Tj ET\n");
- res.set(b"Font".to_vec(), helvetica_resource());
+ let mut y = rect[3] - pad - size * 0.9;
+ for line in wrap(&text, size, width) {
+ if y < rect[1] - size {
+ break;
}
+ let lw = text_width(&line, size);
+ let x = match q {
+ 1 => rect[0] + pad + (width - lw) / 2.0,
+ 2 => rect[2] - pad - lw,
+ _ => rect[0] + pad,
+ };
+ out.extend(format!("1 0 0 1 {} {} Tm ", n(x), n(y)).bytes());
+ out.extend(literal(&win_ansi(&line)));
+ out.extend_from_slice(b" Tj\n");
+ y -= size * 1.2;
+ }
+ out.extend_from_slice(b"ET\n");
+ res.set(b"Font".to_vec(), helvetica_resource());
+ let mut stream = form(full, &out, res);
+ if let Some(m) = matrix {
+ stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
}
- Some(form(rect, &out, res))
+ Some(stream)
+}
+
+fn draw_icon(context: &AppearanceContext<'_>, name: &str, fallback: Rgb, mut drawing: AppearanceDrawing) -> Option<Stream> {
+ let d = context.dict;
+ let col = context.stroke.unwrap_or(fallback);
+ let icon = d.name(b"Name").map(|n| String::from_utf8_lossy(n).into_owned()).unwrap_or_else(|| name.into());
+ let content = if name == "Note" { note_icon(&icon, col) } else { attach_icon(&icon, col) };
+ drawing.content.push_str(&content);
+ Some(form([0.0, 0.0, NOTE_SIZE, NOTE_SIZE], drawing.content.as_bytes(), drawing.resources))
}
diff --git a/crates/annot/src/appearance/symbols.rs b/crates/annot/src/appearance/symbols.rs
index d49224cd9..3b3366252 100644
--- a/crates/annot/src/appearance/symbols.rs
+++ b/crates/annot/src/appearance/symbols.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Dict, Object, PdfString, Rgb, Stream, color, ext_gstate, form, literal, n, nums, rg, rg_stroke, text_width, win_ansi};
/// The label and colour of a standard rubber stamp name (ISO 32000-2 Table 184), for a stamp
/// another program wrote without an appearance. Names are matched byte for byte, as PDF names
diff --git a/crates/annot/src/create.rs b/crates/annot/src/create.rs
index bedd1c6f1..a6db5b940 100644
--- a/crates/annot/src/create.rs
+++ b/crates/annot/src/create.rs
@@ -1,8 +1,10 @@
use super::draw::draw_appearance;
use super::lookup::{annot_dict, annot_ref, annots, fill_sign_shape, page_ref, set_annots};
use super::modify::{n, rich_text};
-use super::types::{FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, Rgb, Shape, StampGroup, Style};
-use super::*;
+use super::types::{
+ FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, OverlayLook, Rgb, Shape, StampGroup, Style,
+};
+use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance};
pub(crate) fn num_array(v: &[f64]) -> Object {
Object::Array(v.iter().map(|x| Object::Real(*x)).collect())
@@ -203,16 +205,12 @@ pub fn callout_attach(rect: [f64; 4], knee: [f64; 2]) -> [f64; 2] {
pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> Result<usize, AnnotError> {
let page = page_ref(doc, new.page)?;
let style = &new.style;
- if !finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite() {
- return Err(AnnotError::Invalid("invalid style".into()));
- }
+ validate_style(style)?;
let rect = rect_for(&new.shape, style)?;
let mut d = base_dict(new.shape.subtype(), rect, page, &new.contents, &new.author, meta);
d.set(b"Subj".to_vec(), PdfString::text(subject(&new.shape)));
let opacity = style.opacity.clamp(0.0, 1.0);
- if opacity < 1.0 {
- d.set(b"CA".to_vec(), Object::Real(opacity));
- }
+ set_non_opaque_style(&mut d, opacity);
let border = |d: &mut Dict| {
let mut bs = Dict::new();
bs.set(b"W".to_vec(), Object::Real(style.width.max(0.0)));
@@ -232,24 +230,7 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
d.set(b"C".to_vec(), rgb(style.color));
d.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
}
- Shape::Redact { quads, overlay, look } => {
- d.set(b"C".to_vec(), rgb(style.color));
- d.set(b"IC".to_vec(), rgb(style.fill.unwrap_or([0.0, 0.0, 0.0])));
- d.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
- if !overlay.is_empty() {
- d.set(b"OverlayText".to_vec(), PdfString::text(overlay));
- let [r, g, b] = look.color.map(|x| x.clamp(0.0, 1.0));
- let size = if look.size > 0.0 { look.size.min(400.0) } else { 0.0 };
- d.set(
- b"DA".to_vec(),
- PdfString::literal(format!("{} {} {} rg /{} {} Tf", n(r), n(g), n(b), look.font.resource(), n(size)).into_bytes()),
- );
- d.set(b"Q".to_vec(), Object::Int(look.align.min(2) as i64));
- if look.repeat {
- d.set(b"Repeat".to_vec(), Object::Bool(true));
- }
- }
- }
+ Shape::Redact { quads, overlay, look } => set_redaction_properties(&mut d, style, quads, overlay, look),
Shape::Rectangle { .. } | Shape::Oval { .. } => {
d.set(b"C".to_vec(), rgb(style.color));
if let Some(f) = style.fill {
@@ -426,22 +407,55 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
let mut list = annots(doc, page);
let index = list.len();
list.push(Object::Ref(r));
- if let Some(pr) = popup {
- let mut p = Dict::new();
- p.set(b"Type".to_vec(), Object::name("Annot"));
- p.set(b"Subtype".to_vec(), Object::name("Popup"));
- p.set(b"Rect".to_vec(), num_array(&pr));
- p.set(b"Parent".to_vec(), Object::Ref(r));
- p.set(b"Open".to_vec(), Object::Bool(false));
- p.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
- let pref = doc.add(Object::Dict(p));
- doc.update_dict(r, |d| d.set(b"Popup".to_vec(), Object::Ref(pref)))?;
- list.push(Object::Ref(pref));
- }
+ add_popup(doc, r, popup, &mut list)?;
set_annots(doc, page, list)?;
Ok(index)
}
+fn validate_style(style: &Style) -> Result<(), AnnotError> {
+ if !finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite() {
+ return Err(AnnotError::Invalid("invalid style".into()));
+ }
+ Ok(())
+}
+
+fn set_redaction_properties(dict: &mut Dict, style: &Style, quads: &[[f64; 8]], overlay: &str, look: &OverlayLook) {
+ dict.set(b"C".to_vec(), rgb(style.color));
+ dict.set(b"IC".to_vec(), rgb(style.fill.unwrap_or([0.0, 0.0, 0.0])));
+ dict.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
+ if !overlay.is_empty() {
+ dict.set(b"OverlayText".to_vec(), PdfString::text(overlay));
+ let [r, g, b] = look.color.map(|x| x.clamp(0.0, 1.0));
+ let size = if look.size > 0.0 { look.size.min(400.0) } else { 0.0 };
+ dict.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /{} {} Tf", n(r), n(g), n(b), look.font.resource(), n(size)).into_bytes()));
+ dict.set(b"Q".to_vec(), Object::Int(look.align.min(2) as i64));
+ if look.repeat {
+ dict.set(b"Repeat".to_vec(), Object::Bool(true));
+ }
+ }
+}
+
+fn set_non_opaque_style(dict: &mut Dict, opacity: f64) {
+ if opacity < 1.0 {
+ dict.set(b"CA".to_vec(), Object::Real(opacity));
+ }
+}
+
+fn add_popup(doc: &mut Document, parent: ObjRef, rect: Option<[f64; 4]>, annots: &mut Vec<Object>) -> Result<(), AnnotError> {
+ let Some(rect) = rect else { return Ok(()) };
+ let mut popup = Dict::new();
+ popup.set(b"Type".to_vec(), Object::name("Annot"));
+ popup.set(b"Subtype".to_vec(), Object::name("Popup"));
+ popup.set(b"Rect".to_vec(), num_array(&rect));
+ popup.set(b"Parent".to_vec(), Object::Ref(parent));
+ popup.set(b"Open".to_vec(), Object::Bool(false));
+ popup.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
+ let popup_ref = doc.add(Object::Dict(popup));
+ doc.update_dict(parent, |dict| dict.set(b"Popup".to_vec(), Object::Ref(popup_ref)))?;
+ annots.push(Object::Ref(popup_ref));
+ Ok(())
+}
+
/// Counterrotate a newly placed picture stamp's appearance into displayed-page axes.
/// The picture may be an image or a PDF page. The normal appearance's transformed bounding
/// box is fitted to `/Rect` by PDF viewers.
diff --git a/crates/annot/src/draw.rs b/crates/annot/src/draw.rs
index 189845441..5e698332d 100644
--- a/crates/annot/src/draw.rs
+++ b/crates/annot/src/draw.rs
@@ -2,7 +2,7 @@ use super::create::{finite, num_array};
use super::lookup::{annot_dict, annots, page_refs};
use super::modify::refuse_foreign_text;
use super::types::NOTE_SIZE;
-use super::*;
+use super::{AnnotError, Dict, Document, ObjRef, Object, Stream, appearance};
/// (Re)generate `/AP /N` for the annotation `r` from its dictionary, for an edit that keeps its
/// text (a restyle, a new size or colour).
diff --git a/crates/annot/src/info.rs b/crates/annot/src/info.rs
index bea14d9ee..b56e0de20 100644
--- a/crates/annot/src/info.rs
+++ b/crates/annot/src/info.rs
@@ -3,7 +3,7 @@ use super::draw::set_appearance;
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, drawn_upright, is_fill_sign, page_ref, page_refs};
use super::modify::{fillable, touch, unlocked};
use super::types::{FLAG_LOCKED, LineEnding, Meta, NoteIcon, Rgb};
-use super::*;
+use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance};
// ── reading ─────────────────────────────────────────────────────────────────────────────────
diff --git a/crates/annot/src/lookup.rs b/crates/annot/src/lookup.rs
index 00ce23c37..c81ec78ef 100644
--- a/crates/annot/src/lookup.rs
+++ b/crates/annot/src/lookup.rs
@@ -1,6 +1,6 @@
use super::info::text_value;
use super::types::{FLAG_HIDDEN, FLAG_NO_ROTATE, FLAG_NO_VIEW, Shape};
-use super::*;
+use super::{AnnotError, Dict, Document, ObjRef, Object, appearance};
// ── pages and /Annots ───────────────────────────────────────────────────────────────────────
diff --git a/crates/annot/src/modify.rs b/crates/annot/src/modify.rs
index 992b3d0c5..7872a6c81 100644
--- a/crates/annot/src/modify.rs
+++ b/crates/annot/src/modify.rs
@@ -7,7 +7,7 @@ use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, page_ref, s
use super::types::{
FLAG_HIDDEN, FLAG_LOCKED, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NewAnnotation, ReviewState, Rgb, Shape, Style,
};
-use super::*;
+use super::{AnnotError, Dict, Document, HashMap, HashSet, ObjRef, Object, PdfString, appearance};
/// A comment another program drew, whose text the standard fonts can't draw. Redrawing it would
/// replace those characters with `?`, so the edit is refused before the dictionary changes.
diff --git a/crates/annot/src/types.rs b/crates/annot/src/types.rs
index 632e990fe..40ed744df 100644
--- a/crates/annot/src/types.rs
+++ b/crates/annot/src/types.rs
@@ -1,5 +1,5 @@
use super::create::normalize;
-use super::*;
+use super::{ObjRef, appearance};
pub type Rgb = [f64; 3];