mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-23 10:51:11 +01:00
pdf: scope synthesized text groups to EPS bridge
This commit is contained in:
1 parent
627d829427
commit
ce6f67566e
6 files changed
+47
-50
No files matched your search
+3
-36
@@ -19,8 +19,6 @@ enum Kind {
|
||||
|
||||
pub(crate) struct Builder {
|
||||
stack: Vec<(Group, Kind)>,
|
||||
/// Active ActualText labels; these follow marked content, not graphics-state scopes.
|
||||
text: Vec<String>,
|
||||
/// Which of the finished top-level nodes are optional-content layers.
|
||||
pub top_layers: Vec<bool>,
|
||||
pub skipped: Vec<String>,
|
||||
@@ -36,7 +34,7 @@ pub(crate) fn group(name: &str) -> Group {
|
||||
|
||||
impl Builder {
|
||||
pub fn new() -> Builder {
|
||||
Builder { stack: vec![(group("page"), Kind::Plain)], text: vec![], top_layers: vec![], skipped: vec![], shapes: 0, base: 0 }
|
||||
Builder { stack: vec![(group("page"), Kind::Plain)], top_layers: vec![], skipped: vec![], shapes: 0, base: 0 }
|
||||
}
|
||||
|
||||
/// A builder for content that will be placed inside this one's open groups and `wrap` more
|
||||
@@ -70,37 +68,6 @@ impl Builder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep marked text separate from the graphics-state group stack. Each painted node is
|
||||
/// labeled at insertion so a clip, blend or mask can outlive its marked-content sequence.
|
||||
pub fn begin_text(&mut self, name: String) -> bool {
|
||||
if !self.has_room(self.text.len().saturating_add(1)) {
|
||||
self.skip("group nesting limit");
|
||||
return false;
|
||||
}
|
||||
self.text.push(name);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn end_text(&mut self) {
|
||||
self.text.pop();
|
||||
}
|
||||
|
||||
fn add_painted(&mut self, mut node: Node) {
|
||||
if !self.has_room(self.text.len()) {
|
||||
self.skip("group nesting limit");
|
||||
self.add(node, false);
|
||||
return;
|
||||
}
|
||||
for name in self.text.iter().rev() {
|
||||
let mut g = group(name);
|
||||
// Logical labels must not isolate the painting from its backdrop.
|
||||
g.isolated = false;
|
||||
g.children.push(node);
|
||||
node = Node::Group(g);
|
||||
}
|
||||
self.add(node, false);
|
||||
}
|
||||
|
||||
/// Close every group opened above `depth`.
|
||||
pub fn close_to(&mut self, depth: usize) {
|
||||
while self.stack.len() > depth.max(1) {
|
||||
@@ -144,7 +111,7 @@ impl Builder {
|
||||
|
||||
/// Add a finished node (an image, pattern tiles).
|
||||
pub fn push(&mut self, n: Node) {
|
||||
self.add_painted(n);
|
||||
self.add(n, false);
|
||||
}
|
||||
|
||||
pub fn fill_stroke(&mut self, path: BezPath, transform: Affine, fill: Option<(Paint, f64, FillRule)>, stroke: Option<Stroke>) {
|
||||
@@ -161,7 +128,7 @@ impl Builder {
|
||||
None => (None, 1.0, FillRule::NonZero),
|
||||
};
|
||||
let s = Shape { name: name.into(), geom: Geom::Path(path), transform, fill: f, fill_opacity: fo, fill_rule: rule, stroke, opacity: 1.0 };
|
||||
self.add_painted(Node::Shape(s));
|
||||
self.add(Node::Shape(s), false);
|
||||
}
|
||||
|
||||
/// The finished top-level nodes and their layer flags.
|
||||
|
||||
@@ -122,9 +122,9 @@ pub enum Framing {
|
||||
/// [`parse_page`] with the page framed as `framing` says (EPS files are their bounding box).
|
||||
pub fn parse_page_framed(bytes: &[u8], index: usize, framing: Framing) -> Result<Doc, Error> {
|
||||
match sniff(bytes) {
|
||||
Some(Format::Pdf) => parse_pdf(bytes, index, framing),
|
||||
Some(Format::Pdf) => parse_pdf(bytes, index, framing, false),
|
||||
Some(Format::Eps) => parse_eps(bytes),
|
||||
Some(Format::VectorCraft) => parse_pdf(&carried_pdf(bytes)?, index, framing),
|
||||
Some(Format::VectorCraft) => parse_pdf(&carried_pdf(bytes)?, index, framing, false),
|
||||
None => Err(Error::NotVector),
|
||||
}
|
||||
}
|
||||
@@ -200,7 +200,7 @@ fn finish(nodes: Vec<Node>, flags: Vec<bool>, skipped: Vec<String>, width: f64,
|
||||
}
|
||||
|
||||
/// Page `index` of a PDF framed as `framing` says, as a document in points (y down).
|
||||
fn parse_pdf(bytes: &[u8], index: usize, framing: Framing) -> Result<Doc, Error> {
|
||||
fn parse_pdf(bytes: &[u8], index: usize, framing: Framing, eps_text: bool) -> Result<Doc, Error> {
|
||||
let file = object::File::parse(bytes)?;
|
||||
let pages = page::pages(&file);
|
||||
if pages.is_empty() {
|
||||
@@ -221,7 +221,7 @@ fn parse_pdf(bytes: &[u8], index: usize, framing: Framing) -> Result<Doc, Error>
|
||||
_ => (Affine::new([1.0, 0.0, 0.0, -1.0, -x0, y1]), w, h),
|
||||
};
|
||||
let content = page::page_content(&file, pg);
|
||||
let mut it = page::Interp::new(&file, pg.bbox);
|
||||
let mut it = page::Interp::new(&file, pg.bbox, eps_text);
|
||||
it.b.skipped.extend(file.repairs.iter().cloned());
|
||||
it.run(&content, &pg.resources, Affine::IDENTITY, 0);
|
||||
let (nodes, flags, skipped) = it.b.finish();
|
||||
@@ -267,7 +267,7 @@ fn parse_eps(bytes: &[u8]) -> Result<Doc, Error> {
|
||||
"not PostScript" | "the EPS has no bounding box" => Error::NoBoundingBox,
|
||||
_ => Error::Read(message),
|
||||
})?;
|
||||
let mut doc = parse_pdf(&converted.pdf, 0, Framing::Placed)?;
|
||||
let mut doc = parse_pdf(&converted.pdf, 0, Framing::Placed, true)?;
|
||||
for skipped in &mut doc.skipped {
|
||||
if skipped == "content (path limit)" {
|
||||
*skipped = "PostScript (path limit)".to_string();
|
||||
|
||||
@@ -210,6 +210,8 @@ pub(crate) struct Interp<'a> {
|
||||
start: Option<Point>,
|
||||
pending_clip: Option<FillRule>,
|
||||
marked: Vec<Marked>,
|
||||
/// The shared PostScript bridge emits ActualText to label outlined shows.
|
||||
eps_text: bool,
|
||||
/// The page box in default user space (for `sh`).
|
||||
page_box: [f64; 4],
|
||||
budget: usize,
|
||||
@@ -231,7 +233,6 @@ fn affine(v: &[f64]) -> Affine {
|
||||
enum Marked {
|
||||
Other,
|
||||
Layer(usize),
|
||||
Text(bool),
|
||||
}
|
||||
|
||||
/// The most tiles one tiling-pattern fill draws.
|
||||
@@ -244,7 +245,7 @@ enum TextItem {
|
||||
}
|
||||
|
||||
impl<'a> Interp<'a> {
|
||||
pub fn new(file: &'a File, page_box: [f64; 4]) -> Self {
|
||||
pub fn new(file: &'a File, page_box: [f64; 4], eps_text: bool) -> Self {
|
||||
Interp {
|
||||
file,
|
||||
b: Builder::new(),
|
||||
@@ -255,6 +256,7 @@ impl<'a> Interp<'a> {
|
||||
start: None,
|
||||
pending_clip: None,
|
||||
marked: vec![],
|
||||
eps_text,
|
||||
page_box,
|
||||
budget: 20_000_000,
|
||||
tm: Affine::IDENTITY,
|
||||
@@ -506,7 +508,7 @@ impl<'a> Interp<'a> {
|
||||
_ => None,
|
||||
};
|
||||
let actual_text = match (args.first().and_then(Obj::name), args.get(1)) {
|
||||
(Some("Span"), Some(Obj::Dict(props))) => props.get("ActualText").and_then(|v| match self.file.resolve(v) {
|
||||
(Some("Span"), Some(Obj::Dict(props))) if self.eps_text => props.get("ActualText").and_then(|v| match self.file.resolve(v) {
|
||||
Obj::Str(bytes) => Some(crate::color::text_string(bytes)),
|
||||
_ => None,
|
||||
}),
|
||||
@@ -518,15 +520,14 @@ impl<'a> Interp<'a> {
|
||||
self.b.open(&name, true);
|
||||
}
|
||||
(None, Some(text)) => {
|
||||
let opened = self.b.begin_text(format!("Text: {text}"));
|
||||
self.marked.push(Marked::Text(opened));
|
||||
self.marked.push(Marked::Layer(self.b.depth()));
|
||||
self.b.open(&format!("Text: {text}"), false);
|
||||
}
|
||||
(None, None) => self.marked.push(Marked::Other),
|
||||
}
|
||||
}
|
||||
"EMC" => match self.marked.pop() {
|
||||
Some(Marked::Layer(d)) => self.close_to(d),
|
||||
Some(Marked::Text(true)) => self.b.end_text(),
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
|
||||
@@ -92,7 +92,7 @@ fn eps_semibold_and_demi_names_select_semibold_fallback() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_actual_text_is_exposed_as_a_logical_group() {
|
||||
fn generic_pdf_actual_text_keeps_paint_without_a_logical_group() {
|
||||
let content = "/Span << /ActualText (Logical text) >> BDC\n1 0 0 rg 10 10 20 20 re f\nEMC";
|
||||
let objs = vec![
|
||||
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None),
|
||||
@@ -103,7 +103,7 @@ fn pdf_actual_text_is_exposed_as_a_logical_group() {
|
||||
|
||||
let doc = parse(&pdf(&objs, 1)).unwrap();
|
||||
|
||||
assert_eq!(shape_names(&doc), vec!["Text: Logical text"]);
|
||||
assert_eq!(shape_names(&doc), vec!["Path"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -103,7 +103,7 @@ fn actual_text_does_not_end_blend_clip_or_soft_mask() {
|
||||
assert!(near(a.get(x, 50), b.get(x, 50)), "x={x}: {:?} != {:?}", a.get(x, 50), b.get(x, 50));
|
||||
}
|
||||
let names = crate::tests::shape_names(&marked);
|
||||
assert_eq!(names.iter().filter(|name| name.as_str() == "Text: inside").count(), 1);
|
||||
assert!(!names.iter().any(|name| name == "Text: inside"), "ordinary PDF marked text is not imported as a group");
|
||||
assert!(names.iter().any(|name| name == "Path"), "marks after EMC are not labeled: {names:?}");
|
||||
assert!(near(a.get(75, 50), [0.5, 1.0, 0.0, 1.0]), "multiply and mask remain active: {:?}", a.get(75, 50));
|
||||
assert!(near(a.get(160, 50), [1.0, 1.0, 0.0, 1.0]), "clip remains active: {:?}", a.get(160, 50));
|
||||
|
||||
@@ -74,6 +74,35 @@ fn eps_exec_of_executable_names_stops_at_the_call_depth() {
|
||||
assert!(doc.skipped.iter().any(|s| s.contains("recursion limit")), "{:?}", doc.skipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_clipped_show_keeps_one_text_label_and_clip_afterwards() {
|
||||
let doc = eps(b"0 0 50 50 rectclip /Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show 1 0 0 setrgbcolor 0 0 100 100 rectfill");
|
||||
let names = shape_names(&doc);
|
||||
assert_eq!(names.iter().filter(|name| name.as_str() == "Text: Hi").count(), 1, "{names:?}");
|
||||
let img = render(&doc);
|
||||
assert!(img.get(25, 75)[0] > 0.99);
|
||||
assert_eq!(img.get(75, 75)[3], 0.0, "the clip outlives the show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_long_show_stores_one_label_for_many_painted_glyphs() {
|
||||
let label = "H".repeat(1024);
|
||||
let doc = eps(format!("/Helvetica findfont 2 scalefont setfont 1 10 moveto ({label}) show").as_bytes());
|
||||
let names = shape_names(&doc);
|
||||
assert_eq!(names, vec![format!("Text: {label}")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_type3_glyph_paints_with_its_own_clip_without_synthetic_text_label() {
|
||||
let doc = eps(b"/T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 1000] def /Encoding 256 array def 0 1 255 { Encoding exch /.notdef put } for Encoding 65 /A put /BuildChar { pop pop 1000 0 0 0 1000 1000 setcachedevice gsave 0 0 500 1000 rectclip 1 0 0 setrgbcolor 0 0 1000 1000 rectfill grestore 0 0 1 setrgbcolor 500 0 500 1000 rectfill } def end def /T3 T3 definefont pop /T3 findfont 20 scalefont setfont 10 10 moveto (AA) show");
|
||||
assert!(!shape_names(&doc).iter().any(|name| name.starts_with("Text: ")));
|
||||
let img = render(&doc);
|
||||
assert!(img.get(15, 80)[0] > 0.99, "first glyph clipped red half");
|
||||
assert!(img.get(25, 80)[2] > 0.99, "first glyph blue half");
|
||||
assert!(img.get(35, 80)[0] > 0.99, "second glyph clipped red half");
|
||||
assert!(img.get(45, 80)[2] > 0.99, "second glyph blue half");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_text_with_bundled_fonts_and_show_variants() {
|
||||
// Not embedded: drawn with the bundled stand-in, like the same text in a PDF.
|
||||
|
||||
Reference in new issue
Block a user