mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-01 02:36:02 +01:00
4315 lines
227 KiB
Rust
4315 lines
227 KiB
Rust
use super::*;
|
||
|
||
fn em_box(text: &str, x0: f32, y0: f32, x1: f32, y1: f32) -> TextGlyph {
|
||
TextGlyph { text: text.into(), rect: [x0, y0, x1, y1], quad: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], direction: [1.0, 0.0] }
|
||
}
|
||
|
||
#[test]
|
||
fn subscript_stays_in_its_word() {
|
||
// "CO2-E": an 8.1 pt "CO" and "-E", with a 4.7 pt "2" drawn 2.7 pt lower (#3174).
|
||
let glyphs = vec![
|
||
em_box("C", 0.0, 92.5, 5.0, 100.6),
|
||
em_box("O", 5.0, 92.5, 11.0, 100.6),
|
||
em_box("2", 11.0, 97.9, 13.5, 102.6),
|
||
em_box("-", 13.5, 92.5, 16.0, 100.6),
|
||
em_box("E", 16.0, 92.5, 21.0, 100.6),
|
||
];
|
||
assert_eq!(layout(glyphs).plain_text(), "CO2-E");
|
||
}
|
||
|
||
#[test]
|
||
fn identity_v_columns_are_searchable_in_reading_order() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
for encoding in ["Identity-V", "UniJIS-UCS2-V"] {
|
||
let mut doc = Document::with_version("1.7");
|
||
let cmap = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /TestUnicode def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 5 beginbfchar <0001> <65E5> <0002> <672C> <0003> <8A9E> <0004> <6587> <0005> <7AE0> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
let cmap = if encoding == "Identity-V" {
|
||
cmap.to_vec()
|
||
} else {
|
||
let mut mapping = String::from_utf8(cmap.to_vec()).unwrap();
|
||
for (code, unicode) in [("0001", "65E5"), ("0002", "672C"), ("0003", "8A9E"), ("0004", "6587"), ("0005", "7AE0")] {
|
||
mapping = mapping.replace(&format!("<{code}> <{unicode}>"), &format!("<{unicode}> <{unicode}>"));
|
||
}
|
||
mapping.into_bytes()
|
||
};
|
||
let unicode = doc.add_object(Stream::new(dictionary! {}, cmap));
|
||
let cid = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "CIDFontType2", "BaseFont" => "TestVertical",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 },
|
||
"DW" => 1000, "DW2" => vec![Object::Integer(880), Object::Integer(-1000)], "CIDToGIDMap" => "Identity"
|
||
});
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "TestVertical", "Encoding" => encoding, "DescendantFonts" => vec![Object::Reference(cid)], "ToUnicode" => unicode });
|
||
let horizontal = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "TestVertical", "Encoding" => "Identity-H", "DescendantFonts" => vec![Object::Reference(cid)], "ToUnicode" => unicode });
|
||
let (first, second) = if encoding == "Identity-V" { ("000100020003", "00040005") } else { ("65E5672C8A9E", "65877AE0") };
|
||
let operators =
|
||
format!("BT /H1 20 Tf 1 0 0 1 40 280 Tm <{first}> Tj /F1 20 Tf 1 0 0 1 200 250 Tm <{first}> Tj 1 0 0 1 170 250 Tm <{second}> Tj ET");
|
||
let content = doc.add_object(Stream::new(dictionary! {}, operators.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font, "H1" => horizontal}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), "日本語\n日本語\n文章");
|
||
assert_eq!(text.find("日本語"), vec![0..3, 3..6]);
|
||
assert_eq!(text.find("文章"), vec![6..8]);
|
||
let rects = text.line_rects(3..6);
|
||
assert_eq!(rects.len(), 1);
|
||
assert!(rects[0][3] - rects[0][1] > rects[0][2] - rects[0][0], "a vertical search highlight: {rects:?}");
|
||
assert!(text.glyphs[3].rect[0] > text.glyphs[6].rect[0], "columns read right to left in page view coordinates");
|
||
}
|
||
}
|
||
|
||
/// WSCAD writes `/ToUnicode /Identity-H`, a name rather than a CMap stream, on Type 0 fonts
|
||
/// whose two-byte codes are UTF-16 code units. The codes read as that Unicode text (as in
|
||
/// Acrobat), so the page's text can be selected and found; before, it had none. Controls (here a
|
||
/// DEL and a C1 control at the line ends) are not text.
|
||
#[test]
|
||
fn identity_to_unicode_names_give_text() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
for name in ["Identity-H", "Identity-V"] {
|
||
let mut doc = Document::with_version("1.4");
|
||
let cid = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "CIDFontType2", "BaseFont" => "RobotoMono-Regular",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 },
|
||
"DW" => 600, "CIDToGIDMap" => "Identity"
|
||
});
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "RobotoMono-Regular", "Encoding" => "Identity-H", "DescendantFonts" => vec![Object::Reference(cid)], "ToUnicode" => name });
|
||
let operators = "BT /F1 12 Tf 1 0 0 1 20 250 Tm <004400650063006B0062006C006100740074007F> Tj 1 0 0 1 20 200 Tm <005A00FC0072006900630068002020AC0085> Tj ET";
|
||
let content = doc.add_object(Stream::new(dictionary! {}, operators.as_bytes().to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), "Deckblatt\nZürich €", "{name}");
|
||
assert_eq!(text.find("zürich"), vec![9..15], "{name}: glyphs 9 to 14");
|
||
}
|
||
}
|
||
|
||
/// One page per text matrix, each showing `codes` in Helvetica whose `/ToUnicode` maps the
|
||
/// codes in `unicode` (a `bfchar` body) to several characters.
|
||
fn ligature_pages(unicode: &str, codes: &str, matrices: &[&str]) -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let cmap = format!(
|
||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /TestLigatures def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange {unicode} endcmap CMapName currentdict /CMap defineresource pop end end"
|
||
);
|
||
let to_unicode = doc.add_object(Stream::new(dictionary! {}, cmap.into_bytes()));
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "ToUnicode" => to_unicode });
|
||
let pages = doc.new_object_id();
|
||
let mut kids = Vec::new();
|
||
for m in matrices {
|
||
let content = doc.add_object(Stream::new(dictionary! {}, format!("BT /F1 20 Tf {m} Tm ({codes}) Tj ET").into_bytes()));
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
kids.push(Object::Reference(page));
|
||
}
|
||
let count = kids.len() as i64;
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
#[test]
|
||
fn a_ligature_is_one_glyph_in_every_writing_direction() {
|
||
// "o", one glyph for "ffi", "c", "e": "office", turned 0°, 90°, 180° and 270°. The same
|
||
// codes without the ligature mapping ("oWce") are the control for the glyph box.
|
||
let turns = ["1 0 0 1 100 150", "0 1 -1 0 150 100", "-1 0 0 -1 200 150", "0 -1 1 0 150 200"];
|
||
let ligature = ligature_pages("1 beginbfchar <57> <006600660069> endbfchar", "oWce", &turns);
|
||
let control = ligature_pages("", "oWce", &turns);
|
||
for (page, turn) in turns.iter().enumerate() {
|
||
let text = extract_page(&ligature, page, &InterpreterSettings::default()).unwrap();
|
||
let plain = extract_page(&control, page, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(plain.plain_text(), "oWce", "Tm {turn}");
|
||
assert_eq!(text.plain_text(), "office", "Tm {turn}");
|
||
assert_eq!(text.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), ["o", "ffi", "c", "e"], "Tm {turn}");
|
||
assert_eq!(text.glyphs[1].rect, plain.glyphs[1].rect, "the painted glyph's box, Tm {turn}");
|
||
assert_eq!(text.find("ffi"), vec![1..2], "Tm {turn}");
|
||
assert_eq!(text.find("of"), vec![0..2], "a match ending inside the ligature covers it, Tm {turn}");
|
||
assert_eq!(text.line_rects(0..4).len(), 1, "one line, Tm {turn}");
|
||
}
|
||
}
|
||
|
||
/// One page per content stream, in Helvetica (`/F1`), with `/P1` in the resources'
|
||
/// `/Properties` naming the `/ActualText` "fi".
|
||
fn marked_pages(contents: &[&str]) -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let pages = doc.new_object_id();
|
||
let mut kids = Vec::new();
|
||
for c in contents {
|
||
let content = doc.add_object(Stream::new(dictionary! {}, c.as_bytes().to_vec()));
|
||
let resources = dictionary! {
|
||
"Font" => dictionary! {"F1" => font},
|
||
"Properties" => dictionary! {"P1" => dictionary! {"ActualText" => Object::string_literal("fi")}},
|
||
};
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => resources, "Contents" => content });
|
||
kids.push(Object::Reference(page));
|
||
}
|
||
let count = kids.len() as i64;
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
fn marked_text(pdf: &Pdf, page: usize) -> PageText {
|
||
extract_page(pdf, page, &InterpreterSettings::default()).unwrap()
|
||
}
|
||
|
||
#[test]
|
||
fn redraws_of_a_long_replacement_share_a_text_budget() {
|
||
let long = "0041".repeat(32 * 1024);
|
||
let redraws = 200;
|
||
let content = format!(
|
||
"BT /F1 20 Tf 1 0 0 1 100 150 Tm /Span <</ActualText <FEFF{long}>>> BDC (x) Tj EMC {} ET",
|
||
"1 0 0 1 100 150 Tm (x) Tj ".repeat(redraws)
|
||
);
|
||
let pdf = marked_pages(&[&content]);
|
||
REDRAW_TEXT_BYTES.with(|c| c.set(0));
|
||
let text = marked_text(&pdf, 0);
|
||
let given = REDRAW_TEXT_BYTES.with(|c| c.get());
|
||
assert!(given <= MAX_REDRAW_TEXT, "{given} bytes of replacement text given to {redraws} redraws");
|
||
assert!(text.plain_text().starts_with("AAAA"));
|
||
// A short replacement still covers its redraw.
|
||
let pdf = marked_pages(&["BT /F1 20 Tf 1 0 0 1 100 150 Tm /Span <</ActualText (fi)>> BDC (x) Tj EMC 1 0 0 1 100 150 Tm (x) Tj ET"]);
|
||
REDRAW_TEXT_BYTES.with(|c| c.set(0));
|
||
assert_eq!(marked_text(&pdf, 0).plain_text(), "fi");
|
||
assert_eq!(REDRAW_TEXT_BYTES.with(|c| c.get()), 2);
|
||
}
|
||
|
||
#[test]
|
||
fn text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei() {
|
||
// Everyday content both ways: a string with a byte above 0x7F, and a later word holding
|
||
// a capital "EI". The end-of-data look-ahead used to read the string's bytes as image
|
||
// data, so the image swallowed the rest of the page. The image is filtered, so its
|
||
// length isn't known up front and the look-ahead decides.
|
||
let pdf = marked_pages(&[
|
||
"BI /W 1 /H 1 /BPC 8 /CS /DeviceGray /F /AHx ID 00> EI BT /F1 20 Tf 1 0 0 1 20 200 Tm (Gr\u{fc}\u{df}e) Tj 1 0 0 1 20 150 Tm (EINGANG) Tj ET",
|
||
]);
|
||
|
||
assert!(marked_text(&pdf, 0).plain_text().contains("EINGANG"), "the text after the inline image was not extracted");
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_replaces_the_glyphs_it_marks_in_every_writing_direction() {
|
||
// Chrome marks each shaped Thai cluster this way: "น้ำ" (U+0E19 U+0E49 U+0E33) here stands
|
||
// for the two glyphs "xy", between "a" and "b". The same codes unmarked are the control.
|
||
let turns = ["1 0 0 1 100 150", "0 1 -1 0 150 100", "-1 0 0 -1 200 150", "0 -1 1 0 150 200"];
|
||
let marked: Vec<String> =
|
||
turns.iter().map(|m| format!("BT /F1 20 Tf {m} Tm (a) Tj /Span <</ActualText <FEFF0E190E490E33>>> BDC (xy) Tj EMC (b) Tj ET")).collect();
|
||
let plain: Vec<String> = turns.iter().map(|m| format!("BT /F1 20 Tf {m} Tm (axyb) Tj ET")).collect();
|
||
let marked = marked_pages(&marked.iter().map(String::as_str).collect::<Vec<_>>());
|
||
let plain = marked_pages(&plain.iter().map(String::as_str).collect::<Vec<_>>());
|
||
for (page, turn) in turns.iter().enumerate() {
|
||
let text = marked_text(&marked, page);
|
||
let control = marked_text(&plain, page);
|
||
assert_eq!(control.plain_text(), "axyb", "Tm {turn}");
|
||
assert_eq!(text.plain_text(), "aน้ำb", "Tm {turn}");
|
||
assert_eq!(text.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), ["a", "น้ำ", "b"], "Tm {turn}");
|
||
assert_eq!(text.find("น้ำ"), vec![1..2], "Tm {turn}");
|
||
assert_eq!(text.line_rects(0..3).len(), 1, "one line, Tm {turn}");
|
||
// The replacement's box is the union of the boxes of the glyphs it replaces.
|
||
let (x, y) = (&control.glyphs[1].rect, &control.glyphs[2].rect);
|
||
let union = [x[0].min(y[0]), x[1].min(y[1]), x[2].max(y[2]), x[3].max(y[3])];
|
||
for (got, want) in text.glyphs[1].rect.iter().zip(union) {
|
||
assert!((got - want).abs() < 0.01, "box {:?} ≠ {union:?}, Tm {turn}", text.glyphs[1].rect);
|
||
}
|
||
assert_eq!(text.glyphs[1].direction, control.glyphs[1].direction, "Tm {turn}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn redraw_dedupe_work_is_bounded_on_hostile_pages() {
|
||
// 100,000 replacements and 100,000 unmarked glyphs that never match, all at one spot:
|
||
// unbounded, every replacement would compare every glyph (10^10 comparisons).
|
||
const N: usize = 100_000;
|
||
let glyph = |text: &str| {
|
||
let quad = [[100.0, 110.0], [110.0, 110.0], [110.0, 100.0], [100.0, 100.0]];
|
||
(0, [1.0, 0.0], TextGlyph { text: text.into(), rect: [100.0, 100.0, 110.0, 110.0], quad, direction: [1.0, 0.0] })
|
||
};
|
||
let mut dev = TextDevice::new();
|
||
// A genuine redraw first: it is still deduplicated within the budget.
|
||
dev.glyphs.push(glyph("fi"));
|
||
dev.glyphs.push(glyph("x"));
|
||
dev.replaced.push(Replaced { at: Some(0), text: "fi".into(), originals: vec![("x".into(), [100.0, 100.0, 110.0, 110.0])] });
|
||
dev.glyphs.extend((0..N).map(|_| glyph("y")));
|
||
for _ in 0..N {
|
||
dev.glyphs.push(glyph("z"));
|
||
let at = dev.glyphs.len() - 1;
|
||
dev.replaced.push(Replaced { at: Some(at), text: "z".into(), originals: vec![("q".into(), [100.0, 100.0, 110.0, 110.0])] });
|
||
}
|
||
let started = std::time::Instant::now();
|
||
dev.finish();
|
||
assert!(started.elapsed() < std::time::Duration::from_secs(30), "took {:?}", started.elapsed());
|
||
assert_eq!(dev.glyphs.len(), 2 * N + 2, "unmatched glyphs are kept");
|
||
assert_eq!(dev.glyphs[1].2.text, "fi", "the redraw found within the budget takes the replacement");
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_follows_the_pdf_rules_for_marked_content() {
|
||
let pdf = marked_pages(&[
|
||
// Named in the resources' /Properties.
|
||
"BT /F1 20 Tf 1 0 0 1 100 150 Tm (o) Tj /Span /P1 BDC (W) Tj EMC (ce) Tj ET",
|
||
// Nested: the outermost replacement covers everything inside it.
|
||
"BT /F1 20 Tf 1 0 0 1 100 150 Tm /Span <</ActualText (AB)>> BDC /Span <</ActualText (Z)>> BDC (x) Tj EMC (y) Tj EMC ET",
|
||
// Empty: the marked glyphs stand for no text (a soft hyphen at a line break); the gap
|
||
// the hyphen leaves still reads as one.
|
||
"BT /F1 20 Tf 1 0 0 1 100 150 Tm (co) Tj /Span <</ActualText ()>> BDC (-) Tj EMC (op) Tj ET",
|
||
// Across two lines: each glyph keeps its own text, so selection and lines still work.
|
||
"BT /F1 20 Tf 1 0 0 1 100 150 Tm /Span <</ActualText (Q)>> BDC (x) Tj 0 -40 Td (y) Tj EMC ET",
|
||
// Unbalanced: a stray EMC first, and a replacement the page never closes.
|
||
"EMC BT /F1 20 Tf 1 0 0 1 100 150 Tm (a) Tj /Span <</ActualText (fi)>> BDC (xy) Tj ET",
|
||
// Marked content without /ActualText changes nothing.
|
||
"BT /F1 20 Tf 1 0 0 1 100 150 Tm /P <</MCID 0>> BDC (ab) Tj EMC /Artifact BMC (c) Tj EMC ET",
|
||
]);
|
||
let plain: Vec<String> = (0..6).map(|p| marked_text(&pdf, p).plain_text()).collect();
|
||
assert_eq!(plain, ["ofice", "AB", "co op", "x\ny", "afi", "abc"]);
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_over_painted_paths_reads_where_they_are_painted() {
|
||
// Words drawn as outlines (a face that can't be embedded) carry their text in /ActualText
|
||
// (ISO 32000-2 §14.9.4): it reads at the box of the paths it marks, in view space (y down).
|
||
let pdf = marked_pages(&[
|
||
"/Span <</ActualText (valid)>> BDC 100 40 m 160 40 l 160 60 l 100 60 l f EMC",
|
||
// A curve is measured by its control points, as redaction measures it.
|
||
"/Span <</ActualText (arc)>> BDC 100 40 m 100 100 160 100 160 40 c f EMC",
|
||
"BT /F1 20 Tf 1 0 0 1 20 150 Tm (a) Tj ET /Span <</ActualText (b)>> BDC 100 140 60 20 re f EMC BT /F1 20 Tf 1 0 0 1 200 150 Tm (c) Tj ET",
|
||
// Glyphs inside the span keep their own box; the paths beside them don't widen it.
|
||
"/Span <</ActualText (x)>> BDC BT /F1 20 Tf 1 0 0 1 100 150 Tm (y) Tj ET 0 0 300 300 re f EMC",
|
||
// Paths are not text without a replacement, and an empty one stands for nothing.
|
||
"100 140 60 20 re f",
|
||
"/Span <</ActualText ()>> BDC 100 140 60 20 re f EMC",
|
||
]);
|
||
let painted = marked_text(&pdf, 0);
|
||
assert_eq!(painted.plain_text(), "valid");
|
||
assert_eq!(painted.glyphs[0].rect, [100.0, 240.0, 160.0, 260.0]);
|
||
assert_eq!(marked_text(&pdf, 1).glyphs[0].rect, [100.0, 200.0, 160.0, 260.0]);
|
||
let between = marked_text(&pdf, 2);
|
||
assert_eq!(between.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), ["a", "b", "c"]);
|
||
let mixed = marked_text(&pdf, 3);
|
||
assert_eq!(mixed.plain_text(), "x");
|
||
assert!(mixed.glyphs[0].rect[2] - mixed.glyphs[0].rect[0] < 20.0, "{:?}", mixed.glyphs[0].rect);
|
||
for page in 4..6 {
|
||
assert_eq!(marked_text(&pdf, page).plain_text(), "", "page {page}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn the_painted_filter_leaves_out_replacements_that_mark_no_glyph() {
|
||
// A page's own text, without words that only /ActualText names.
|
||
let pdf = marked_pages(&[
|
||
"/Span <</ActualText (valid)>> BDC 100 40 m 160 40 l 160 60 l 100 60 l f EMC",
|
||
"BT /F1 20 Tf 1 0 0 1 20 150 Tm (a) Tj ET /Span <</ActualText (b)>> BDC 100 140 60 20 re f EMC BT /F1 20 Tf 1 0 0 1 200 150 Tm (c) Tj ET",
|
||
]);
|
||
let own = |page| extract_page_filtered(&pdf, page, &InterpreterSettings::default(), TextFilter { painted: true, ..Default::default() });
|
||
assert_eq!(own(0).unwrap().plain_text(), "");
|
||
let between = own(1).unwrap().plain_text();
|
||
assert!(between.contains('a') && between.contains('c') && !between.contains('b'), "the glyphs stay: {between:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_over_paint_reads_only_where_it_shows() {
|
||
let pdf = marked_pages(&[
|
||
// A page-sized fill clipped to a word's box reads at that box.
|
||
"q 100 40 30 20 re W n /Span <</ActualText (c)>> BDC 0 0 300 300 re f EMC Q",
|
||
// Wholly clipped away, it reads nowhere.
|
||
"q 0 0 10 10 re W n /Span <</ActualText (gone)>> BDC 100 40 60 20 re f EMC Q",
|
||
// A clip that ended before the paint no longer cuts it.
|
||
"q 0 0 10 10 re W n Q /Span <</ActualText (back)>> BDC 100 40 60 20 re f EMC",
|
||
]);
|
||
assert_eq!(marked_text(&pdf, 0).glyphs[0].rect, [100.0, 240.0, 130.0, 260.0]);
|
||
assert_eq!(marked_text(&pdf, 1).plain_text(), "");
|
||
assert_eq!(marked_text(&pdf, 2).glyphs[0].rect, [100.0, 240.0, 160.0, 260.0]);
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_over_paint_reads_only_inside_the_crop_box() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let (page, crop) = ([0, 0, 300, 300], [50, 60, 250, 240]);
|
||
let pages = [
|
||
// Wholly outside the crop box, as a glyph there is: it reads nowhere.
|
||
("/Span <</ActualText (below)>> BDC 100 10 60 20 re f EMC", page, crop),
|
||
// Across its left edge: it reads from that edge, as a glyph across it still shows.
|
||
("/Span <</ActualText (edge)>> BDC 20 100 60 20 re f EMC", page, crop),
|
||
// Partly painted outside it: its words may be among what the crop box hides.
|
||
("/Span <</ActualText (part)>> BDC 100 100 60 20 re f 100 10 60 20 re f EMC", page, crop),
|
||
// A glyph the crop takes leaves the replacement no glyph, and the paint can't place it.
|
||
("/Span <</ActualText (split)>> BDC BT /F1 12 Tf 1 0 0 1 100 10 Tm (x) Tj ET 100 100 60 20 re f EMC", page, crop),
|
||
// On a page wide enough to hold them, paint too far apart to be the place of words.
|
||
("/Span <</ActualText (far)>> BDC 100 40 10 10 re f 12100 40 10 10 re f EMC", [0, 0, 14400, 300], [0, 0, 14400, 300]),
|
||
];
|
||
let boxed = |b: [i64; 4]| b.map(Object::Integer).to_vec();
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let parent = doc.new_object_id();
|
||
let mut kids = Vec::new();
|
||
for (ops, media, crop) in pages {
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.as_bytes().to_vec()));
|
||
kids.push(Object::Reference(doc.add_object(dictionary! {
|
||
"Type" => "Page",
|
||
"Parent" => parent,
|
||
"MediaBox" => boxed(media),
|
||
"CropBox" => boxed(crop),
|
||
"Resources" => dictionary! { "Font" => dictionary! { "F1" => font } },
|
||
"Contents" => content,
|
||
})));
|
||
}
|
||
let count = kids.len() as i64;
|
||
doc.objects.insert(parent, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
|
||
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => parent });
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
assert_eq!(marked_text(&pdf, 0).plain_text(), "");
|
||
// View space starts at the crop box's top-left corner.
|
||
assert_eq!(marked_text(&pdf, 1).glyphs[0].rect, [0.0, 120.0, 30.0, 140.0]);
|
||
for page in 2..5 {
|
||
assert_eq!(marked_text(&pdf, page).plain_text(), "", "page {page}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_over_paint_reads_along_the_way_it_is_drawn() {
|
||
// The same quarter turn for a path and for text: the replacement runs the way the text does.
|
||
let pdf = marked_pages(&[
|
||
"q 0 1 -1 0 150 150 cm /Span <</ActualText (turned)>> BDC 0 0 40 10 re f EMC Q",
|
||
"q 0 1 -1 0 150 150 cm BT /F1 10 Tf 0 0 Td (t) Tj ET Q",
|
||
]);
|
||
let (painted, text) = (marked_text(&pdf, 0), marked_text(&pdf, 1));
|
||
assert_eq!(painted.plain_text(), "turned");
|
||
assert_eq!(painted.glyphs[0].direction, text.glyphs[0].direction);
|
||
let [x0, y0, x1, y1] = painted.glyphs[0].rect;
|
||
assert_eq!((x1 - x0, y1 - y0), (10.0, 40.0), "40 along the turned line, 10 across it");
|
||
}
|
||
|
||
#[test]
|
||
fn actual_text_over_a_picture_reads_where_it_is_drawn() {
|
||
// Two pixels square, so a box placed in pixels rather than across the picture shows.
|
||
let pdf = marked_pages(&["/Span <</ActualText (E=mc2)>> BDC q 60 0 0 20 100 40 cm BI /W 2 /H 2 /CS /G /BPC 8 ID AAAA EI Q EMC"]);
|
||
let text = marked_text(&pdf, 0);
|
||
assert_eq!(text.plain_text(), "E=mc2");
|
||
assert_eq!(text.glyphs[0].rect, [100.0, 240.0, 160.0, 260.0]);
|
||
// Counting without images leaves it out.
|
||
let filter = TextFilter { images: true, ..Default::default() };
|
||
assert_eq!(extract_page_filtered(&pdf, 0, &InterpreterSettings::default(), filter).unwrap().plain_text(), "");
|
||
}
|
||
|
||
#[test]
|
||
fn excluded_glyphs_beside_paint_leave_the_whole_replacement_out() {
|
||
// The marked glyphs are a figure's, so the replacement goes with them; the paint beside
|
||
// them neither keeps it nor turns it into a mixed span that can't be counted.
|
||
let pdf = marked_pages(&[
|
||
"/Span <</ActualText (f)>> BDC /Figure BMC BT /F1 20 Tf 1 0 0 1 100 150 Tm (x) Tj ET EMC 100 40 60 20 re f EMC",
|
||
// Paint inside an excluded region is excluded with it.
|
||
"/Span <</ActualText (z)>> BDC /Figure BMC 100 40 60 20 re f EMC EMC",
|
||
"/Span <</ActualText (t)>> BDC /Table BMC q 60 0 0 20 100 40 cm BI /W 1 /H 1 /CS /G /BPC 8 ID A EI Q EMC EMC",
|
||
]);
|
||
let filtered = |page, filter| extract_page_filtered(&pdf, page, &InterpreterSettings::default(), filter).unwrap().plain_text();
|
||
let (figures, tables) = (TextFilter { images: true, ..Default::default() }, TextFilter { tables: true, ..Default::default() });
|
||
assert_eq!(filtered(0, figures.clone()), "");
|
||
assert_eq!((filtered(1, TextFilter::default()), filtered(1, figures)), ("z".to_string(), String::new()));
|
||
assert_eq!((filtered(2, TextFilter::default()), filtered(2, tables)), ("t".to_string(), String::new()));
|
||
}
|
||
|
||
#[test]
|
||
fn paint_split_by_an_exclusion_is_a_mixed_span_that_cant_be_counted() {
|
||
// Paint places a replacement that marks no glyph, so paint left out mixes it as excluded
|
||
// glyphs do: the words left out can't be told from the rest.
|
||
let picture = "q 60 0 0 20 100 40 cm BI /W 1 /H 1 /CS /G /BPC 8 ID A EI Q";
|
||
let (table, beside) = (
|
||
format!("/Span <</ActualText (t)>> BDC /Table BMC {picture} EMC 200 40 60 20 re f EMC"),
|
||
format!("/Span <</ActualText (p)>> BDC {picture} 200 40 60 20 re f EMC"),
|
||
);
|
||
let pdf = marked_pages(&[
|
||
"/Span <</ActualText (w)>> BDC /Figure BMC 100 40 60 20 re f EMC 200 40 60 20 re f EMC",
|
||
&table,
|
||
&beside,
|
||
// Glyphs place this one, and the paint beside them is not its words.
|
||
"/Span <</ActualText (g)>> BDC BT /F1 20 Tf 1 0 0 1 100 150 Tm (y) Tj ET /Figure BMC 100 40 60 20 re f EMC EMC",
|
||
]);
|
||
let filtered = |page, filter| extract_page_filtered(&pdf, page, &InterpreterSettings::default(), filter).map(|t| t.plain_text());
|
||
let (figures, tables) = (TextFilter { images: true, ..Default::default() }, TextFilter { tables: true, ..Default::default() });
|
||
for (page, text, filter) in [(0, "w", figures.clone()), (1, "t", tables), (2, "p", figures.clone())] {
|
||
assert_eq!(filtered(page, TextFilter::default()), Ok(text.to_string()));
|
||
assert!(filtered(page, filter).is_err(), "page {page}");
|
||
}
|
||
assert_eq!(filtered(3, figures), Ok("g".to_string()));
|
||
}
|
||
|
||
#[test]
|
||
fn annotations_never_join_a_replacement_the_page_left_open() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let pages = doc.new_object_id();
|
||
let content = doc.add_object(Stream::new(dictionary! {}, b"/Span <</ActualText (open)>> BDC 100 40 60 20 re f".to_vec()));
|
||
let ap = doc.add_object(Stream::new(
|
||
dictionary! { "Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 50.into(), 50.into()] },
|
||
b"0 0 50 50 re f".to_vec(),
|
||
));
|
||
let annot = doc.add_object(dictionary! {
|
||
"Type" => "Annot", "Subtype" => "Square", "F" => 4,
|
||
"Rect" => vec![200.into(), 200.into(), 250.into(), 250.into()], "AP" => dictionary! { "N" => ap },
|
||
});
|
||
let page = doc.add_object(dictionary! {
|
||
"Type" => "Page", "Parent" => pages, "Contents" => content, "Annots" => vec![Object::Reference(annot)],
|
||
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)],
|
||
});
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let text = marked_text(&pdf, 0);
|
||
assert_eq!(text.plain_text(), "open");
|
||
assert_eq!(text.glyphs[0].rect, [100.0, 240.0, 160.0, 260.0], "the square comment is not part of it");
|
||
}
|
||
|
||
#[test]
|
||
fn an_unmarked_redraw_of_actual_text_reads_as_the_same_text() {
|
||
// Canva draws text twice (an outline or shadow) and marks only one drawing. The copy,
|
||
// before or after the marked one and half a point off, takes the same replacement and is
|
||
// dropped as a redraw; the same codes elsewhere on the page keep their own text.
|
||
let marked = "BT /F1 20 Tf 1 0 0 1 100 150 Tm (a) Tj /Span <</ActualText <FEFF0E190E490E33>>> BDC (xy) Tj EMC (b) Tj ET";
|
||
let copy = "BT /F1 20 Tf 1 0 0 1 100.5 150.5 Tm (axyb) Tj ET";
|
||
let elsewhere = "BT /F1 20 Tf 1 0 0 1 100 50 Tm (axyb) Tj ET";
|
||
let pdf = marked_pages(&[&format!("{marked} {copy} {elsewhere}"), &format!("{copy} {marked} {elsewhere}")]);
|
||
for page in 0..2 {
|
||
assert_eq!(marked_text(&pdf, page).plain_text(), "aน้ำb\naxyb", "page {page}");
|
||
}
|
||
}
|
||
|
||
/// Issue #3109: text drawn in clipping mode (`7 Tr`) sets the clip for a subsequent fill,
|
||
/// shading or image without painting the glyphs directly, and must still reach `TextDevice`
|
||
/// with the same boxes and search ranges as modes 0–6.
|
||
#[test]
|
||
fn clipping_mode_text_is_extracted_and_searchable_like_other_rendering_modes() {
|
||
let fill_through = " 0 0 1 rg 0 0 300 300 re f";
|
||
let mut pages: Vec<String> =
|
||
(0..=7).map(|mode| format!("q BT /F1 24 Tf {mode} Tr 72 150 Td () Tj [(Hello) -200 (World)] TJ ET{fill_through} Q")).collect();
|
||
// Page 8: /ActualText wrapping 7 Tr clip-only text.
|
||
pages.push(format!("q /Span <</ActualText (Hello World)>> BDC BT /F1 24 Tf 7 Tr 72 150 Td (Glyphs) Tj ET EMC{fill_through} Q"));
|
||
// Page 9: 0 Tr underpainting followed by 7 Tr at the same position (outline/gradient overlay) deduplicates.
|
||
pages.push(format!("BT /F1 24 Tf 0 Tr 72 150 Td (Hello World) Tj ET q BT /F1 24 Tf 7 Tr 72 150 Td (Hello World) Tj ET{fill_through} Q"));
|
||
// Page 10: 90° turned 7 Tr text.
|
||
pages.push(format!("q BT /F1 24 Tf 7 Tr 0 1 -1 0 150 100 Tm (Hello World) Tj ET{fill_through} Q"));
|
||
// Page 11: 7 Tr without any fill-through (visually blank, still extractable).
|
||
pages.push("BT /F1 24 Tf 7 Tr 72 150 Td (Hello World) Tj ET".into());
|
||
|
||
let refs: Vec<&str> = pages.iter().map(String::as_str).collect();
|
||
let pdf = marked_pages(&refs);
|
||
let control = marked_text(&pdf, 0);
|
||
assert_eq!(control.plain_text(), "Hello World");
|
||
let control_rects = control.line_rects(0..5);
|
||
assert_eq!(control_rects.len(), 1);
|
||
for mode in 0..=7 {
|
||
let text = marked_text(&pdf, mode);
|
||
assert_eq!(text.plain_text(), "Hello World", "mode {mode} Tr");
|
||
assert_eq!(text.find("hello"), vec![0..5], "mode {mode} Tr");
|
||
assert_eq!(text.find_opts("Hello", true, true), vec![0..5], "mode {mode} Tr");
|
||
assert_eq!(
|
||
text.find_with(|chars| chars.starts_with(&['H', 'e', 'l', 'l', 'o']).then_some(0..5).into_iter().collect()),
|
||
vec![0..5],
|
||
"mode {mode} Tr"
|
||
);
|
||
assert_eq!(text.line_rects(0..5), control_rects, "mode {mode} Tr");
|
||
assert_eq!(text.glyphs, control.glyphs, "mode {mode} Tr");
|
||
}
|
||
let actual = marked_text(&pdf, 8);
|
||
assert_eq!(actual.plain_text(), "Hello World");
|
||
assert_eq!(actual.find("Hello"), vec![0..1]);
|
||
|
||
let deduped = marked_text(&pdf, 9);
|
||
assert_eq!(deduped.plain_text(), "Hello World");
|
||
|
||
let turned = marked_text(&pdf, 10);
|
||
assert_eq!(turned.plain_text(), "Hello World");
|
||
assert_eq!(turned.find("World"), vec![6..11]);
|
||
|
||
let unfilled = marked_text(&pdf, 11);
|
||
assert_eq!(unfilled.plain_text(), "Hello World");
|
||
|
||
// Visual check: page 7 (`7 Tr` + blue fill-through) paints blue only inside the clipped
|
||
// glyph outlines, whereas page 11 (`7 Tr` alone) paints no ink at all.
|
||
let mut renderer = crate::PageRenderer::new(std::sync::Arc::new(pdf.data().as_ref().to_vec()), crate::RenderConfig::default());
|
||
let filled_px = renderer.render(crate::RenderRequest { page: 7, kind: crate::RequestKind::Pixels, scale: 1.0, ..Default::default() });
|
||
assert!(filled_px.error.is_none());
|
||
let blue_pixels = filled_px.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 32 && p[1] < 32 && p[2] > 200).count();
|
||
let white_pixels = filled_px.rgba.as_chunks::<4>().0.iter().filter(|p| p[..3] == [255, 255, 255]).count();
|
||
assert!(blue_pixels > 50 && white_pixels > 80_000, "blue={blue_pixels}, white={white_pixels}");
|
||
|
||
let unfilled_px = renderer.render(crate::RenderRequest { page: 11, kind: crate::RequestKind::Pixels, scale: 1.0, ..Default::default() });
|
||
assert!(unfilled_px.error.is_none());
|
||
assert!(unfilled_px.rgba.as_chunks::<4>().0.iter().all(|p| p[..3] == [255, 255, 255]));
|
||
}
|
||
|
||
#[test]
|
||
fn clipping_mode_filter_keeps_titles_and_excludes_ocr() {
|
||
let pdf = marked_pages(&[
|
||
"q BT /F1 24 Tf 7 Tr 30 200 Td (Clipped heading) Tj ET 0 0 1 rg 0 0 300 300 re f Q BT /F1 12 Tf 3 Tr 30 100 Td (Hidden OCR) Tj ET",
|
||
"q /Span <</ActualText (Accessible heading)>> BDC BT /F1 24 Tf 7 Tr 30 200 Td (Clipped heading) Tj ET EMC 0 0 1 rg 0 0 300 300 re f Q",
|
||
]);
|
||
assert!(marked_text(&pdf, 0).plain_text().contains("Hidden OCR"));
|
||
for (page, expected) in [(0, "Clipped heading"), (1, "Accessible heading")] {
|
||
let text = extract_page_filtered(&pdf, page, &InterpreterSettings::default(), TextFilter { images: true, ..Default::default() }).unwrap();
|
||
assert_eq!(text.plain_text(), expected);
|
||
assert!(!text.find("heading").is_empty());
|
||
}
|
||
}
|
||
|
||
/// ISO 32000-2 §9.3.6: Type 3 text under `7 Tr` is not rendered (vendored hayro-interpret
|
||
/// patch 64), but it is still clipping text, not an invisible text layer: the filter that
|
||
/// drops OCR layers keeps it, as it keeps clipping text in other fonts.
|
||
#[test]
|
||
fn clipping_mode_type3_text_is_kept_by_the_ocr_filter() {
|
||
let font = "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] \
|
||
/CharProcs << /A 6 0 R >> /Encoding << /Type /Encoding /Differences [65 /A] >> \
|
||
/FirstChar 65 /LastChar 65 /Widths [1000] >>";
|
||
let glyph = "1000 0 100 0 900 800 d1 100 0 800 800 re f";
|
||
let content = "BT /T3 24 Tf 7 Tr 30 200 Td (AAA) Tj ET BT /T3 12 Tf 3 Tr 30 100 Td (A) Tj ET";
|
||
let objects = [
|
||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /T3 5 0 R >> >> >>".to_string(),
|
||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||
font.to_string(),
|
||
format!("<< /Length {} >>\nstream\n{glyph}\nendstream", glyph.len()),
|
||
];
|
||
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 offset in offsets {
|
||
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||
}
|
||
bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let all = extract_page_filtered(&pdf, 0, &InterpreterSettings::default(), TextFilter::default()).unwrap();
|
||
assert_eq!(all.plain_text().matches('A').count(), 4, "{:?}", all.plain_text());
|
||
let filtered = extract_page_filtered(&pdf, 0, &InterpreterSettings::default(), TextFilter { images: true, ..Default::default() }).unwrap();
|
||
assert_eq!(filtered.plain_text().trim(), "AAA", "the 7 Tr text stays, the 3 Tr layer goes");
|
||
}
|
||
|
||
/// One page per `(encoding, content)`, in Helvetica (`/F1`).
|
||
fn encoded_pages(pages: &[(lopdf::Object, &[u8])]) -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let pages_id = doc.new_object_id();
|
||
let mut kids = Vec::new();
|
||
for (encoding, content) in pages {
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => encoding.clone() });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
kids.push(Object::Reference(page));
|
||
}
|
||
let count = kids.len() as i64;
|
||
doc.objects.insert(pages_id, dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
/// The Annex D.2 alias codes extract as the ink they draw, not as formatting characters.
|
||
///
|
||
/// WinAnsiEncoding gives 0xAD and 0xA0 the glyph names `hyphen` and `space`, the names it
|
||
/// also gives 0x2D and 0x20, and MacRomanEncoding gives 0xCA `space`. Reporting the Adobe
|
||
/// Glyph List values U+00AD and U+00A0 for them hid visible text: a soft hyphen is invisible,
|
||
/// so "well-known" written that way matched no search and no redaction pattern.
|
||
/// `XiaoBiaoSong.pdf` in the pdf.js corpus drew 104 of them.
|
||
///
|
||
/// A `/Differences` entry naming `sfthyphen` or `nbspace` is a deliberate statement about one
|
||
/// code and keeps its glyph list value. pdftotext draws the same line: on this fixture it
|
||
/// reads the base-encoded codes as "a-b a b" and the named ones as U+00AD.
|
||
#[test]
|
||
fn the_annex_d2_alias_codes_read_as_an_ordinary_hyphen_and_space() {
|
||
use lopdf::{Object, dictionary};
|
||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||
let differences = Object::Dictionary(dictionary! {
|
||
"Type" => "Encoding",
|
||
"BaseEncoding" => "WinAnsiEncoding",
|
||
"Differences" => vec![Object::Integer(88), name("sfthyphen"), Object::Integer(89), name("nbspace")],
|
||
});
|
||
let pdf = encoded_pages(&[
|
||
(name("WinAnsiEncoding"), &b"BT /F1 20 Tf 1 0 0 1 20 150 Tm (a\xadb\xa0c) Tj ET"[..]),
|
||
(name("MacRomanEncoding"), &b"BT /F1 20 Tf 1 0 0 1 20 150 Tm (a\xcab) Tj ET"[..]),
|
||
(differences, &b"BT /F1 20 Tf 1 0 0 1 20 150 Tm (aXbYc) Tj ET"[..]),
|
||
]);
|
||
let texts = |page| extract_page(&pdf, page, &InterpreterSettings::default()).unwrap().glyphs.iter().map(|g| g.text.clone()).collect::<Vec<_>>();
|
||
assert_eq!(texts(0), ["a", "-", "b", " ", "c"], "WinAnsi 0xAD and 0xA0");
|
||
assert_eq!(texts(1), ["a", " ", "b"], "MacRoman 0xCA");
|
||
assert_eq!(texts(2), ["a", "\u{ad}", "b", "\u{a0}", "c"], "a named glyph keeps its glyph list value");
|
||
}
|
||
|
||
/// #3169, #3170: glyph names outside the Adobe Glyph List still read as text. Ligature
|
||
/// (`f_i`) and suffixed (`hyphen.case`) names go by the glyph list specification's full
|
||
/// mapping. A name that only numbers the glyph reads as nothing, not as a guess from the code
|
||
/// (review on #3239: with `/C1` at 233, StandardEncoding's 233 would read `Ø` for a glyph drawn
|
||
/// as `é`). `C39` at 39 and `C174` at 174 name their own codes, but this font's other numbered
|
||
/// names (`c251` at 97, `C39.sc` at 61, `C1` at 233, `a12` at 88) don't, so they read as
|
||
/// nothing too (see `numbered_glyph_names_read_as_their_own_code`). A name with no meaning
|
||
/// left (`foo`) reads as nothing.
|
||
#[test]
|
||
fn glyph_names_outside_the_glyph_list_still_read_as_text() {
|
||
use lopdf::{Object, dictionary};
|
||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||
let differences = Object::Dictionary(dictionary! {
|
||
"Type" => "Encoding",
|
||
"Differences" => vec![
|
||
Object::Integer(30), name("f_i"), name("f_l"), Object::Integer(2), name("hyphen.case"),
|
||
Object::Integer(39), name("C39"), Object::Integer(97), name("c251"), Object::Integer(174), name("C174"),
|
||
Object::Integer(88), name("a12"), name("foo"), name("uni00660069"),
|
||
Object::Integer(61), name("C39.sc"), Object::Integer(233), name("C1"),
|
||
],
|
||
});
|
||
// One glyph per line: the test font has none of these glyphs, so they have no width, and
|
||
// on one line a later `fi` would sit on the first and be dropped as its fake-bold copy.
|
||
let mut content = b"BT /F1 20 Tf 20 290 Td".to_vec();
|
||
for code in *b"\x1e\x1f\x02'a\xaeXYZ=\xe9" {
|
||
content.extend_from_slice(b" (");
|
||
content.push(code);
|
||
content.extend_from_slice(b") Tj 0 -25 Td");
|
||
}
|
||
content.extend_from_slice(b" ET");
|
||
let pdf = encoded_pages(&[(differences, &content[..])]);
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text();
|
||
let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||
assert_eq!(lines, ["fi", "fl", "-", "fi"], "{text:?}");
|
||
}
|
||
|
||
/// A glyph name that only numbers its glyph, with no `/ToUnicode` (ISO 32000-2 §9.10.2 has no
|
||
/// route for it), reads as its code's Latin-1 character when the number is that very code, in
|
||
/// decimal (`C70` at 70, `C0071` at 71, `MT72` at 72, `C39` at 39, `C174` at 174) or
|
||
/// hexadecimal (`G49` at 0x49, `GE9` at 0xE9), as pdftotext, PDFium and MuPDF read
|
||
/// it: Windows printer drivers and typesetters name subset glyphs so. Only in a font where every
|
||
/// numbered name names its own code: one more name numbering another code (`/C1` at 233, review
|
||
/// on #3239) turns the whole font back to nothing, and so does a font whose names number
|
||
/// something else, where a name can match its code by coincidence (`/MT40` at 0x40). A subset
|
||
/// that counts its glyphs in order of first use from code 1 (`/Differences [1 /C1 /C2 … /C80]`)
|
||
/// names its own codes too, but `/C65` there is the 65th glyph used, not `A`: a numbered name at
|
||
/// a control code (`C1` at 1, `C9` at 9) gives the counter away and the font reads nothing.
|
||
/// Code 32 is the first code a numbered name may name: `C32` at 32 reads as a space.
|
||
#[test]
|
||
fn numbered_glyph_names_read_as_their_own_code() {
|
||
use lopdf::{Object, dictionary};
|
||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||
let encoding = |differences: Vec<Object>| Object::Dictionary(dictionary! { "Type" => "Encoding", "Differences" => differences });
|
||
// One glyph per line, as in `glyph_names_outside_the_glyph_list_still_read_as_text`.
|
||
let one_per_line = |codes: &[u8]| {
|
||
let mut content = b"BT /F1 20 Tf 20 290 Td".to_vec();
|
||
for code in codes {
|
||
content.extend_from_slice(format!(" <{code:02x}> Tj 0 -25 Td").as_bytes());
|
||
}
|
||
content.extend_from_slice(b" ET");
|
||
content
|
||
};
|
||
let own = encoding(vec![
|
||
Object::Integer(70),
|
||
name("C70"),
|
||
name("C0071"),
|
||
name("MT72"),
|
||
name("G49"),
|
||
Object::Integer(233),
|
||
name("GE9"),
|
||
Object::Integer(39),
|
||
name("C39"),
|
||
Object::Integer(174),
|
||
name("C174"),
|
||
]);
|
||
let one_other = encoding(vec![Object::Integer(70), name("C70"), Object::Integer(233), name("C1")]);
|
||
let numbered_otherwise = encoding(vec![Object::Integer(1), name("C70"), name("C105"), Object::Integer(64), name("MT40")]);
|
||
let counter = encoding(std::iter::once(Object::Integer(1)).chain((1..=80).map(|n| name(&format!("C{n}")))).collect());
|
||
let own_and_a_control = encoding(vec![Object::Integer(9), name("C9"), Object::Integer(70), name("C70"), name("C0071")]);
|
||
// Code 32 is the first code a numbered name may name: `/C32` at 32 is a space, not a counter.
|
||
let own_from_32 = encoding(vec![Object::Integer(32), name("C32"), Object::Integer(70), name("C70"), name("C0071")]);
|
||
let pages = [
|
||
one_per_line(b"FGHI\xe9'\xae"),
|
||
one_per_line(b"F\xe9"),
|
||
one_per_line(b"\x01\x02@"),
|
||
one_per_line(b"\x01\x20\x41\x42\x50"),
|
||
one_per_line(b"\x09FG"),
|
||
b"BT /F1 20 Tf 20 290 Td <462047> Tj ET".to_vec(),
|
||
];
|
||
let pdf = encoded_pages(&[
|
||
(own, &pages[0][..]),
|
||
(one_other, &pages[1][..]),
|
||
(numbered_otherwise, &pages[2][..]),
|
||
(counter, &pages[3][..]),
|
||
(own_and_a_control, &pages[4][..]),
|
||
(own_from_32, &pages[5][..]),
|
||
]);
|
||
let lines = |page| {
|
||
let text = extract_page(&pdf, page, &InterpreterSettings::default()).unwrap().plain_text();
|
||
text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect::<Vec<_>>()
|
||
};
|
||
assert_eq!(lines(0), ["F", "G", "H", "I", "\u{e9}", "'", "\u{ae}"]);
|
||
assert!(lines(1).is_empty(), "/C1 at 233 beside /C70 at 70: {:?}", lines(1));
|
||
assert!(lines(2).is_empty(), "/MT40 at 0x40 among names numbering other codes: {:?}", lines(2));
|
||
assert!(lines(3).is_empty(), "a first-use counter /C1 … /C80 from code 1: {:?}", lines(3));
|
||
assert!(lines(4).is_empty(), "/C9 at 9 beside /C70 at 70: {:?}", lines(4));
|
||
let page5 = extract_page(&pdf, 5, &InterpreterSettings::default()).unwrap().plain_text();
|
||
assert_eq!(page5.trim_matches('\n'), "F G", "/C32 at 32 beside /C70 at 70 reads as a space");
|
||
}
|
||
|
||
/// `numbered_glyph_names_read_as_their_own_code` in a Type 3 font, which already reads codes
|
||
/// 32-126 by the code: above 126, `C174` at 174, `C176` at 176 and `GE9` at 0xE9 read as the
|
||
/// code's Latin-1 character, unless one numbered name in the font numbers another code
|
||
/// (`/C1` at 233) or sits at a control code, as a first-use counter's `/C1` at 1 does.
|
||
#[test]
|
||
fn numbered_type3_glyph_names_read_as_their_own_code() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||
// Each font's /Differences as (code, glyph name) pairs, and the codes its page shows.
|
||
type Names<'a> = &'a [(i64, &'a str)];
|
||
let fonts: [(Names, &[u8]); 3] = [
|
||
(&[(70, "C70"), (174, "C174"), (176, "C176"), (233, "GE9")], b"F\xae\xb0\xe9"),
|
||
(&[(174, "C174"), (176, "C176"), (233, "C1")], b"\xae\xb0\xe9"),
|
||
(&[(1, "C1"), (2, "C2"), (174, "C174"), (176, "C176")], b"\xae\xb0"),
|
||
];
|
||
let mut doc = Document::with_version("1.7");
|
||
let pages_id = doc.new_object_id();
|
||
let mut kids = Vec::new();
|
||
for (names, codes) in fonts {
|
||
let glyph = doc.add_object(Stream::new(dictionary! {}, b"600 0 0 0 500 700 d1 0 0 500 700 re f".to_vec()));
|
||
let mut differences = Vec::new();
|
||
let mut procs = lopdf::Dictionary::new();
|
||
for &(code, glyph_name) in names {
|
||
differences.extend([Object::Integer(code), name(glyph_name)]);
|
||
procs.set(glyph_name, glyph);
|
||
}
|
||
let font = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "Type3",
|
||
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()],
|
||
"FontMatrix" => vec![0.001.into(), 0.into(), 0.into(), 0.001.into(), 0.into(), 0.into()],
|
||
"CharProcs" => procs,
|
||
"Encoding" => dictionary! { "Type" => "Encoding", "Differences" => differences },
|
||
"FirstChar" => 0, "LastChar" => 255, "Widths" => vec![Object::Integer(600); 256],
|
||
});
|
||
// One glyph per line, as in `glyph_names_outside_the_glyph_list_still_read_as_text`.
|
||
let mut content = b"BT /T3 20 Tf 20 290 Td".to_vec();
|
||
for code in codes {
|
||
content.extend_from_slice(format!(" <{code:02x}> Tj 0 -25 Td").as_bytes());
|
||
}
|
||
content.extend_from_slice(b" ET");
|
||
let content = doc.add_object(Stream::new(dictionary! {}, content));
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "MediaBox" => vec![0.into(), 0.into(), 300.into(), 300.into()], "Resources" => dictionary! {"Font" => dictionary! {"T3" => font}}, "Contents" => content });
|
||
kids.push(Object::Reference(page));
|
||
}
|
||
let count = kids.len() as i64;
|
||
doc.objects.insert(pages_id, dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let lines = |page| {
|
||
let text = extract_page(&pdf, page, &InterpreterSettings::default()).unwrap().plain_text();
|
||
text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect::<Vec<_>>()
|
||
};
|
||
assert_eq!(lines(0), ["F", "\u{ae}", "\u{b0}", "\u{e9}"]);
|
||
assert!(lines(1).is_empty(), "/C1 at 233 beside /C174 at 174: {:?}", lines(1));
|
||
assert!(lines(2).is_empty(), "a counter's /C1 at 1 beside /C174 at 174: {:?}", lines(2));
|
||
}
|
||
|
||
/// Review on #3239: the glyph list specification's `uni` and `u` forms take uppercase hex
|
||
/// digits only, and map a name with lowercase ones to nothing ("uni20ac" in its examples).
|
||
/// Names upstream's own lookup can't read (several groups, a suffix) show it: lowercase reads
|
||
/// as nothing, uppercase as its characters. A bare `uni20ac` or `u1040c` reads as nothing too
|
||
/// (`agl_unicode_from_name_rule_reads_text`).
|
||
#[test]
|
||
fn glyph_names_with_lowercase_hex_read_as_nothing() {
|
||
use lopdf::{Object, dictionary};
|
||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||
let differences = Object::Dictionary(dictionary! {
|
||
"Type" => "Encoding",
|
||
"Differences" => vec![Object::Integer(65), name("uni20ac0308"), name("uni20AC0308"), name("u1040c.alt"), name("u1040C.alt"), name("f_uni20ac"), name("f_uni20AC")],
|
||
});
|
||
let pdf = encoded_pages(&[(
|
||
differences,
|
||
&b"BT /F1 20 Tf 20 180 Td (A) Tj 0 -25 Td (B) Tj 0 -25 Td (C) Tj 0 -25 Td (D) Tj 0 -25 Td (E) Tj 0 -25 Td (F) Tj ET"[..],
|
||
)]);
|
||
// One glyph per line, so each name's text stays its own (and a name read as nothing
|
||
// leaves no line).
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text();
|
||
let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||
assert_eq!(lines, ["\u{20ac}\u{308}", "\u{1040c}", "f", "f\u{20ac}"], "{text:?}");
|
||
}
|
||
|
||
/// The glyph list specification's `uni` form is `uni` and groups of exactly four uppercase hex
|
||
/// digits, its `u` form `u` and four to six, outside the surrogate range: `uni65`, `u65`,
|
||
/// `uni20ac`, `u1f600`, `uni+065` and `uniD800` name no character, and their glyphs read as
|
||
/// nothing rather than as `e`, `€` or an emoji. The well-formed names read as before.
|
||
#[test]
|
||
fn agl_unicode_from_name_rule_reads_text() {
|
||
use lopdf::{Object, dictionary};
|
||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||
let names = ["uni65", "u65", "uni20ac", "u1f600", "uni+065", "uniD800", "u10FFFF0", "uni0065", "u0066", "u1F600", "uni20AC"];
|
||
let differences = Object::Dictionary(dictionary! {
|
||
"Type" => "Encoding",
|
||
"Differences" => std::iter::once(Object::Integer(65)).chain(names.iter().map(|n| name(n))).collect::<Vec<_>>(),
|
||
});
|
||
// One glyph per line, so each name's text stays its own (and a name read as nothing
|
||
// leaves no line).
|
||
let mut content = b"BT /F1 20 Tf 20 290 Td".to_vec();
|
||
for code in (b'A'..).take(names.len()) {
|
||
content.extend_from_slice(b" (");
|
||
content.push(code);
|
||
content.extend_from_slice(b") Tj 0 -25 Td");
|
||
}
|
||
content.extend_from_slice(b" ET");
|
||
let pdf = encoded_pages(&[(differences, &content[..])]);
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text();
|
||
let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||
assert_eq!(lines, ["e", "f", "\u{1f600}", "\u{20ac}"], "{text:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn narrow_ligatures_keep_every_letter() {
|
||
// Split evenly, this "ffi" put its two "f"s so close that the second was dropped as a
|
||
// fake-bold copy of the first.
|
||
let pdf = ligature_pages("1 beginbfchar <62> <006600660069> endbfchar", "obce", &["1 0 0 1 100 150"]);
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), "office");
|
||
}
|
||
|
||
#[test]
|
||
fn right_to_left_ligatures_keep_their_logical_order() {
|
||
// "سلام" drawn left to right as meem, alef, lam, seen; then with lam-alef as one glyph.
|
||
let letters = ligature_pages("4 beginbfchar <61> <0645> <62> <0644> <63> <0633> <64> <0627> endbfchar", "adbc", &["1 0 0 1 100 150"]);
|
||
let ligature = ligature_pages("3 beginbfchar <61> <0645> <62> <06440627> <63> <0633> endbfchar", "abc", &["1 0 0 1 100 150"]);
|
||
for pdf in [letters, ligature] {
|
||
assert_eq!(extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text(), "سلام");
|
||
}
|
||
// "بَاب" with beh and its fatha as one glyph, as Add text writes shaped Arabic: the mark
|
||
// stays after its letter.
|
||
let marked = ligature_pages("3 beginbfchar <61> <0628064E> <62> <0627> <63> <0628> endbfchar", "cba", &["1 0 0 1 100 150"]);
|
||
assert_eq!(extract_page(&marked, 0, &InterpreterSettings::default()).unwrap().plain_text(), "بَاب");
|
||
}
|
||
|
||
#[test]
|
||
fn vertical_ligatures_stay_in_their_column() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
// CID 2 is one glyph for "株式".
|
||
let cmap = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /TestUnicode def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 3 beginbfchar <0001> <65E5> <0002> <682A5F0F> <0003> <8A9E> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
let unicode = doc.add_object(Stream::new(dictionary! {}, cmap.to_vec()));
|
||
let cid = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "CIDFontType2", "BaseFont" => "TestVertical",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 },
|
||
"DW" => 1000, "DW2" => vec![Object::Integer(880), Object::Integer(-1000)], "CIDToGIDMap" => "Identity"
|
||
});
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "TestVertical", "Encoding" => "Identity-V", "DescendantFonts" => vec![Object::Reference(cid)], "ToUnicode" => unicode });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 20 Tf 1 0 0 1 200 250 Tm <000100020003> Tj ET".to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), "日株式語");
|
||
assert_eq!(text.glyphs.len(), 3);
|
||
assert_eq!(text.line_rects(0..3).len(), 1, "one column");
|
||
}
|
||
|
||
/// A column of Latin capitals in a vertical font, tracked out with negative character spacing
|
||
/// (pdf.js issue 20930: `-40 Tc` puts 40 pt between 24 pt letters). Across the column each glyph
|
||
/// is as wide as its `/W` width w0 and centred on the column (ISO 32000-2 §9.7.4.3), so the
|
||
/// letters stay one line and Find matches the word. Boxes as wide as each outline made a narrow
|
||
/// letter's line allowance smaller than the tracking, and the column broke into lines.
|
||
#[test]
|
||
fn tracked_vertical_latin_stays_one_line() {
|
||
tracked_vertical_latin(-40.0, 100.0);
|
||
}
|
||
|
||
#[test]
|
||
fn horizontally_scaled_vertical_latin_box_is_scaled_across_the_column() {
|
||
// Horizontal scaling Th = Tz / 100 scales the glyph's width w0 across the column (ISO 32000-2
|
||
// §9.4.4, the text rendering matrix), and not the advance down it. The tracking is 20 pt here:
|
||
// the line's gap allowance is three times the narrower box across it, 3 × 8 pt at 50 Tz.
|
||
tracked_vertical_latin(-20.0, 50.0);
|
||
}
|
||
|
||
/// `ABCDE` down one Identity-V column at 24 pt with `tc Tc` and `tz Tz`.
|
||
fn tracked_vertical_latin(tc: f32, tz: f32) {
|
||
let text = vertical_latin(
|
||
&[(36, 667), (37, 667), (38, 722), (39, 722), (40, 667)],
|
||
None,
|
||
&format!("BT /F1 24 Tf {tc} Tc {tz} Tz 1 0 0 1 100 340 Tm <00240025002600270028> Tj ET"),
|
||
);
|
||
assert_eq!(text.plain_text(), "ABCDE");
|
||
assert_eq!(text.find("ABCDE"), vec![0..5]);
|
||
// Each box spans w0 (here 24 pt × 0.667 or 0.722, times Th) centred on the column at x = 100.
|
||
assert_eq!(text.glyphs.len(), 5);
|
||
for (g, w0) in text.glyphs.iter().zip([667.0, 667.0, 722.0, 722.0, 667.0]) {
|
||
let [x0, _, x1, _] = g.rect;
|
||
assert!((x1 - x0 - 24.0 * w0 / 1000.0 * tz / 100.0).abs() < 0.01, "{:?} is w0 wide: {:?}", g.text, g.rect);
|
||
assert!(((x0 + x1) / 2.0 - 100.0).abs() < 0.01, "{:?} is centred on the column: {:?}", g.text, g.rect);
|
||
}
|
||
}
|
||
|
||
/// The text of a page showing `content` in a vertical CIDFontType2 `/F1` with `/DW 1000`, the
|
||
/// `widths` (CID, w0) in `/W`, and CIDs 36 to 41 reading `A` to `F`. `cmap` is the body of an
|
||
/// embedded vertical CMap mapping codes to CIDs (`begincidchar` … `endcidchar`); `None` uses
|
||
/// Identity-V.
|
||
fn vertical_latin(widths: &[(i64, i64)], cmap: Option<&str>, content: &str) -> crate::text::PageText {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let to_unicode = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /TestUnicode def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 6 beginbfchar <0024> <0041> <0025> <0042> <0026> <0043> <0027> <0044> <0028> <0045> <0029> <0046> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
let unicode = doc.add_object(Stream::new(dictionary! {}, to_unicode.to_vec()));
|
||
let widths: Vec<Object> = widths.iter().flat_map(|&(cid, w)| [Object::Integer(cid), Object::Array(vec![Object::Integer(w)])]).collect();
|
||
let cid = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "CIDFontType2", "BaseFont" => "TestVerticalLatin",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 },
|
||
"DW" => 1000, "W" => widths, "DW2" => vec![Object::Integer(880), Object::Integer(-1000)], "CIDToGIDMap" => "Identity"
|
||
});
|
||
let encoding = match cmap {
|
||
Some(body) => {
|
||
let stream = format!(
|
||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> def /CMapName /TestCodes-V def /CMapType 1 def /WMode 1 def 1 begincodespacerange <0000> <FFFF> endcodespacerange {body} endcmap CMapName currentdict /CMap defineresource pop end end"
|
||
);
|
||
Object::Reference(doc.add_object(Stream::new(
|
||
dictionary! { "Type" => "CMap", "CMapName" => "TestCodes-V", "WMode" => 1, "CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 } },
|
||
stream.into_bytes(),
|
||
)))
|
||
}
|
||
None => Object::Name(b"Identity-V".to_vec()),
|
||
};
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "TestVerticalLatin", "Encoding" => encoding, "DescendantFonts" => vec![Object::Reference(cid)], "ToUnicode" => unicode });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(400), Object::Integer(500)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap()
|
||
}
|
||
|
||
/// A CID that `/W` doesn't list is `/DW` wide across the column (ISO 32000-2 §9.7.4.3), and the
|
||
/// widths are looked up by CID, not by character code: an embedded vertical CMap maps the codes
|
||
/// `<0024>`… (which `/W` lists 500 wide as CIDs) to CIDs 50…. The tracked column stays one line
|
||
/// that Find matches.
|
||
#[test]
|
||
fn vertical_latin_widths_come_from_dw_and_are_looked_up_by_cid() {
|
||
let cmap = "5 begincidchar <0024> 50 <0025> 51 <0026> 52 <0027> 53 <0028> 54 endcidchar";
|
||
// CID 52 (`C`) has no /W entry: it is /DW = 1000 wide.
|
||
let widths = [(36, 500), (37, 500), (38, 500), (39, 500), (40, 500), (50, 667), (51, 667), (53, 722), (54, 667)];
|
||
let text = vertical_latin(&widths, Some(cmap), "BT /F1 24 Tf -40 Tc 1 0 0 1 100 340 Tm <00240025002600270028> Tj ET");
|
||
assert_eq!(text.plain_text(), "ABCDE");
|
||
assert_eq!(text.find("ABCDE"), vec![0..5]);
|
||
let got: Vec<f32> = text.glyphs.iter().map(|g| g.rect[2] - g.rect[0]).collect();
|
||
assert_eq!(got.len(), 5);
|
||
for (w, w0) in got.iter().zip([667.0, 667.0, 1000.0, 722.0, 667.0]) {
|
||
assert!((w - 24.0 * w0 / 1000.0).abs() < 0.01, "{got:?}");
|
||
}
|
||
}
|
||
|
||
/// Two vertical columns of `/DW`-wide letters set 13.5 pt apart at 20 pt overlap across the
|
||
/// column (each box is 20 pt wide), and still read as two lines, in order, with Find matching
|
||
/// each column and not a word spanning both.
|
||
#[test]
|
||
fn close_vertical_columns_of_dw_wide_letters_stay_apart() {
|
||
let text = vertical_latin(&[], None, "BT /F1 20 Tf 1 0 0 1 113.5 340 Tm <002400250026> Tj 1 0 0 1 100 340 Tm <002700280029> Tj ET");
|
||
assert_eq!(text.plain_text().lines().map(str::trim).collect::<Vec<_>>(), ["ABC", "DEF"]);
|
||
assert_eq!(text.find("ABC").len(), 1);
|
||
assert_eq!(text.find("DEF").len(), 1);
|
||
assert!(text.find("CD").is_empty() && text.find("ABCDEF").is_empty(), "{:?}", text.plain_text());
|
||
}
|
||
|
||
#[test]
|
||
fn upright_mapping_round_trips() {
|
||
let r = [10.0, 20.0, 30.0, 25.0];
|
||
for q in 0..4 {
|
||
assert_eq!(from_upright(to_upright(r, q, 300.0, 200.0), q, 300.0, 200.0), r, "quarter {q}");
|
||
}
|
||
// A 90° page: the view's top-right corner is the upright top-left.
|
||
assert_eq!(to_upright([290.0, 0.0, 300.0, 10.0], 1, 300.0, 200.0), [0.0, 0.0, 10.0, 10.0]);
|
||
}
|
||
|
||
#[test]
|
||
fn whole_words_ignore_neighbours_in_scripts_written_without_spaces() {
|
||
// "台北市的PDF檔案" in one run: Chinese writes no spaces between words, so "台北" is a
|
||
// whole word inside "台北市" and "PDF" inside "的PDF檔", as Acrobat finds them with Whole
|
||
// words only on. A Latin neighbour still bounds: "cat" is not a whole word in "category".
|
||
let mut v = Vec::new();
|
||
word(&mut v, "台北市的PDF檔案", 10.0, 10.0, 6.0);
|
||
word(&mut v, "category", 74.0, 10.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text(), "台北市的PDF檔案 category");
|
||
assert_eq!(t.find_opts("台北", false, true), vec![0..2], "a word inside a longer run of ideographs");
|
||
assert_eq!(t.find_opts("北市", false, true), vec![1..3]);
|
||
assert_eq!(t.find_opts("PDF", false, true), vec![4..7], "Latin between ideographs");
|
||
assert_eq!(t.find_opts("pdf檔", false, true), vec![4..8]);
|
||
assert!(t.find_opts("cat", false, true).is_empty(), "Latin neighbours still bound a word");
|
||
assert_eq!(t.find_opts("category", false, true), vec![9..17]);
|
||
// Thai and Japanese kana are written without spaces too.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "ภาษาไทย", 10.0, 30.0, 6.0);
|
||
word(&mut v, "ひらがなとカタカナ", 62.0, 30.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.find_opts("ไทย", false, true), vec![4..7]);
|
||
assert_eq!(t.find_opts("カタカナ", false, true), vec![12..16]);
|
||
}
|
||
|
||
/// #2075 review: digits still bound a whole word in those scripts (๑ is not a word inside
|
||
/// the number ๑๒), and letters from the later Myanmar and Han blocks don't.
|
||
#[test]
|
||
fn whole_words_in_unspaced_scripts_keep_digits_and_later_blocks() {
|
||
let one = |text: &str| {
|
||
let mut v = Vec::new();
|
||
word(&mut v, text, 10.0, 10.0, 6.0);
|
||
layout(v)
|
||
};
|
||
assert!(one("๑๒").find_opts("๑", false, true).is_empty(), "a Thai digit beside it bounds");
|
||
assert!(one("台北3").find_opts("台北", false, true).is_empty(), "so does an ASCII digit");
|
||
// Myanmar Extended-A (U+AA60), Myanmar Extended-B (U+A9E0), CJK Extension H (U+31350).
|
||
for text in ["\u{AA60}PDF", "\u{A9E0}PDF", "\u{31350}PDF"] {
|
||
assert_eq!(one(text).find_opts("PDF", false, true), vec![1..4], "{text}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn turkish_dotted_and_dotless_i_match_in_any_case() {
|
||
// "İSTANBUL IRMAK KIŞ" on one line: each word typed in lower case must find it, and the
|
||
// reverse. `to_lowercase` alone made `İ` two characters and left `ı` unmatched.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "İSTANBUL", 10.0, 10.0, 7.0);
|
||
word(&mut v, "IRMAK", 80.0, 10.0, 7.0);
|
||
word(&mut v, "KIŞ", 130.0, 10.0, 7.0);
|
||
let upper = layout(v);
|
||
assert_eq!(upper.plain_text(), "İSTANBUL IRMAK KIŞ");
|
||
assert_eq!(upper.find("istanbul"), vec![0..8]);
|
||
assert_eq!(upper.find("İstanbul"), vec![0..8]);
|
||
assert_eq!(upper.find("ırmak"), vec![8..13]);
|
||
assert_eq!(upper.find("kış"), vec![13..16]);
|
||
assert_eq!(upper.find("istanbul ırmak kış"), vec![0..16], "a phrase across the words");
|
||
assert_eq!(upper.find_opts("ırmak", false, true), vec![8..13], "whole words");
|
||
assert!(upper.find_opts("istanbul", true, false).is_empty(), "case-sensitive search stays exact");
|
||
assert_eq!(upper.find_opts("İSTANBUL", true, false), vec![0..8]);
|
||
|
||
let mut v = Vec::new();
|
||
word(&mut v, "istanbul", 10.0, 10.0, 7.0);
|
||
word(&mut v, "ırmak", 80.0, 10.0, 7.0);
|
||
word(&mut v, "kış", 130.0, 10.0, 7.0);
|
||
let lower = layout(v);
|
||
assert_eq!(lower.find("İSTANBUL"), vec![0..8]);
|
||
assert_eq!(lower.find("IRMAK"), vec![8..13]);
|
||
assert_eq!(lower.find("KIŞ"), vec![13..16]);
|
||
}
|
||
|
||
/// Find and replace matches a paragraph's text with the find bar's own rules: the same
|
||
/// matches as the page search, as byte ranges of the text (multi-byte letters included).
|
||
#[test]
|
||
fn text_search_agrees_with_the_page_search() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "İSTANBUL", 10.0, 10.0, 7.0);
|
||
word(&mut v, "cat", 80.0, 10.0, 7.0);
|
||
word(&mut v, "Cats", 110.0, 10.0, 7.0);
|
||
word(&mut v, "cat.", 150.0, 10.0, 7.0);
|
||
let page = layout(v);
|
||
let text = page.plain_text();
|
||
assert_eq!(text, "İSTANBUL cat Cats cat.");
|
||
for (needle, case, whole) in
|
||
[("cat", false, false), ("cat", true, false), ("cat", false, true), ("istanbul cat", false, false), ("CATS", true, true)]
|
||
{
|
||
let glyphs: Vec<String> = page.find_opts(needle, case, whole).into_iter().map(|r| page.text_of(r)).collect();
|
||
let bytes: Vec<&str> = find_in_text(&text, needle, case, whole, usize::MAX).into_iter().filter_map(|r| text.get(r)).collect();
|
||
assert_eq!(glyphs, bytes, "{needle:?} case {case} whole {whole}");
|
||
}
|
||
assert_eq!(find_in_text(&text, "cat", false, true, usize::MAX), vec![10..13, 19..22]);
|
||
assert_eq!(find_in_text(&text, "istanbul", false, false, usize::MAX), vec![0..9], "İ is two bytes");
|
||
assert_eq!(find_in_text("a\n b", "a b", false, false, usize::MAX), vec![0..5], "any whitespace run is one space");
|
||
assert_eq!(find_in_text("cat cat", "cat", false, false, 1), vec![0..3]);
|
||
assert!(find_in_text("cat", " ", false, false, usize::MAX).is_empty());
|
||
assert!(find_in_text("cat", "cat", false, false, 0).is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn greek_sigma_forms_match_without_changing_exact_search_or_glyph_ranges() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "κόσμος", 10.0, 10.0, 7.0);
|
||
word(&mut v, "ΚΌΣΜΟΣ", 80.0, 10.0, 7.0);
|
||
word(&mut v, "σςΣ", 150.0, 10.0, 7.0);
|
||
let text = layout(v);
|
||
assert_eq!(text.plain_text(), "κόσμος ΚΌΣΜΟΣ σςΣ");
|
||
for query in ["κόσμος", "ΚΌΣΜΟΣ"] {
|
||
assert_eq!(text.find(query), vec![0..6, 6..12]);
|
||
assert_eq!(text.find_opts(query, false, true), vec![0..6, 6..12]);
|
||
}
|
||
for query in ["σ", "ς", "Σ"] {
|
||
assert_eq!(text.find(query), vec![2..3, 5..6, 8..9, 11..12, 12..13, 13..14, 14..15]);
|
||
assert!(text.find_opts(query, false, true).is_empty());
|
||
}
|
||
assert_eq!(text.find_opts("κόσμος", true, false), vec![0..6]);
|
||
assert_eq!(text.find_opts("ΚΌΣΜΟΣ", true, false), vec![6..12]);
|
||
assert_eq!(text.find_opts("ς", true, false), vec![5..6, 13..14]);
|
||
assert_eq!(text.find_opts_limited("ς", false, false, 2), vec![2..3, 5..6]);
|
||
assert_eq!(text.line_rects(text.find("κόσμος")[1].clone()), text.line_rects(6..12));
|
||
}
|
||
|
||
#[test]
|
||
fn case_folding_keeps_one_character_per_character() {
|
||
for s in ["İSTANBUL", "ırmak", "Hello WORLD", "ÇAĞLAR", "Straße", "ΣΟΦΙΑ", "Σσς", "日本語"] {
|
||
assert_eq!(fold_case(s).chars().count(), s.chars().count(), "{s}");
|
||
}
|
||
assert_eq!(fold_case("Hello WORLD"), "hello world");
|
||
assert_eq!(fold_case("ÇAĞLAR Şişli"), "çağlar şişli");
|
||
assert_eq!(fold_case("İIıi"), "iiii");
|
||
assert_eq!(fold_case("Σσς"), "σσσ");
|
||
}
|
||
|
||
fn g(t: &str, x0: f32, y0: f32, x1: f32) -> TextGlyph {
|
||
let rect = [x0, y0, x1, y0 + 10.0];
|
||
TextGlyph { text: t.into(), rect, quad: [[x0, y0], [x1, y0], [x1, rect[3]], [x0, rect[3]]], direction: [1.0, 0.0] }
|
||
}
|
||
|
||
/// A glyph whose em box is `w` × `h` at `origin`, advancing along `dir` with its up edge along
|
||
/// `up` (a unit step of each), as a sheared or turned text matrix draws it.
|
||
fn tilted(t: &str, origin: [f32; 2], dir: [f32; 2], up: [f32; 2], w: f32, h: f32) -> TextGlyph {
|
||
let p = |a: f32, b: f32| [origin[0] + dir[0] * a + up[0] * b, origin[1] + dir[1] * a + up[1] * b];
|
||
let quad = [p(0.0, 0.0), p(w, 0.0), p(w, h), p(0.0, h)];
|
||
let xs = quad.map(|q| q[0]);
|
||
let ys = quad.map(|q| q[1]);
|
||
let rect = [
|
||
xs.iter().copied().fold(f32::MAX, f32::min),
|
||
ys.iter().copied().fold(f32::MAX, f32::min),
|
||
xs.iter().copied().fold(f32::MIN, f32::max),
|
||
ys.iter().copied().fold(f32::MIN, f32::max),
|
||
];
|
||
TextGlyph { text: t.into(), rect, quad, direction: dir }
|
||
}
|
||
|
||
/// #3693: pointing at the middle of a glyph in sheared or turned text finds that glyph, not
|
||
/// the one before it whose bounding box overlaps it.
|
||
#[test]
|
||
fn nearest_finds_the_glyph_under_the_pointer_in_sheared_and_turned_text() {
|
||
let s = std::f32::consts::FRAC_1_SQRT_2;
|
||
// (writing direction, up edge) in view space (y down): upright, sheared 0.35, turned 45°.
|
||
for (dir, up) in [([1.0, 0.0], [0.0, -1.0]), ([1.0, 0.0], [0.35, -1.0]), ([s, -s], [-s, -s])] {
|
||
let mut advance = 0.0;
|
||
let glyphs: Vec<TextGlyph> = "film in the list of tiny jilt flit"
|
||
.chars()
|
||
.map(|c| {
|
||
let w = if "filjt ".contains(c) { 3.0 } else { 6.0 };
|
||
let g = tilted(&c.to_string(), [50.0 + dir[0] * advance, 300.0 + dir[1] * advance], dir, up, w, 14.0);
|
||
advance += w;
|
||
g
|
||
})
|
||
.collect();
|
||
let t = layout(glyphs.clone());
|
||
assert_eq!(t.glyphs.len(), glyphs.len(), "layout kept every glyph");
|
||
for (i, g) in glyphs.iter().enumerate() {
|
||
let cx = g.quad.iter().map(|q| q[0]).sum::<f32>() / 4.0;
|
||
let cy = g.quad.iter().map(|q| q[1]).sum::<f32>() / 4.0;
|
||
assert_eq!(t.nearest(cx, cy), Some(i), "dir {dir:?} up {up:?}: glyph {i} ({})", g.text);
|
||
}
|
||
// Past either end of the line, the end glyph is still the nearest.
|
||
let (first, last) = (&glyphs[0], &glyphs[glyphs.len() - 1]);
|
||
assert_eq!(t.nearest(first.quad[0][0] - dir[0] * 8.0, first.quad[0][1] - dir[1] * 8.0), Some(0));
|
||
assert_eq!(t.nearest(last.quad[1][0] + dir[0] * 8.0, last.quad[1][1] + dir[1] * 8.0), Some(glyphs.len() - 1));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_degenerate_or_nan_quad_holds_no_point() {
|
||
assert!(!quad_contains(&[[1.0, 1.0]; 4], 1.0, 1.0));
|
||
assert!(!quad_contains(&[[0.0, 0.0], [1.0, 0.0], [f32::NAN, 1.0], [0.0, 1.0]], 0.5, 0.5));
|
||
assert!(quad_contains(&[[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]], 4.0, 2.0));
|
||
// Wound the other way.
|
||
assert!(quad_contains(&[[0.0, 0.0], [0.0, 4.0], [4.0, 4.0], [4.0, 0.0]], 2.0, 2.0));
|
||
}
|
||
|
||
#[test]
|
||
fn lines_words_and_search() {
|
||
// "Hello world" on line 1, "Next" on line 2.
|
||
let mut v = Vec::new();
|
||
for (i, c) in "Hello".chars().enumerate() {
|
||
v.push(g(&c.to_string(), 10.0 + i as f32 * 6.0, 10.0, 16.0 + i as f32 * 6.0));
|
||
}
|
||
for (i, c) in "world".chars().enumerate() {
|
||
v.push(g(&c.to_string(), 50.0 + i as f32 * 6.0, 10.0, 56.0 + i as f32 * 6.0));
|
||
}
|
||
for (i, c) in "Next".chars().enumerate() {
|
||
v.push(g(&c.to_string(), 10.0 + i as f32 * 6.0, 30.0, 16.0 + i as f32 * 6.0));
|
||
}
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text(), "Hello world\nNext");
|
||
assert_eq!(t.find("WORLD next"), vec![5..14]);
|
||
assert_eq!(t.find("o"), vec![4..5, 6..7]);
|
||
assert_eq!(t.line_rects(3..12).len(), 2);
|
||
assert_eq!(t.nearest(52.0, 14.0), Some(5));
|
||
}
|
||
|
||
/// #1315: a custom match that ends on a reconstructed word or line separator does not take
|
||
/// the following glyph.
|
||
#[test]
|
||
fn a_match_ending_on_a_separator_stops_before_the_next_glyph() {
|
||
let glyphs: Vec<TextGlyph> = "quickbrown"
|
||
.chars()
|
||
.enumerate()
|
||
.map(|(i, c)| {
|
||
let x = i as f32 * 6.0;
|
||
g(&c.to_string(), x, 0.0, x + 6.0)
|
||
})
|
||
.collect();
|
||
for line_break in [false, true] {
|
||
let mut space_before = vec![false; 10];
|
||
space_before[5] = !line_break;
|
||
let line_of = (0..10).map(|i| u32::from(line_break && i >= 5)).collect();
|
||
let page = PageText { glyphs: glyphs.clone(), line_of, space_before, truncated: false };
|
||
let plain = if line_break { "quick\nbrown" } else { "quick brown" };
|
||
assert_eq!(page.plain_text(), plain);
|
||
assert_eq!(page.find("quick "), vec![0..5]);
|
||
let span = |r: std::ops::Range<usize>| Vec::from([r]);
|
||
assert_eq!(page.find_with(|_| span(0..5)), vec![0..5]);
|
||
assert_eq!(page.find_with(|_| span(5..11)), vec![5..10]);
|
||
assert_eq!(page.find_with(|_| span(6..11)), vec![5..10]);
|
||
let hits = page.find_with(|_| span(0..6));
|
||
assert_eq!(page.text_of(hits[0].clone()), "quick");
|
||
assert_eq!(hits, vec![0..5]);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn phrase_search_ignores_repeated_spaces() {
|
||
// "quick brown" drawn with two space glyphs in a row. Text extraction keeps both spaces,
|
||
// but the phrase search has always collapsed runs of whitespace in the query, so the page
|
||
// text has to be collapsed the same way or the phrase is never found (#814).
|
||
let mut v = Vec::new();
|
||
word(&mut v, "quick", 10.0, 10.0, 6.0);
|
||
v.push(g(" ", 46.0, 10.0, 52.0));
|
||
v.push(g(" ", 52.0, 10.0, 58.0));
|
||
word(&mut v, "brown", 58.0, 10.0, 6.0);
|
||
let n = v.len();
|
||
let t = PageText { glyphs: v, line_of: vec![0; n], space_before: vec![false; n], truncated: false };
|
||
assert_eq!(t.plain_text(), "quick brown");
|
||
assert_eq!(t.find("quick brown"), vec![0..12]);
|
||
assert_eq!(t.find("quick brown"), vec![0..12], "the query's own run of spaces is collapsed too");
|
||
assert_eq!(t.find("quick\tbrown"), vec![0..12]);
|
||
assert_eq!(t.find("quick"), vec![0..5]);
|
||
assert_eq!(t.find("brown"), vec![7..12]);
|
||
assert_eq!(t.find_opts_limited("o", false, false, 0), Vec::new());
|
||
assert!(t.find("quick absent").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn limited_search_stops_after_the_requested_matches() {
|
||
let mut glyphs = Vec::new();
|
||
word(&mut glyphs, "oooo", 10.0, 10.0, 6.0);
|
||
let text = layout(glyphs);
|
||
assert_eq!(text.find_opts_limited("o", false, false, 2), vec![0..1, 1..2]);
|
||
assert_eq!(text.find_opts_limited("o", false, false, 10), vec![0..1, 1..2, 2..3, 3..4]);
|
||
}
|
||
|
||
fn tall(t: &str, x0: f32, y0: f32, x1: f32, h: f32) -> TextGlyph {
|
||
let rect = [x0, y0, x1, y0 + h];
|
||
TextGlyph { text: t.into(), rect, quad: [[x0, y0], [x1, y0], [x1, rect[3]], [x0, rect[3]]], direction: [1.0, 0.0] }
|
||
}
|
||
|
||
/// #3172: blanks drawn over big digits must not show inside the number, and the word gap next to big digits follows
|
||
/// the glyphs it lies between.
|
||
#[test]
|
||
fn blanks_under_a_number_and_a_word_gap_next_to_big_digits() {
|
||
// Big dark digits, then a smaller sentence drawn over them with blanks where the digits sit.
|
||
let mut v = Vec::new();
|
||
for (t, x) in [("5", 0.0), ("0", 6.0), ("1", 100.0), ("4", 106.0)] {
|
||
v.push(tall(t, x, 3.0, x + 6.0, 34.0));
|
||
}
|
||
for (t, x) in [("F", 16.5), ("R", 22.5), (" ", 100.0), (" ", 106.0), ("C", 130.0), ("D", 136.0)] {
|
||
v.push(tall(t, x, 6.0, x + 6.0, 28.0));
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "50 FR 14 CD");
|
||
}
|
||
|
||
/// #3172: a word break on the covered blank that opens an overprinted run moves to the run's next glyph.
|
||
#[test]
|
||
fn a_covered_leading_blank_keeps_the_word_break_of_its_run() {
|
||
let v = vec![
|
||
g("1", 0.0, 10.0, 6.0),
|
||
// " X" drawn over the "1": the blank is covered, and "X" sits right behind it.
|
||
g(" ", 0.0, 10.0, 6.0),
|
||
g("X", 6.0, 10.0, 12.0),
|
||
];
|
||
assert_eq!(layout(v).plain_text(), "1 X");
|
||
}
|
||
|
||
/// #3172: a superscript keeps the line's word-gap threshold, not its own smaller height's, so a small gap before it is
|
||
/// no word break.
|
||
#[test]
|
||
fn a_superscript_close_to_its_host_takes_no_space() {
|
||
let v = vec![g("a", 0.0, 10.0, 6.0), g("x", 6.0, 10.0, 12.0), tall("2", 13.2, 7.0, 16.8, 6.0)];
|
||
assert_eq!(layout(v).plain_text(), "ax2");
|
||
}
|
||
|
||
/// #3172: a combining mark is measured by its cluster's base. Its own small box would shrink the word-gap threshold
|
||
/// next to it, so a close letter after "á" read as a new word (noted in review).
|
||
#[test]
|
||
fn a_letter_close_after_a_combining_mark_takes_no_space() {
|
||
let v = vec![
|
||
g("x", 0.0, 10.0, 6.0),
|
||
g("a", 6.0, 10.0, 12.0),
|
||
tall("\u{301}", 10.0, 19.0, 12.0, 1.0),
|
||
g("b", 13.0, 10.0, 19.0),
|
||
g("y", 19.0, 10.0, 25.0),
|
||
];
|
||
assert_eq!(layout(v).plain_text(), "xa\u{301}by");
|
||
}
|
||
|
||
/// #3172: a superscript too small for the sub- and superscript test (under half its host's height) still keeps the
|
||
/// line's word-gap threshold next to its host: its height says no more about that gap (noted in review).
|
||
#[test]
|
||
fn a_tiny_superscript_close_to_its_host_takes_no_space() {
|
||
let v = vec![g("a", 0.0, 10.0, 6.0), g("b", 6.0, 10.0, 12.0), tall("2", 13.0, 9.5, 15.4, 4.0)];
|
||
assert_eq!(layout(v).plain_text(), "ab2");
|
||
}
|
||
|
||
/// #3172: only another run's ink drops a blank. A space its own run's letter is kerned over is still that run's word
|
||
/// break, even on a line where another run overprints elsewhere.
|
||
#[test]
|
||
fn a_blank_its_own_letters_overlap_stays_a_word_break() {
|
||
let v = vec![
|
||
// "A B" with the space pulled back under the "A", and the "B" kerned close: the space is the only word break.
|
||
g("A", 0.0, 10.0, 6.0),
|
||
g(" ", 2.0, 10.0, 8.0),
|
||
g("B", 6.5, 10.0, 12.5),
|
||
// A word far right, then a run drawn back over the "B", so the line's runs collide.
|
||
g("Q", 200.0, 10.0, 206.0),
|
||
g("1", 7.5, 10.0, 13.5),
|
||
];
|
||
let text = layout(v).plain_text();
|
||
assert!(text.starts_with("A B"), "{text:?}");
|
||
}
|
||
|
||
fn word(v: &mut Vec<TextGlyph>, s: &str, x: f32, y: f32, advance: f32) {
|
||
for (i, c) in s.chars().enumerate() {
|
||
let x0 = x + i as f32 * advance;
|
||
v.push(g(&c.to_string(), x0, y, x0 + 6.0));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn fake_bold_duplicates_are_removed() {
|
||
let mut v = Vec::new();
|
||
for (i, c) in "Bold".chars().enumerate() {
|
||
let x = 10.0 + i as f32 * 7.0;
|
||
v.push(g(&c.to_string(), x, 10.0, x + 6.0));
|
||
v.push(g(&c.to_string(), x + 0.3, 10.0, x + 6.3));
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "Bold");
|
||
// A zero-width combining mark redrawn on itself is dropped too.
|
||
let v = vec![g("e", 10.0, 10.0, 16.0), g("\u{301}", 13.0, 10.0, 13.0), g("e", 10.0, 10.0, 16.0), g("\u{301}", 13.0, 10.0, 13.0)];
|
||
assert_eq!(layout(v).plain_text(), "e\u{301}");
|
||
}
|
||
|
||
/// Text drawn once per column clip: "WO" and the `edge` glyphs, lots of other text, then the `second_pass`.
|
||
fn column_passes(edge: &[TextGlyph], second_pass: &[TextGlyph]) -> String {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "WO", 10.0, 10.0, 6.0);
|
||
v.extend_from_slice(edge);
|
||
for k in 0..50 {
|
||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||
}
|
||
v.extend_from_slice(second_pass);
|
||
layout(v).plain_text()
|
||
}
|
||
|
||
/// #3173: a page drawn once per column clip draws a glyph on the clip edge in both passes, far apart in drawing order.
|
||
#[test]
|
||
fn a_glyph_redrawn_by_the_other_column_pass_is_dropped() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "WO", 10.0, 10.0, 6.0);
|
||
v.push(g("R", 22.0, 10.0, 28.0));
|
||
word(&mut v, "illu", 10.0, 30.0, 6.0);
|
||
v.push(g("s", 34.0, 30.0, 40.0));
|
||
// The other pass: lots of other text, then the same glyphs at (almost) the same place and the rest of each word.
|
||
for k in 0..50 {
|
||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||
}
|
||
v.push(g("R", 22.0, 10.0, 28.0));
|
||
word(&mut v, "LD", 28.0, 10.0, 6.0);
|
||
v.push(g("s", 33.99, 30.0, 39.99));
|
||
word(&mut v, "trated", 40.0, 30.0, 6.0);
|
||
let text = layout(v).plain_text();
|
||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||
assert!(text.lines().any(|l| l == "illustrated"), "{text}");
|
||
}
|
||
|
||
/// #3173: the second pass draws the glyph a little taller, so its grid cell must still be the one of the first copy.
|
||
#[test]
|
||
fn a_redrawn_glyph_of_slightly_different_height_is_dropped() {
|
||
// Far from the page origin, a grid cell sized by each glyph's own height would put the two copies three cells apart.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "WO", 150.0, 150.0, 6.0);
|
||
v.push(em_box("R", 162.0, 150.0, 168.0, 160.0));
|
||
for k in 0..50 {
|
||
word(&mut v, "xx", 300.0, 200.0 + 14.0 * k as f32, 6.0);
|
||
}
|
||
v.push(em_box("R", 162.0, 150.0, 168.0, 160.3));
|
||
word(&mut v, "LD", 168.0, 150.0, 6.0);
|
||
let text = layout(v).plain_text();
|
||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||
}
|
||
|
||
/// #3173: a fake-bold copy after the last glyph of a pass does not hide that the glyph ends its run.
|
||
#[test]
|
||
fn a_fake_bold_copy_at_the_end_of_a_pass_does_not_hide_the_run_end() {
|
||
let mut second = vec![g("R", 22.0, 10.0, 28.0)];
|
||
word(&mut second, "LD", 28.0, 10.0, 6.0);
|
||
let text = column_passes(&[g("R", 22.0, 10.0, 28.0), g("R", 22.1, 10.0, 28.1)], &second);
|
||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||
}
|
||
|
||
/// A glyph redrawn five or more times in a row at its own place prints once: the copies past the
|
||
/// four-glyph window still match the kept glyph they follow.
|
||
#[test]
|
||
fn many_copies_of_a_glyph_in_a_row_print_once() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "WOR", 10.0, 10.0, 6.0);
|
||
for _ in 0..7 {
|
||
v.push(g("L", 28.0, 10.0, 34.0));
|
||
}
|
||
v.push(g("D", 34.0, 10.0, 40.0));
|
||
assert_eq!(layout(v).plain_text(), "WORLD");
|
||
}
|
||
|
||
/// #3173: the far redraw check reaches as far as a redraw may sit vertically, for a tall, narrow
|
||
/// glyph whose horizontal tolerance is much smaller than its vertical one.
|
||
#[test]
|
||
fn a_tall_narrow_glyph_redrawn_a_little_higher_is_dropped() {
|
||
let mut v = vec![em_box("|", 10.0, 100.0, 11.0, 140.0)];
|
||
for k in 0..50 {
|
||
word(&mut v, "xx", 100.0, 200.0 + 14.0 * k as f32, 6.0);
|
||
}
|
||
v.push(em_box("|", 10.0, 107.0, 11.0, 147.0));
|
||
let text = layout(v).plain_text();
|
||
assert_eq!(text.matches('|').count(), 1, "{text}");
|
||
}
|
||
|
||
/// #3173: a glyph followed by its superscript is inside a run, so a later run starting at its place is not its redraw.
|
||
#[test]
|
||
fn a_glyph_followed_by_its_superscript_is_not_a_run_end() {
|
||
let mut v = vec![em_box("H", 10.0, 10.0, 16.0, 20.0), em_box("2", 16.0, 16.0, 19.0, 22.0)];
|
||
for k in 0..50 {
|
||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||
}
|
||
v.push(em_box("H", 10.0, 10.0, 16.0, 20.0));
|
||
v.push(em_box("O", 16.0, 10.0, 22.0, 20.0));
|
||
let text = layout(v).plain_text();
|
||
assert_eq!(text.matches('H').count(), 2, "{text}");
|
||
}
|
||
|
||
/// #3173: a glyph kept in a cell does not hide the earlier glyph there that the redraw matches.
|
||
#[test]
|
||
fn a_redraw_is_matched_against_earlier_glyphs_of_the_same_cell() {
|
||
// A narrow "l" at 10 ends its line, a second one 0.8 pt to the right (more than a half of its width) is its own letter,
|
||
// and the last one, more than 4 glyphs later, redraws the first.
|
||
let v = vec![
|
||
g("l", 10.0, 10.0, 11.0),
|
||
g("Z", 200.0, 100.0, 206.0),
|
||
g("l", 10.8, 10.0, 11.8),
|
||
g("Y", 300.0, 200.0, 306.0),
|
||
g("Z", 300.0, 300.0, 306.0),
|
||
g("Y", 300.0, 400.0, 306.0),
|
||
g("Z", 300.0, 500.0, 306.0),
|
||
g("l", 10.0, 10.0, 11.0),
|
||
];
|
||
let text = layout(v).plain_text();
|
||
assert_eq!(text.matches('l').count(), 2, "{text}");
|
||
}
|
||
|
||
/// #1467: condensed text (80 Tz and below, OCR layers fitted to the scan) sets narrow letters
|
||
/// closer than a fifth of their height apart; a doubled letter there is two letters, not a redraw.
|
||
#[test]
|
||
fn condensed_double_letters_are_kept() {
|
||
for scale in [0.8, 0.65, 0.5] {
|
||
let mut v = Vec::new();
|
||
let mut x = 10.0;
|
||
// Helvetica advances at 10 pt, in thousandths of an em.
|
||
for (c, adv) in [('A', 667.0), ('l', 222.0), ('l', 222.0), ('e', 556.0)] {
|
||
let w = adv / 100.0 * scale;
|
||
v.push(g(&c.to_string(), x, 10.0, x + w));
|
||
x += w;
|
||
}
|
||
assert_eq!(layout(v.clone()).plain_text(), "Alle", "at {scale} horizontal scaling");
|
||
// Each letter redrawn a fifth of a point to the right is still one letter.
|
||
let bold: Vec<TextGlyph> = v.iter().flat_map(|c| [c.clone(), g(&c.text, c.rect[0] + 0.2, 10.0, c.rect[2] + 0.2)]).collect();
|
||
assert_eq!(layout(bold).plain_text(), "Alle", "fake bold at {scale} horizontal scaling");
|
||
}
|
||
}
|
||
|
||
/// #2457: OCR text layers squeeze each word into its box down to 20 Tz and below, where a
|
||
/// narrow letter is less than a twentieth of its height wide. Doubled letters, and letters
|
||
/// repeated two or three places on, are still letters there, not redraws.
|
||
#[test]
|
||
fn ocr_condensed_double_letters_are_kept() {
|
||
// Helvetica advances, in thousandths of an em.
|
||
let adv = |c: char| match c {
|
||
'M' => 833.0,
|
||
'K' | 'B' => 667.0,
|
||
'W' => 944.0,
|
||
'I' | 't' | 'f' => 278.0,
|
||
'i' | 'l' => 222.0,
|
||
'm' => 833.0,
|
||
'r' => 333.0,
|
||
's' => 500.0,
|
||
_ => 556.0,
|
||
};
|
||
for scale in [0.2, 0.1, 0.05] {
|
||
for word in ["Hallo", "Mitte", "Wille", "Kommission", "Illustration", "still", "Brunnen", "Kaffee"] {
|
||
let mut v = Vec::new();
|
||
let mut x = 10.0;
|
||
for c in word.chars() {
|
||
let w = adv(c) / 100.0 * scale;
|
||
v.push(g(&c.to_string(), x, 10.0, x + w));
|
||
x += w;
|
||
}
|
||
assert_eq!(layout(v.clone()).plain_text(), word, "at {scale} horizontal scaling");
|
||
// Each letter drawn twice at the same place is still one letter.
|
||
let bold: Vec<TextGlyph> = v.iter().flat_map(|c| [c.clone(), c.clone()]).collect();
|
||
assert_eq!(layout(bold).plain_text(), word, "fake bold at {scale} horizontal scaling");
|
||
// And redrawn a quarter of its own width to the right (the match reaches half of it).
|
||
let shifted: Vec<TextGlyph> = v
|
||
.iter()
|
||
.flat_map(|c| {
|
||
let d = (c.rect[2] - c.rect[0]) * 0.25;
|
||
[c.clone(), g(&c.text, c.rect[0] + d, 10.0, c.rect[2] + d)]
|
||
})
|
||
.collect();
|
||
assert_eq!(layout(shifted).plain_text(), word, "shifted fake bold at {scale} horizontal scaling");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn two_columns_read_left_then_right_even_if_drawn_interleaved() {
|
||
let mut v = Vec::new();
|
||
// Drawn row by row across both columns, as some producers do.
|
||
word(&mut v, "Left1", 10.0, 10.0, 6.0);
|
||
word(&mut v, "Right1", 200.0, 10.0, 6.0);
|
||
word(&mut v, "Left2", 10.0, 24.0, 6.0);
|
||
word(&mut v, "Right2", 200.0, 24.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text(), "Left1\nLeft2\nRight1\nRight2");
|
||
}
|
||
|
||
/// Runs on one baseline read as one line, left to right, with a space at the gap between them, however they were
|
||
/// drawn and whatever their sizes. Columns of several lines still read one after the other.
|
||
#[test]
|
||
fn runs_on_one_baseline_read_as_one_line_in_any_drawing_order() {
|
||
// Glyphs of `h` pt on the baseline `base`, 0.6 em apart.
|
||
let sized = |v: &mut Vec<TextGlyph>, s: &str, x: f32, base: f32, h: f32| {
|
||
for (i, c) in s.chars().enumerate() {
|
||
let x0 = x + i as f32 * h * 0.6;
|
||
v.push(em_box(&c.to_string(), x0, base - 0.8 * h, x0 + h * 0.6, base + 0.2 * h));
|
||
}
|
||
};
|
||
// The second word drawn first, three and a half heights to the right of the first.
|
||
let mut v = Vec::new();
|
||
sized(&mut v, "second", 160.0, 100.0, 14.0);
|
||
sized(&mut v, "first", 90.0, 100.0, 14.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text(), "first second");
|
||
assert_eq!(t.line_rects(0..t.glyphs.len()).len(), 1, "one line, one highlight");
|
||
// A 9 pt label, a 14 pt word and a 9 pt note on one baseline.
|
||
let mut v = Vec::new();
|
||
sized(&mut v, "11", 40.0, 100.0, 9.0);
|
||
sized(&mut v, "hidden", 90.0, 100.0, 14.0);
|
||
sized(&mut v, "note", 170.0, 100.0, 9.0);
|
||
assert_eq!(layout(v).plain_text(), "11 hidden note");
|
||
// A label beside two columns of two lines: the label joins the first line of the left column, and the
|
||
// columns keep their own lines.
|
||
let mut v = Vec::new();
|
||
sized(&mut v, "07", 40.0, 100.0, 9.0);
|
||
sized(&mut v, "leftone", 90.0, 100.0, 12.0);
|
||
sized(&mut v, "lefttwo", 90.0, 114.0, 12.0);
|
||
sized(&mut v, "rightone", 300.0, 100.0, 12.0);
|
||
sized(&mut v, "righttwo", 300.0, 114.0, 12.0);
|
||
assert_eq!(layout(v).plain_text(), "07 leftone\nlefttwo\nrightone\nrighttwo");
|
||
// Two columns of prose 20 pt apart, where a one-line paragraph that fills the left column shares its baseline
|
||
// with the first line of a paragraph in the right one: the paragraph is the next column, not the line's value.
|
||
let mut v = Vec::new();
|
||
for (k, y) in [100.0, 112.0, 124.0].iter().enumerate() {
|
||
sized(&mut v, &format!("leftparagraphlinenumber{k}xxxxxxxxxxxxxxx"), 72.0, *y, 10.0);
|
||
}
|
||
sized(&mut v, "leftlastonelinexxxxxxxxxxxxxxxxxxxxxxxx", 72.0, 160.0, 10.0);
|
||
for (k, y) in [100.0, 112.0, 124.0].iter().enumerate() {
|
||
sized(&mut v, &format!("rightparagraphline{k}"), 326.0, *y, 10.0);
|
||
}
|
||
sized(&mut v, "rightsecondpara", 326.0, 160.0, 10.0);
|
||
sized(&mut v, "rightsecondparaline2", 326.0, 172.0, 10.0);
|
||
let t = layout(v).plain_text();
|
||
assert!(t.lines().any(|l| l == "leftlastonelinexxxxxxxxxxxxxxxxxxxxxxxx"), "{t}");
|
||
assert!(t.lines().any(|l| l == "rightsecondpara"), "{t}");
|
||
// Staggered columns (review on #4468): the left column's short last line shares its baseline with
|
||
// the right column's first line. That last line is no label, so the columns keep their lines.
|
||
let mut v = Vec::new();
|
||
sized(&mut v, "leftcol1", 10.0, 100.0, 10.0);
|
||
sized(&mut v, "leftcol2", 10.0, 112.0, 10.0);
|
||
sized(&mut v, "end", 10.0, 124.0, 10.0);
|
||
sized(&mut v, "rightone", 82.0, 124.0, 10.0);
|
||
sized(&mut v, "righttwo", 82.0, 136.0, 10.0);
|
||
assert_eq!(layout(v).plain_text(), "leftcol1\nleftcol2\nend\nrightone\nrighttwo");
|
||
// Half a height lower is another line.
|
||
let mut v = Vec::new();
|
||
sized(&mut v, "first", 90.0, 100.0, 14.0);
|
||
sized(&mut v, "lower", 160.0, 107.0, 14.0);
|
||
assert_eq!(layout(v).plain_text(), "first\nlower");
|
||
// Right-to-left runs on one baseline keep their lines: their blocks read left first.
|
||
let mut v = Vec::new();
|
||
sized(&mut v, "שלום", 90.0, 100.0, 14.0);
|
||
sized(&mut v, "עולם", 200.0, 100.0, 14.0);
|
||
assert_eq!(layout(v).plain_text().lines().count(), 2);
|
||
}
|
||
|
||
/// A page of fourteen labelled rows, each a case of text copy: a `/fi` glyph by name, a ToUnicode map, an
|
||
/// `/ActualText` span, word gaps by `TJ` and `Td`, a hyphen at a line end, two columns, words drawn out of order,
|
||
/// fake bold, invisible text, letter spacing and a line turned upwards.
|
||
fn copy_test_page() -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let rows: [(&str, &str); 14] = [
|
||
("01", "BT /F2 14 Tf 90 {Y} Td (of\\200ce) Tj ET"),
|
||
("02", "BT /F3 14 Tf 90 {Y} Td (XEY) Tj ET"),
|
||
("03", "/Span << /ActualText (replaced) >> BDC BT /F1 14 Tf 90 {Y} Td (shown) Tj ET EMC"),
|
||
("04", "BT /F1 14 Tf 90 {Y} Td [(Hello) -400 (world)] TJ ET"),
|
||
("05", "BT /F1 14 Tf 90 {Y} Td [(W) 80 (ave)] TJ ET"),
|
||
("06", "BT /F1 14 Tf 90 {Y} Td (exam-) Tj 0 -16 Td (ple) Tj ET"),
|
||
("07", "BT /F1 12 Tf 90 {Y} Td (left one) Tj 0 -14 Td (left two) Tj ET BT /F1 12 Tf 300 {Y} Td (right one) Tj 0 -14 Td (right two) Tj ET"),
|
||
("08", "BT /F1 14 Tf 160 {Y} Td (second) Tj ET BT /F1 14 Tf 90 {Y} Td (first) Tj ET"),
|
||
("09", "BT /F1 14 Tf 90 {Y} Td (caf\\351 na\\357ve) Tj ET"),
|
||
("10", "BT /F1 14 Tf 90 {Y} Td (Bold) Tj ET BT /F1 14 Tf 90.4 {Y} Td (Bold) Tj ET"),
|
||
("11", "BT /F1 14 Tf 3 Tr 90 {Y} Td (hidden) Tj ET BT /F1 9 Tf 0.5 g 160 {Y} Td (<- invisible word here) Tj ET"),
|
||
("12", "BT /F1 14 Tf 8 Tc 90 {Y} Td (SPACED) Tj ET"),
|
||
("13", "BT /F1 14 Tf 0 1 -1 0 110 {Y} Tm (up) Tj ET"),
|
||
("14", "BT /F1 14 Tf 90 {Y} Td (split) Tj 40 0 Td (words) Tj ET"),
|
||
];
|
||
let mut content = String::from("BT /F1 9 Tf 40 770 Td (Text copy and search test) Tj ET\n");
|
||
let mut y = 740;
|
||
for (tag, body) in rows {
|
||
content += &format!("BT /F1 9 Tf 0.4 g 40 {y} Td ({tag}) Tj ET 0 g\nq {} Q\n", body.replace("{Y}", &y.to_string()));
|
||
y -= 38
|
||
+ match tag {
|
||
"06" | "13" => 10,
|
||
"07" => 6,
|
||
_ => 0,
|
||
};
|
||
}
|
||
let mut doc = Document::with_version("1.7");
|
||
let helvetica = || dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding" };
|
||
let f1 = doc.add_object(helvetica());
|
||
let differences = dictionary! { "Type" => "Encoding", "BaseEncoding" => "WinAnsiEncoding", "Differences" => vec![Object::Integer(128), Object::Name(b"fi".to_vec())] };
|
||
let f2 = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => differences });
|
||
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Test-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 3 beginbfchar <58> <004B> <45> <0045> <59> <0059> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
let to_unicode = doc.add_object(Stream::new(dictionary! {}, cmap.as_bytes().to_vec()));
|
||
let mut f3 = helvetica();
|
||
f3.set("ToUnicode", to_unicode);
|
||
let f3 = doc.add_object(f3);
|
||
let contents = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! {
|
||
"Type" => "Page", "Parent" => pages, "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
|
||
"Resources" => dictionary! { "Font" => dictionary! { "F1" => f1, "F2" => f2, "F3" => f3 } }, "Contents" => contents
|
||
});
|
||
doc.objects.insert(pages, dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1 }.into());
|
||
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
/// Copy of the whole page: one line per baseline in left-to-right order whatever the drawing order, the `/fi`
|
||
/// glyph as its letters, and the line turned upwards in its row, not after the page. `/ActualText` replaces what
|
||
/// is drawn (ISO 32000-2 §14.9.4), a hard hyphen at a line end stays (§14.8.2.3: an incidental one is U+00AD),
|
||
/// fake bold reads once, and letter spacing that is the same between every letter is tracking, not word gaps.
|
||
#[test]
|
||
fn a_copied_page_reads_one_line_per_baseline_in_reading_order() {
|
||
let text = extract_page(©_test_page(), 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(
|
||
text.plain_text(),
|
||
"Text copy and search test\n01 office\n02 KEY\n03 replaced\n04 Hello world\n05 Wave\n06 exam-\nple\n07 left one\nleft two\n\
|
||
right one\nright two\n08 first second\n09 café naïve\n10 Bold\n11 hidden <- invisible word here\n12 SPACED\n13\nup\n14 split words"
|
||
);
|
||
assert_eq!(text.find("first second").len(), 1);
|
||
assert_eq!(text.find("office").len(), 1);
|
||
}
|
||
|
||
/// A turned line inside the page's text reads where it stands; one in the margin, beside every line (a stamp
|
||
/// set up the edge of the page), still reads after the text instead of splitting a paragraph.
|
||
#[test]
|
||
fn a_turned_line_reads_in_place_inside_the_text_and_after_it_in_the_margin() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let page = |before: &str, after: &str| {
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let mut content = before.to_owned();
|
||
for (k, word) in ["Alpha", "Beta", "Gamma", "Delta"].iter().enumerate() {
|
||
content += &format!("BT /F1 12 Tf 72 {} Td ({word}) Tj ET\n", 700 - 30 * k);
|
||
}
|
||
content += after;
|
||
let contents = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! {
|
||
"Type" => "Page", "Parent" => pages, "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
|
||
"Resources" => dictionary! { "Font" => dictionary! { "F1" => font } }, "Contents" => contents
|
||
});
|
||
doc.objects.insert(pages, dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1 }.into());
|
||
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text()
|
||
};
|
||
// "up", set upwards from the baseline of "Beta" beside it, and "dn", set downwards in the space under it.
|
||
let up = "BT /F1 12 Tf 0 1 -1 0 110 670 Tm (up) Tj ET\n";
|
||
let down = "BT /F1 8 Tf 0 -1 1 0 100 662 Tm (dn) Tj ET\n";
|
||
assert_eq!(page("", up), "Alpha\nBeta\nup\nGamma\nDelta");
|
||
assert_eq!(page(up, ""), "Alpha\nBeta\nup\nGamma\nDelta", "drawn before the text");
|
||
assert_eq!(page("", down), "Alpha\nBeta\ndn\nGamma\nDelta");
|
||
// Upside-down text inside the text's area, under "Beta", is not turned a quarter and keeps its own flow.
|
||
let upside_down = "BT /F1 12 Tf -1 0 0 -1 110 660 Tm (ud) Tj ET\n";
|
||
assert_eq!(page("", upside_down), "Alpha\nBeta\nGamma\nDelta\nud");
|
||
// A stamp up the left margin, beside "Beta" and "Gamma": laid out with the text, it would read after "Alpha".
|
||
let stamp = "BT /F1 10 Tf 0 1 -1 0 30 640 Tm (arXiv stamp) Tj ET\n";
|
||
assert_eq!(page("", stamp), "Alpha\nBeta\nGamma\nDelta\narXiv stamp");
|
||
}
|
||
|
||
#[test]
|
||
fn ligature_characters_read_as_their_letters() {
|
||
assert_eq!(ligature_letters("o\u{FB01}ce".into()), "ofice");
|
||
assert_eq!(ligature_letters("\u{FB00}\u{FB02}\u{FB03}\u{FB04}\u{FB05}\u{FB06}".into()), "ffflffifflstst");
|
||
// Only those seven: other compatibility characters stay as they are.
|
||
assert_eq!(ligature_letters("\u{FB13}\u{FF21}\u{2460}é".into()), "\u{FB13}\u{FF21}\u{2460}é");
|
||
assert_eq!(ligature_letters(String::new()), "");
|
||
}
|
||
|
||
/// Lays out one-word lines, each `(text, x, y)`, 10 pt high: 14 pt apart is a line in a paragraph, 24 pt a
|
||
/// paragraph gap.
|
||
fn lines(at: &[(&str, f32, f32)]) -> String {
|
||
let mut v = Vec::new();
|
||
for &(s, x, y) in at {
|
||
word(&mut v, s, x, y, 6.0);
|
||
}
|
||
layout(v).plain_text()
|
||
}
|
||
|
||
#[test]
|
||
fn a_column_reads_on_past_a_paragraph_gap() {
|
||
// #3658: a heading and paragraph A at the top of the left column, a paragraph gap, then paragraph B, which
|
||
// goes on at the top of the right column, and paragraph C below it.
|
||
let two = [
|
||
("Heading", 10.0, 10.0),
|
||
("A1", 10.0, 30.0),
|
||
("A2", 10.0, 44.0),
|
||
("A3", 10.0, 58.0),
|
||
("B1", 10.0, 82.0),
|
||
("B2", 10.0, 96.0),
|
||
("B3", 200.0, 30.0),
|
||
("B4", 200.0, 44.0),
|
||
("C1", 200.0, 68.0),
|
||
("C2", 200.0, 82.0),
|
||
];
|
||
assert_eq!(lines(&two), "Heading\nA1\nA2\nA3\nB1\nB2\nB3\nB4\nC1\nC2");
|
||
// Three columns, each with a gap at a different height.
|
||
let three = [
|
||
("A1", 10.0, 10.0),
|
||
("A2", 10.0, 24.0),
|
||
("B1", 10.0, 48.0),
|
||
("C1", 150.0, 10.0),
|
||
("D1", 150.0, 38.0),
|
||
("D2", 150.0, 52.0),
|
||
("E1", 290.0, 10.0),
|
||
("E2", 290.0, 24.0),
|
||
("E3", 290.0, 38.0),
|
||
("F1", 290.0, 62.0),
|
||
];
|
||
assert_eq!(lines(&three), "A1\nA2\nB1\nC1\nD1\nD2\nE1\nE2\nE3\nF1");
|
||
}
|
||
|
||
#[test]
|
||
fn a_column_reads_on_past_a_line_that_only_touches_it() {
|
||
// The #3658 page with a right-column paragraph whose first line touches B1's by 1 pt or 0.1 pt, or whose
|
||
// second line carries a 6 pt footnote marker reaching up beside B2: none of them is a row with B1.
|
||
let page = |extra: &[(&str, f32, f32, f32)]| {
|
||
let mut v = Vec::new();
|
||
let left = [("H", 10.0, 10.0), ("A1", 10.0, 30.0), ("A2", 10.0, 44.0), ("A3", 10.0, 58.0), ("B1", 10.0, 82.0), ("B2", 10.0, 96.0)];
|
||
for &(s, x, y) in left.iter().chain(&[("R1", 200.0, 30.0), ("R2", 200.0, 44.0)]) {
|
||
word(&mut v, s, x, y, 6.0);
|
||
}
|
||
for &(s, x, y, h) in extra {
|
||
for (i, c) in s.chars().enumerate() {
|
||
let x0 = x + i as f32 * h * 0.6;
|
||
v.push(em_box(&c.to_string(), x0, y, x0 + h * 0.6, y + h));
|
||
}
|
||
}
|
||
layout(v).plain_text().replace('\n', " ")
|
||
};
|
||
assert_eq!(page(&[("S1", 200.0, 91.0, 10.0), ("S2", 200.0, 105.0, 10.0)]), "H A1 A2 A3 B1 B2 R1 R2 S1 S2", "1 pt touch");
|
||
assert_eq!(page(&[("S1", 200.0, 72.1, 10.0), ("S2", 200.0, 86.1, 10.0)]), "H A1 A2 A3 B1 B2 R1 R2 S1 S2", "0.1 pt touch");
|
||
let marker = page(&[("S1", 200.0, 68.0, 10.0), ("x", 200.0, 96.0, 10.0), ("9", 206.5, 90.0, 6.0), ("S2y", 214.0, 96.0, 10.0)]);
|
||
assert!(marker.starts_with("H A1 A2 A3 B1 B2 R1 R2 S1 "), "footnote marker: {marker}");
|
||
}
|
||
|
||
#[test]
|
||
fn a_full_width_line_ends_the_columns_above_it() {
|
||
// Two columns, a full-width heading, two more columns and a full-width footnote. The left column stops at the
|
||
// heading and the footnote: the right column above each one reads first.
|
||
let page = [
|
||
("L1", 10.0, 10.0),
|
||
("L2", 10.0, 24.0),
|
||
("L3", 10.0, 48.0),
|
||
("R1", 200.0, 10.0),
|
||
("R2", 200.0, 38.0),
|
||
("Fullwidthheading", 10.0, 80.0),
|
||
("L4", 10.0, 110.0),
|
||
("L5", 10.0, 124.0),
|
||
("L6", 10.0, 148.0),
|
||
("R3", 200.0, 110.0),
|
||
("R4", 200.0, 138.0),
|
||
("Fullwidthfootnote", 10.0, 200.0),
|
||
];
|
||
// The two full-width lines run past the right column (x = 286 and 304) at 18 pt a letter.
|
||
let mut v = Vec::new();
|
||
for &(s, x, y) in &page {
|
||
word(&mut v, s, x, y, if s.len() > 2 { 18.0 } else { 6.0 });
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "L1\nL2\nL3\nR1\nR2\nFullwidthheading\nL4\nL5\nL6\nR3\nR4\nFullwidthfootnote");
|
||
}
|
||
|
||
#[test]
|
||
fn table_rows_apart_still_read_across() {
|
||
// Rows a paragraph gap apart whose cells start level read row by row, as before #3658.
|
||
let rows = [("Name", 10.0, 10.0), ("Qty", 100.0, 10.0), ("Apple", 10.0, 34.0), ("12", 100.0, 34.0), ("Pear", 10.0, 58.0), ("7", 100.0, 58.0)];
|
||
// The cells of a row share its baseline, so they share a line too.
|
||
assert_eq!(lines(&rows), "Name Qty\nApple 12\nPear 7");
|
||
// Column select still separates them with a tab.
|
||
let mut v = Vec::new();
|
||
for &(s, x, y) in &rows {
|
||
word(&mut v, s, x, y, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
assert_eq!(t.column_text(&t.glyphs_in([0.0, 0.0, 300.0, 300.0])), "Name\tQty\nApple\t12\nPear\t7");
|
||
}
|
||
|
||
/// Two cells two heights apart (closer than [`CELL_GAP`]) copy the same whichever is drawn first:
|
||
/// drawn left to right they were always one run, and the right cell drawn first now joins it too.
|
||
#[test]
|
||
fn close_cells_copy_the_same_in_either_drawing_order() {
|
||
let copy = |cells: &[(&str, f32)]| {
|
||
let mut v = Vec::new();
|
||
for &(s, x) in cells {
|
||
word(&mut v, s, x, 10.0, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
(t.plain_text(), t.column_text(&t.glyphs_in([0.0, 0.0, 300.0, 300.0])))
|
||
};
|
||
let in_order = copy(&[("Name", 10.0), ("Qty", 54.0)]);
|
||
assert_eq!(copy(&[("Qty", 54.0), ("Name", 10.0)]), in_order);
|
||
assert_eq!(in_order.0, "Name Qty");
|
||
}
|
||
|
||
#[test]
|
||
fn form_rows_in_mixed_sizes_still_read_across() {
|
||
// 8 pt labels beside 12 pt values on one baseline, rows 30 pt apart: the tops differ by 4 pt, but the first
|
||
// lines overlap, so each row reads label then value.
|
||
let mut v = Vec::new();
|
||
let sized = |v: &mut Vec<TextGlyph>, s: &str, x: f32, base: f32, h: f32| {
|
||
for (i, c) in s.chars().enumerate() {
|
||
let x0 = x + i as f32 * h * 0.6;
|
||
v.push(em_box(&c.to_string(), x0, base - h, x0 + h * 0.6, base));
|
||
}
|
||
};
|
||
for (i, (label, value)) in [("Name", "Alice"), ("Street", "Main"), ("City", "Oslo")].into_iter().enumerate() {
|
||
let base = 20.0 + 30.0 * i as f32;
|
||
sized(&mut v, label, 10.0, base, 8.0);
|
||
sized(&mut v, value, 100.0, base, 12.0);
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "Name Alice\nStreet Main\nCity Oslo");
|
||
// Values drawn 6 pt below their labels, rows a paragraph gap apart.
|
||
let offset =
|
||
[("Name", 10.0, 10.0), ("Val1", 100.0, 16.0), ("Addr", 10.0, 40.0), ("Val2", 100.0, 46.0), ("City", 10.0, 70.0), ("Val3", 100.0, 76.0)];
|
||
assert_eq!(lines(&offset), "Name\nVal1\nAddr\nVal2\nCity\nVal3");
|
||
}
|
||
|
||
#[test]
|
||
fn a_column_does_not_jump_to_a_distant_footer_footnote_or_caption() {
|
||
// A page number far below the left column reads after the right column. L3 and R3, one-line paragraphs
|
||
// on one baseline a column apart, keep their own lines.
|
||
let footer = [
|
||
("L1", 10.0, 10.0),
|
||
("L2", 10.0, 24.0),
|
||
("L3", 10.0, 48.0),
|
||
("R1", 200.0, 10.0),
|
||
("R2", 200.0, 24.0),
|
||
("R3", 200.0, 48.0),
|
||
("Pg7", 10.0, 400.0),
|
||
];
|
||
assert_eq!(lines(&footer), "L1\nL2\nR1\nR2\nL3\nR3\nPg7");
|
||
// So does a footnote under the left column only, with the page number under the right one.
|
||
let footnote = [
|
||
("L1", 10.0, 10.0),
|
||
("L2", 10.0, 24.0),
|
||
("L3", 10.0, 48.0),
|
||
("R1", 200.0, 10.0),
|
||
("R2", 200.0, 24.0),
|
||
("R3", 200.0, 48.0),
|
||
("Note", 10.0, 380.0),
|
||
("Pg7", 200.0, 400.0),
|
||
];
|
||
assert_eq!(lines(&footnote), "L1\nL2\nR1\nR2\nL3\nR3\nNote\nPg7");
|
||
// A caption under a full-width figure (no text from 70 to 250), as narrow as the left column, reads after both
|
||
// columns above the figure and before the columns below it.
|
||
let caption = [
|
||
("L1", 10.0, 10.0),
|
||
("L2", 10.0, 24.0),
|
||
("L3", 10.0, 38.0),
|
||
("R1", 200.0, 10.0),
|
||
("R2", 200.0, 24.0),
|
||
("R3", 200.0, 38.0),
|
||
("Cap", 10.0, 260.0),
|
||
("M1", 10.0, 290.0),
|
||
("M2", 10.0, 304.0),
|
||
("N1", 200.0, 290.0),
|
||
("N2", 200.0, 304.0),
|
||
];
|
||
assert_eq!(lines(&caption), "L1\nL2\nL3\nR1\nR2\nR3\nCap\nM1\nM2\nN1\nN2");
|
||
}
|
||
|
||
#[test]
|
||
fn many_column_paragraphs_order_in_bounded_time() {
|
||
// 2000 paragraphs in two columns, the right one offset by half a paragraph: every block is a column
|
||
// continuation, and choosing each one scans the remaining blocks.
|
||
let mut v = Vec::new();
|
||
for i in 0..1000u16 {
|
||
let y = 10.0 + 24.0 * f32::from(i);
|
||
word(&mut v, "L", 10.0, y, 6.0);
|
||
word(&mut v, "R", 200.0, y + 12.0, 6.0);
|
||
}
|
||
let start = std::time::Instant::now();
|
||
let text = layout(v).plain_text();
|
||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||
// Compared without printing 4000 characters on failure.
|
||
let expected = format!("{}{}", "L\n".repeat(1000), "R\n".repeat(999) + "R");
|
||
assert!(text == expected, "the first R reads after {:?} lines, not 1000", text.find('R').map(|i| i / 2));
|
||
}
|
||
|
||
#[test]
|
||
fn tracked_text_keeps_letters_together() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "CHAPTER", 10.0, 10.0, 9.0); // 3pt tracking between 6pt-wide letters
|
||
word(&mut v, "FOUR", 10.0 + 7.0 * 9.0 + 5.0, 10.0, 9.0);
|
||
assert_eq!(layout(v).plain_text(), "CHAPTER FOUR");
|
||
}
|
||
|
||
#[test]
|
||
fn toc_leaders_do_not_hide_word_gaps() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
for dots in [0, 5, 10, 20, 40, 60] {
|
||
for (words, expected) in [
|
||
("(Was)-333(ist)-333(OTRS?)", "Was ist OTRS?"),
|
||
("(Das)-333(OTRS)-333(Web-Interface)", "Das OTRS Web-Interface"),
|
||
("(Neuen)-333(Zugang)-333(beantragen)", "Neuen Zugang beantragen"),
|
||
] {
|
||
// The issue's LaTeX TJ spacing, without embedding the corpus PDF or a font asset.
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Times-Roman" });
|
||
let operators = format!("BT /F1 10 Tf 10 100 Td [{words}-441{}-1663(7)] TJ ET", "-500(.)".repeat(dots));
|
||
let content = doc.add_object(Stream::new(dictionary! {}, operators.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! {
|
||
"Type" => "Page", "Parent" => pages,
|
||
"MediaBox" => vec![0.into(), 0.into(), 800.into(), Object::Integer(200)],
|
||
"Resources" => dictionary! { "Font" => dictionary! { "F1" => font } }, "Contents" => content
|
||
});
|
||
doc.objects.insert(pages, dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1 }.into());
|
||
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), format!("{expected} {}7", ". ".repeat(dots)), "{dots} leader dots");
|
||
let hits = text.find_opts(expected, true, true);
|
||
assert_eq!(hits.len(), 1, "{expected:?}, {dots} leader dots");
|
||
assert_eq!(text.text_of(hits[0].clone()), expected);
|
||
assert_eq!(text.line_rects(hits[0].clone()).len(), 1);
|
||
assert_eq!(text.find(&expected.to_lowercase()), hits);
|
||
assert!(text.find(&expected.replace(' ', "")).is_empty());
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn short_tracked_ellipses_remain_searchable() {
|
||
for dots in [3, 4] {
|
||
let mut v = Vec::new();
|
||
for i in 0..dots {
|
||
let x = 10.0 + i as f32 * 4.0;
|
||
v.push(g(".", x, 10.0, x + 2.0));
|
||
}
|
||
let ellipsis = ".".repeat(dots);
|
||
let text = layout(v.clone());
|
||
assert_eq!(text.plain_text(), ellipsis);
|
||
assert_eq!(text.find(&ellipsis), vec![0..dots]);
|
||
v.insert(0, g("A", 0.0, 10.0, 6.0));
|
||
let x = 12.0 + dots as f32 * 4.0;
|
||
v.push(g("B", x, 10.0, x + 6.0));
|
||
let text = layout(v);
|
||
let expected = format!("A {ellipsis} B");
|
||
assert_eq!(text.plain_text(), expected);
|
||
assert_eq!(text.find(&expected), vec![0..dots + 2]);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn leaders_preserve_tracking_in_letters_numbers_and_punctuation() {
|
||
for advance in [9.0, 12.0] {
|
||
for leader in [".", "-", "…"] {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "CHAPTER-1", 10.0, 10.0, advance);
|
||
let x = 10.0 + 9.0 * advance + 5.0;
|
||
word(&mut v, "1.4", x, 10.0, advance);
|
||
let mut x = x + 3.0 * advance + 5.0;
|
||
for _ in 0..60 {
|
||
v.push(g(leader, x, 10.0, x + 2.5));
|
||
x += 11.0;
|
||
}
|
||
let text = layout(v);
|
||
assert_eq!(text.plain_text(), format!("CHAPTER-1 1.4 {}", vec![leader; 60].join(" ")));
|
||
assert_eq!(text.find("chapter-1 1.4"), vec![0..12]);
|
||
}
|
||
}
|
||
// Decimal punctuation and repeated letters/digits still use their original tracking estimate.
|
||
for value in ["1.4", "1111", "llll"] {
|
||
let mut v = Vec::new();
|
||
word(&mut v, value, 10.0, 10.0, 12.0);
|
||
assert_eq!(layout(v).plain_text(), value);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn rtl_runs_come_out_in_logical_order_and_cjk_has_no_spaces() {
|
||
let mut v = Vec::new();
|
||
// Hebrew "שלום" drawn visually right-to-left: ם ו ל ש from left to right.
|
||
word(&mut v, "םולש", 10.0, 10.0, 6.0);
|
||
assert_eq!(layout(v).plain_text(), "שלום");
|
||
let mut v = Vec::new();
|
||
word(&mut v, "每个字", 10.0, 10.0, 9.0);
|
||
assert_eq!(layout(v).plain_text(), "每个字");
|
||
}
|
||
|
||
/// #1062: the word gap stays between the runs when the right-hand run is drawn first, and
|
||
/// between the words of a right-to-left line.
|
||
#[test]
|
||
fn word_gaps_follow_position_not_drawing_order() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "19.4", 40.0, 10.0, 6.0);
|
||
word(&mut v, "20.0", 10.0, 10.0, 6.0);
|
||
assert_eq!(layout(v).plain_text(), "20.0 19.4");
|
||
let mut v = Vec::new();
|
||
// "שלום עולם" drawn visually: עולם reversed on the left, שלום reversed on the right.
|
||
word(&mut v, "םלוע", 10.0, 10.0, 6.0);
|
||
word(&mut v, "םולש", 40.0, 10.0, 6.0);
|
||
assert_eq!(layout(v).plain_text(), "שלום עולם");
|
||
}
|
||
|
||
/// A right-to-left show string in reverse order starts with the space that ends its word, and the next letter is pulled
|
||
/// back over it (ISO 32000-2 §14.8.2.5.3): the space stays a word break after the word, not inside it (pdf.js #11656).
|
||
#[test]
|
||
fn a_space_taken_back_under_the_next_letter_stays_before_it() {
|
||
let rtl_line = |first: &str| {
|
||
// Drawn left to right: " הנידמה" with the space's advance taken back, then "רקבמ" after a word gap.
|
||
let mut v = vec![em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box(first, 9.9, 0.0, 17.5, 11.0)];
|
||
let mut x = 17.5;
|
||
for c in ["נ", "י", "ד", "מ", "ה"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
x += 3.5;
|
||
for c in ["ר", "ק", "ב", "מ"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
layout(v)
|
||
};
|
||
let text = rtl_line("ה");
|
||
assert_eq!(text.plain_text().trim_end(), "מבקר המדינה");
|
||
assert_eq!(text.find("המדינה").len(), 1);
|
||
// The same with punctuation: the question mark ends the line, with no space before it.
|
||
assert_eq!(rtl_line("?").plain_text().trim_end(), "מבקר המדינ?");
|
||
// Right-to-left text drawn letter by letter leftwards: the letter after the space ends where the space starts, a
|
||
// rounding hair over it, and stays on its left.
|
||
let mut v = Vec::new();
|
||
let mut x = 60.0;
|
||
for c in ["ש", "ל", "ו", "ם"] {
|
||
v.push(em_box(c, x - 6.0, 0.0, x, 11.0));
|
||
x -= 6.0;
|
||
}
|
||
v.push(em_box(" ", x - 3.5, 0.0, x, 11.0));
|
||
x -= 3.5;
|
||
v.push(em_box("ע", x - 6.0, 0.0, x + 0.005, 11.0));
|
||
x -= 6.0;
|
||
for c in ["ו", "ל", "ם"] {
|
||
v.push(em_box(c, x - 6.0, 0.0, x, 11.0));
|
||
x -= 6.0;
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "שלום עולם");
|
||
// A space inside a cluster, under a letter and the mark drawn on it, stays where x order puts it: before the mark.
|
||
let v = vec![
|
||
em_box("ש", 9.995, 0.0, 25.0, 11.0),
|
||
em_box(" ", 10.006, 0.0, 13.5, 11.0),
|
||
em_box("\u{5B4}", 10.003, 0.0, 12.8, 11.0),
|
||
em_box("ל", 25.0, 0.0, 31.0, 11.0),
|
||
];
|
||
assert_eq!(layout(v).plain_text(), "ל \u{5B4}ש");
|
||
// Left-to-right text has no reverse-order show strings: a space taken back there is still placed by position.
|
||
let v = vec![
|
||
em_box("a", 0.0, 0.0, 6.0, 11.0),
|
||
em_box("b", 6.0, 0.0, 12.0, 11.0),
|
||
em_box(" ", 12.0, 0.0, 15.5, 11.0),
|
||
em_box("c", 11.9, 0.0, 17.9, 11.0),
|
||
];
|
||
assert_eq!(layout(v).plain_text().trim_end(), "abc");
|
||
// A space whose advance stands is placed by position, as before.
|
||
let mut v = vec![em_box("a", 0.0, 0.0, 6.0, 11.0), em_box(" ", 6.0, 0.0, 9.5, 11.0), em_box("b", 9.5, 0.0, 15.5, 11.0)];
|
||
v.push(em_box("c", 15.5, 0.0, 21.5, 11.0));
|
||
assert_eq!(layout(v).plain_text(), "a bc");
|
||
}
|
||
|
||
/// A neutral taken back over a space keeps the space before it only inside right-to-left text. On a right-to-left line
|
||
/// drawn in logical order, a parenthesis that opens Latin text and is kerned back into the space before it stays
|
||
/// where its position puts it, as it would on a line without the Hebrew word.
|
||
#[test]
|
||
fn a_taken_back_neutral_beside_latin_text_keeps_its_place() {
|
||
// Drawn right to left: "שלום", the space, "(" pulled back into the space, then "AB" to its left.
|
||
let mut v = Vec::new();
|
||
let mut x = 60.0;
|
||
for c in ["ש", "ל", "ו", "ם"] {
|
||
v.push(em_box(c, x - 6.5, 0.0, x, 11.0));
|
||
x -= 6.5;
|
||
}
|
||
v.push(em_box(" ", x - 3.5, 0.0, x, 11.0));
|
||
x -= 3.5;
|
||
v.push(em_box("(", x - 2.0, 0.0, x + 2.0, 11.0));
|
||
x -= 2.0;
|
||
v.push(em_box("A", x - 13.0, 0.0, x - 6.5, 11.0));
|
||
v.push(em_box("B", x - 6.5, 0.0, x, 11.0));
|
||
assert_eq!(layout(v).plain_text(), "שלום (AB");
|
||
// A number reads as right-to-left beside a neutral: a question mark taken back over the space after "15", drawn in
|
||
// reverse order, still ends the line with no space before it.
|
||
let mut v = vec![em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box("?", 9.9, 0.0, 15.0, 11.0)];
|
||
v.push(em_box("1", 15.0, 0.0, 20.5, 11.0));
|
||
v.push(em_box("5", 20.5, 0.0, 26.0, 11.0));
|
||
v.push(em_box(" ", 26.0, 0.0, 29.5, 11.0));
|
||
let mut x = 29.5;
|
||
for c in ["ף", "י", "ע", "ס"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
assert_eq!(layout(v).plain_text().trim_end(), "סעיף 15?");
|
||
}
|
||
|
||
/// A mark drawn between a space and the letter taken back over it does not keep them apart: the space still ends the
|
||
/// word before, and the mark follows its letter, whether its box starts right or left of the space's start.
|
||
#[test]
|
||
fn a_mark_between_a_space_and_its_taken_back_letter_keeps_the_space_before_both() {
|
||
let line = |mark_x0: f32| {
|
||
let mut v = vec![em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box("\u{5B8}", mark_x0, 0.0, 17.5, 11.0), em_box("ה", 9.9, 0.0, 17.5, 11.0)];
|
||
let mut x = 17.5;
|
||
for c in ["נ", "י", "ד", "מ", "ה"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
x += 3.5;
|
||
for c in ["ר", "ק", "ב", "מ"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
assert_eq!(line(12.0).trim_end(), "מבקר המדינה\u{5B8}");
|
||
assert_eq!(line(9.95).trim_end(), "מבקר המדינה\u{5B8}");
|
||
// PDFBOX-5487's Arabic: a tanwin pulled back over the space, and the alef it sits on starting at the space's own
|
||
// start, so x order puts the alef after the space.
|
||
let mut v = vec![em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box("\u{64B}", 9.5, 0.0, 16.3, 11.0), em_box("ا", 10.0, 0.0, 12.8, 11.0)];
|
||
let mut x = 12.8;
|
||
for c in ["ر", "ي", "ر", "ق", "ت"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
v.push(em_box("ي", 3.0, 0.0, 6.0, 11.0));
|
||
v.push(em_box("ف", 6.0, 0.0, 9.5, 11.0));
|
||
assert_eq!(layout(v).plain_text().trim_end(), "تقريراً في");
|
||
}
|
||
|
||
/// Two taken-back spaces on one line each stay before their letter, and a second space drawn before a taken-back one
|
||
/// stays with it.
|
||
#[test]
|
||
fn two_taken_back_spaces_on_a_line_each_stay_before_their_letter() {
|
||
// Drawn left to right: " הנידמה" and " רקבמ", each space's advance taken back by its next letter, then " לע".
|
||
let word = |v: &mut Vec<TextGlyph>, x: &mut f32, first: &str, rest: &[&str]| {
|
||
v.push(em_box(" ", *x, 0.0, *x + 3.5, 11.0));
|
||
v.push(em_box(first, *x - 0.1, 0.0, *x + 6.4, 11.0));
|
||
*x += 6.4;
|
||
for c in rest {
|
||
v.push(em_box(c, *x, 0.0, *x + 6.5, 11.0));
|
||
*x += 6.5;
|
||
}
|
||
};
|
||
let mut v = Vec::new();
|
||
let mut x = 10.0;
|
||
word(&mut v, &mut x, "ה", &["נ", "י", "ד", "מ", "ה"]);
|
||
word(&mut v, &mut x, "ר", &["ק", "ב", "מ"]);
|
||
// The last word's space keeps its advance.
|
||
v.push(em_box(" ", x, 0.0, x + 3.5, 11.0));
|
||
x += 3.5;
|
||
for c in ["ל", "ע"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
assert_eq!(layout(v).plain_text().trim(), "על מבקר המדינה");
|
||
// Two spaces in a row, the second taken back: both stay before the letter.
|
||
let mut v = vec![em_box(" ", 6.5, 0.0, 10.0, 11.0), em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box("ה", 9.9, 0.0, 17.5, 11.0)];
|
||
let mut x = 17.5;
|
||
for c in ["נ", "י", "ד", "מ", "ה"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
// Untrimmed: both spaces follow the word, in drawing order.
|
||
assert_eq!(layout(v).plain_text(), "המדינה ");
|
||
}
|
||
|
||
/// pdf.js issue 11656 (https://github.com/mozilla/pdf.js/issues/11656): its content stream rebuilt with the same
|
||
/// codes, widths, adjustments and `/ToUnicode` on an unembedded font. Each right-to-left show string starts with a
|
||
/// space taken back under the next letter or punctuation; copied text keeps whole words and punctuation after its
|
||
/// word, and the parentheses of "15(ב)(4)" read as before.
|
||
#[test]
|
||
fn issue_11656_layout_reads_whole_words() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let shows: [(f32, f32, &str); 10] = [
|
||
(
|
||
386.83,
|
||
708.96,
|
||
"[<0003>324<0022>-3<02AD>11<02AC02A5>4<02AB0003>10<02AD02A502AC>4<02B90003>8<02A402AE000302AD>9<02AC02A5>4<02B2>-3<000302AD02A502AC02B9>] TJ",
|
||
),
|
||
(380.71, 708.96, "<0003> Tj"),
|
||
(
|
||
329.69,
|
||
686.62,
|
||
"[<0003>324<001102A902BA>3<02A902AE02A0000302A302AC>4<02A9000302B8>4<02A102AB>11<000302A902B0>10<02A00003>-2<000F02AD02A902A8>4<02A502A7>13<02A4000302AF02AE000302A302B8>6<02A502A9>5<000302A902B002A0>] TJ",
|
||
),
|
||
(323.57, 686.62, "<0003> Tj"),
|
||
(446.35, 664.3, "[<0011>10<02AD02A902A3>6<02AC02A9>4<02A4000302AC02AB000302A502AE02AB>] TJ"),
|
||
(
|
||
378.19,
|
||
641.98,
|
||
"[<000302B3>-2<02A902B202B1>11<000302A902B402AC0003>10<02A402AC02A0000302BA02A5>3<02AC02A5>4<02B2>7<02B4000302A1>-3<02A502A9>5<02A702AC>] TJ",
|
||
),
|
||
(366.19, 641.98, "-0.0278 Tc [<00140018>] TJ 0 Tc"),
|
||
(346.51, 641.98, "[<000C000B>5<02A1000C>] TJ"),
|
||
(340.49, 641.98, "[<0017>] TJ"),
|
||
(236.33, 641.98, "[<0003>324<02A402B002A902A3>4<02AE02A4000302B802B7>16<02A102AE0003>-2<02B7>3<02A502A7>13<02AC0003000B>] TJ"),
|
||
];
|
||
let ops: String = shows.iter().map(|(x, y, show)| format!("BT /F1 11.04 Tf 1 0 0 1 {x} {y} Tm {show} ET\n")).collect();
|
||
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfchar <0003> <0020> endbfchar 1 beginbfrange <000B> <000C> [<0029> <0028>] endbfrange 3 beginbfchar <000F> <002C> <0011> <002E> <0014> <0031> endbfchar 1 beginbfrange <0017> <0018> <0034> endbfrange 1 beginbfchar <0022> <003F> endbfchar 5 beginbfrange <02A0> <02A1> <05D0> <02A3> <02A5> <05D3> <02A7> <02A9> <05D7> <02AB> <02B4> <05DB> <02B7> <02BA> <05E7> endbfrange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
let ranges: [(i64, &[i64]); 13] = [
|
||
(0, &[1000]),
|
||
(3, &[313]),
|
||
(11, &[383, 383]),
|
||
(15, &[303]),
|
||
(17, &[303]),
|
||
(20, &[546]),
|
||
(23, &[546, 546]),
|
||
(34, &[474]),
|
||
(672, &[673, 640]),
|
||
(675, &[601, 685, 274]),
|
||
(679, &[685, 699, 274]),
|
||
(683, &[621, 621, 685, 685, 362, 401, 730, 648, 662, 652]),
|
||
(695, &[677, 569, 815, 709]),
|
||
];
|
||
let w: Vec<Object> = ranges
|
||
.iter()
|
||
.flat_map(|(first, widths)| [Object::Integer(*first), Object::Array(widths.iter().map(|&n| Object::Integer(n)).collect())])
|
||
.collect();
|
||
let mut doc = Document::with_version("1.7");
|
||
let unicode = doc.add_object(Stream::new(dictionary! {}, cmap.as_bytes().to_vec()));
|
||
let cid = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "CIDFontType2", "BaseFont" => "TestHebrew",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 },
|
||
"DW" => 1000, "W" => w, "CIDToGIDMap" => "Identity"
|
||
});
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "TestHebrew", "Encoding" => "Identity-H", "DescendantFonts" => vec![Object::Reference(cid)], "ToUnicode" => unicode });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let text = extract_page(&Pdf::new(std::sync::Arc::new(bytes)).unwrap(), 0, &InterpreterSettings::default()).unwrap();
|
||
let plain = text.plain_text();
|
||
let lines: Vec<&str> = plain.lines().map(str::trim).collect();
|
||
assert_eq!(
|
||
lines,
|
||
[
|
||
"שלום עולם מה שלום כולם?",
|
||
"אני יורד מן החוטים, אני כבר ילד אמיתי.",
|
||
"כמו כל הילדים.",
|
||
"לחיוב פעולות אלה לפי סעיף 15(ב)(4) לחוק מבקר המדינה"
|
||
]
|
||
);
|
||
for word in ["המדינה", "כולם?", "אמיתי.", "15(ב)(4)", "(ב)"] {
|
||
assert_eq!(text.find(word).len(), 1, "{word:?} in {lines:?}");
|
||
}
|
||
}
|
||
|
||
/// #2667: a number or punctuation on a right-to-left line must not split it into separately reversed words.
|
||
#[test]
|
||
fn rtl_line_with_number_and_punctuation_reads_in_logical_order() {
|
||
let line = |words: &[&str]| {
|
||
let mut v = Vec::new();
|
||
let mut x = 10.0;
|
||
for w in words {
|
||
word(&mut v, w, x, 10.0, 6.0);
|
||
x += w.chars().count() as f32 * 6.0 + 6.0;
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
// Each line as drawn, left to right.
|
||
assert_eq!(line(&["םילקש", "120", "ריחמ"]), "מחיר 120 שקלים");
|
||
assert_eq!(line(&[".הקידב", "ךמסמ", "והז", ":תירבע"]), "עברית: זהו מסמך בדיקה.");
|
||
assert_eq!(line(&["باتك", "12.5", "ددع"]), "عدد 12.5 كتاب");
|
||
assert_eq!(line(&["םלוע", "םולש"]), "שלום עולם");
|
||
assert_eq!(line(&["Total", "םולש", "price"]), "Total שלום price");
|
||
}
|
||
|
||
/// Two lines, "ab cd" and "e fg": words stop at blank glyphs, word gaps and line ends.
|
||
#[test]
|
||
fn words_and_lines_around_a_glyph() {
|
||
let t = PageText {
|
||
glyphs: Vec::from(["a", "b", " ", "c", "d", "e", "f", "g"].map(|s| TextGlyph {
|
||
text: s.into(),
|
||
rect: [0.0; 4],
|
||
quad: [[0.0; 2]; 4],
|
||
direction: [1.0, 0.0],
|
||
})),
|
||
line_of: vec![0, 0, 0, 0, 0, 1, 1, 1],
|
||
space_before: vec![false, false, false, false, false, false, true, false],
|
||
truncated: false,
|
||
};
|
||
assert_eq!(t.word_at(1), Some((0, 1)));
|
||
assert_eq!(t.word_at(3), Some((3, 4)));
|
||
assert_eq!(t.word_at(4), Some((3, 4)));
|
||
assert_eq!(t.word_at(5), Some((5, 5)));
|
||
assert_eq!(t.word_at(7), Some((6, 7)));
|
||
assert_eq!(t.line_at(2), Some((0, 4)));
|
||
assert_eq!(t.line_at(6), Some((5, 7)));
|
||
assert_eq!(t.word_at(8), None);
|
||
assert_eq!(t.line_at(8), None);
|
||
assert_eq!(PageText::default().line_at(0), None);
|
||
}
|
||
|
||
/// A 400 × 400 page drawing `ops` with Helvetica as /F1 and Courier as /F2.
|
||
fn text_page(ops: &str) -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let helvetica = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let courier = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Courier" });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.as_bytes().to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(400), Object::Integer(400)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => helvetica, "F2" => courier}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
/// `body` shown in /F`font` at `size` with its baseline turned `degrees` counter-clockwise.
|
||
fn turned(degrees: f64, font: u8, size: f64, x: f64, y: f64, body: &str) -> String {
|
||
let (s, c) = degrees.to_radians().sin_cos();
|
||
format!("BT /F{font} {size} Tf {c:.6} {s:.6} {:.6} {c:.6} {x:.4} {y:.4} Tm {body} ET\n", -s)
|
||
}
|
||
|
||
fn page_text(ops: &str) -> String {
|
||
extract_page(&text_page(ops), 0, &InterpreterSettings::default()).unwrap().plain_text()
|
||
}
|
||
|
||
#[test]
|
||
fn short_doubled_word_at_same_origin_does_not_interleave() {
|
||
let ops = "BT /F1 12 Tf 50 Tz 1 0 0 1 100 200 Tm (world) Tj ET\n".repeat(2);
|
||
assert_single_word(page_glyphs(&ops));
|
||
}
|
||
|
||
#[test]
|
||
fn short_near_shadow_does_not_interleave() {
|
||
let ops = "BT /F1 12 Tf 50 Tz 1 0 0 1 100 200 Tm (world) Tj ET\nBT /F1 12 Tf 50 Tz 1 0 0 1 101 200 Tm (world) Tj ET\n";
|
||
assert_single_word(page_glyphs(ops));
|
||
}
|
||
|
||
#[test]
|
||
fn turned_short_doubled_word_does_not_interleave() {
|
||
let one = turned(37.0, 1, 12.0, 100.0, 200.0, "50 Tz (world) Tj");
|
||
assert_single_word(page_glyphs(&(one.clone() + &one)));
|
||
}
|
||
|
||
#[test]
|
||
fn large_backward_tj_adjustment_stays_in_one_run() {
|
||
let text = page_glyphs("BT /F1 12 Tf 50 Tz 1 0 0 1 100 200 Tm [(wor) 3000 (ld)] TJ ET");
|
||
assert_eq!(text.plain_text(), "ld wor");
|
||
assert_eq!(text.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), ["l", "d", "w", "o", "r"]);
|
||
assert!(text.line_of.iter().all(|line| *line == 0));
|
||
assert_eq!(text.space_before, [false, false, true, false, false]);
|
||
}
|
||
|
||
#[test]
|
||
fn reset_prefix_requires_one_glyph_height_of_progress() {
|
||
let mut glyphs = Vec::new();
|
||
word(&mut glyphs, "abc", 10.0, 10.0, 6.0);
|
||
word(&mut glyphs, "abc", 10.0, 10.0, 6.0);
|
||
let glyphs: Vec<&TextGlyph> = glyphs.iter().collect();
|
||
assert!(!restarts_run(&glyphs, 0, 3, 9.99));
|
||
assert!(!restarts_run(&glyphs, 0, 3, 10.0));
|
||
assert!(restarts_run(&glyphs, 0, 3, 10.01));
|
||
}
|
||
|
||
#[test]
|
||
fn reset_prefix_uses_the_existing_redraw_position_tolerance() {
|
||
let mut near = Vec::new();
|
||
word(&mut near, "abc", 10.0, 10.0, 6.0);
|
||
word(&mut near, "abc", 11.99, 10.0, 6.0);
|
||
let near: Vec<&TextGlyph> = near.iter().collect();
|
||
assert!(restarts_run(&near, 0, 3, 10.01));
|
||
|
||
let mut far = Vec::new();
|
||
word(&mut far, "abc", 10.0, 10.0, 6.0);
|
||
word(&mut far, "abc", 12.01, 10.0, 6.0);
|
||
let far: Vec<&TextGlyph> = far.iter().collect();
|
||
assert!(!restarts_run(&far, 0, 3, 10.01));
|
||
}
|
||
|
||
#[test]
|
||
fn reset_prefix_rejects_non_finite_positions() {
|
||
let mut glyphs = Vec::new();
|
||
word(&mut glyphs, "abc", 10.0, 10.0, 6.0);
|
||
word(&mut glyphs, "abc", 10.0, 10.0, 6.0);
|
||
glyphs[3].rect[0] = f32::NAN;
|
||
let glyphs: Vec<&TextGlyph> = glyphs.iter().collect();
|
||
assert!(!restarts_run(&glyphs, 0, 3, 10.01));
|
||
}
|
||
|
||
#[test]
|
||
fn turned_lines_group_along_their_baseline() {
|
||
// Two lines 13 pt apart, words separated by TJ offsets (no space glyphs), the second
|
||
// line drawn first. Turned away from the quarter turns, the lines' boxes overlap.
|
||
for degrees in [12.0, 30.0, 37.0, 45.0, 60.0, 135.0, 200.0, 300.0, -45.0] {
|
||
let (s, c) = f64::to_radians(degrees).sin_cos();
|
||
let second = turned(degrees, 1, 12.0, 200.0 + s * 13.0, 200.0 - c * 13.0, "[(Second) -400 (line) -400 (here)] TJ");
|
||
let first = turned(degrees, 1, 12.0, 200.0, 200.0, "[(First) -400 (line) -400 (text)] TJ");
|
||
assert_eq!(page_text(&(second + &first)), "First line text\nSecond line here", "{degrees}°");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn crossing_turned_lines_stay_apart() {
|
||
// Lines at 30° and −30° crossing each other, their glyphs drawn alternately.
|
||
let (up, down) = ("Upward words here", "Downward words now");
|
||
let mut ops = String::new();
|
||
let (s, c) = f64::to_radians(30.0).sin_cos();
|
||
for (k, (a, b)) in up.chars().zip(down.chars()).enumerate() {
|
||
let along = 7.2 * k as f64;
|
||
ops += &turned(30.0, 2, 12.0, 100.0 + c * along, 150.0 + s * along, &format!("({a}) Tj"));
|
||
ops += &turned(-30.0, 2, 12.0, 100.0 + c * along, 250.0 - s * along, &format!("({b}) Tj"));
|
||
}
|
||
ops += &turned(-30.0, 2, 12.0, 100.0 + c * 7.2 * 17.0, 250.0 - s * 7.2 * 17.0, "(w) Tj");
|
||
assert_eq!(page_text(&ops), "Downward words now\nUpward words here");
|
||
}
|
||
|
||
#[test]
|
||
fn text_along_a_curve_is_one_line() {
|
||
// Courier glyphs (7.2 pt advance) set on circles of radius 90 around (200, 200): over
|
||
// the top reading clockwise, under the bottom reading counter-clockwise, and a full ring.
|
||
let arc = |text: &str, from: f64, clockwise: bool, radius: f64| {
|
||
let step = (7.2 / radius).to_degrees() * if clockwise { -1.0 } else { 1.0 };
|
||
let mut ops = String::new();
|
||
for (k, ch) in text.chars().enumerate() {
|
||
let a = from + step * k as f64;
|
||
let (s, c) = a.to_radians().sin_cos();
|
||
ops += &turned(if clockwise { a - 90.0 } else { a + 90.0 }, 2, 12.0, 200.0 + radius * c, 200.0 + radius * s, &format!("({ch}) Tj"));
|
||
}
|
||
ops
|
||
};
|
||
assert_eq!(page_text(&arc("CURVED STAMP TEXT", 150.0, true, 90.0)), "CURVED STAMP TEXT");
|
||
assert_eq!(page_text(&arc("BOTTOM ARC WORDS", 220.0, false, 90.0)), "BOTTOM ARC WORDS");
|
||
assert_eq!(page_text(&arc("ROUND SEAL OF THE COMPANY LIMITED", 180.0, true, 50.0)), "ROUND SEAL OF THE COMPANY LIMITED");
|
||
}
|
||
|
||
#[test]
|
||
fn sheared_text_keeps_its_word_gaps() {
|
||
// The baseline climbs at about 31° while the glyphs stay upright.
|
||
let ops = "BT /F1 12 Tf 1 0.6 0 1 100 200 Tm [(Sheared) -400 (first)] TJ 1 0.6 0 1 100 187 Tm [(Sheared) -400 (second)] TJ ET";
|
||
assert_eq!(page_text(ops), "Sheared first\nSheared second");
|
||
}
|
||
|
||
#[test]
|
||
fn turned_text_keeps_its_place_in_the_reading_order() {
|
||
// A turned label between a heading and its caption reads between them, as it did when
|
||
// it was laid out with the horizontal text; a vertical body still follows its heading.
|
||
let ops = "BT /F1 14 Tf 1 0 0 1 50 360 Tm (Heading above) Tj ET\n".to_string()
|
||
+ &turned(30.0, 1, 12.0, 80.0, 250.0, "(Turned label) Tj")
|
||
+ "BT /F1 12 Tf 1 0 0 1 50 150 Tm (Caption below) Tj ET\n";
|
||
assert_eq!(page_text(&ops), "Heading above\nTurned label\nCaption below");
|
||
}
|
||
|
||
#[test]
|
||
fn turned_glyphs_keep_their_shape_and_direction() {
|
||
// 30° counter-clockwise on the page is 30° up from the x axis in view space (y down).
|
||
let pdf = text_page(&(turned(30.0, 1, 20.0, 100.0, 100.0, "(Ab) Tj") + "BT /F1 20 Tf 1 0 0.5 1 100 300 Tm (Ab) Tj ET"));
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), "Ab\nAb");
|
||
for g in &text.glyphs {
|
||
assert!(g.quad.iter().flatten().chain(&g.direction).chain(&g.rect).all(|c| c.is_finite()), "{g:?}");
|
||
let bounds = g.quad.iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |r, p| {
|
||
[r[0].min(p[0]), r[1].min(p[1]), r[2].max(p[0]), r[3].max(p[1])]
|
||
});
|
||
assert_eq!(g.rect, bounds, "the box bounds the quad");
|
||
let [x, y] = [g.quad[1][0] - g.quad[0][0], g.quad[1][1] - g.quad[0][1]];
|
||
assert!(
|
||
(x * g.direction[1] - y * g.direction[0]).abs() < 1e-3 && x * g.direction[0] + y * g.direction[1] > 0.0,
|
||
"quad[0] → quad[1] runs along the direction: {g:?}"
|
||
);
|
||
}
|
||
let (skewed, turned) = (&text.glyphs[0], &text.glyphs[2]);
|
||
assert!((turned.direction[0] - 30f32.to_radians().cos()).abs() < 1e-6 && (turned.direction[1] + 0.5).abs() < 1e-6, "{turned:?}");
|
||
assert_eq!(skewed.direction, [1.0, 0.0]);
|
||
let slant = skewed.quad[3][0] - skewed.quad[0][0];
|
||
assert!((slant - 10.0).abs() < 1e-3, "the skewed glyph's upright edge leans by half its 20 pt height: {skewed:?}");
|
||
}
|
||
|
||
/// The operators drawing each `(text, text matrix)` run in Helvetica 12 pt, one text object per run.
|
||
fn run_ops(runs: &[(&str, &str)]) -> String {
|
||
runs.iter().map(|(text, tm)| format!("BT /F1 12 Tf {tm} Tm ({text}) Tj ET\n")).collect()
|
||
}
|
||
|
||
fn page_glyphs(ops: &str) -> PageText {
|
||
extract_page(&text_page(ops), 0, &InterpreterSettings::default()).unwrap()
|
||
}
|
||
|
||
fn assert_single_word(text: PageText) {
|
||
assert_eq!(text.plain_text(), "world");
|
||
assert_eq!(text.glyphs.iter().map(|g| g.text.as_str()).collect::<String>(), "world");
|
||
assert_eq!(text.line_of, [0; 5]);
|
||
assert_eq!(text.space_before, [false; 5]);
|
||
}
|
||
|
||
#[test]
|
||
fn runs_printed_over_each_other_stay_whole_at_any_angle() {
|
||
// Two runs that start at one point (exact overprint), that start 40 pt along and 3 pt down
|
||
// (shifted), and that are 14 pt apart (clear): at 0° and at 37°, each run comes out whole.
|
||
let tm = |angle: f32, along: f32, down: f32| {
|
||
let (s, c) = angle.to_radians().sin_cos();
|
||
let (x, y) = (100.0 + along * c - down * s, 200.0 + along * s + down * c);
|
||
format!("{c:.6} {s:.6} {:.6} {c:.6} {x:.4} {y:.4}", -s)
|
||
};
|
||
let (alpha, delta) = ("Alpha beta gamma", "Delta epsilon zeta");
|
||
for angle in [0.0, 37.0] {
|
||
for (along, down) in [(0.0, 0.0), (40.0, -3.0), (0.0, -14.0)] {
|
||
let text = page_glyphs(&run_ops(&[(alpha, &tm(angle, 0.0, 0.0)), (delta, &tm(angle, along, down))]));
|
||
for run in [alpha, delta] {
|
||
assert!(
|
||
!text.find(run).is_empty(),
|
||
"{run:?} whole at {angle}° with the second run {along} pt along and {down} pt across: {:?}",
|
||
text.plain_text()
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_run_drawn_over_a_line_leaves_the_line_whole() {
|
||
// "XX" is drawn over the middle of "beta" after the line, so it is a run of its own that
|
||
// overlaps the line. The line must still come out as one whole line.
|
||
let text = page_glyphs(&run_ops(&[("Alpha beta gamma", "1 0 0 1 100 200"), ("XX", "1 0 0 1 136 200")]));
|
||
let flat = text.plain_text();
|
||
assert!(flat.contains("Alpha beta gamma"), "{flat:?}");
|
||
assert!(flat.contains("XX") && !flat.contains('\n'), "{flat:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn a_combining_mark_drawn_last_stays_with_its_letter() {
|
||
// "ab", then a far-off "Z", then a zero-width combining mark at the start of "b". The mark
|
||
// is a run of its own, but it has no extent, so it goes back next to "b".
|
||
let mut v = Vec::new();
|
||
word(&mut v, "ab", 10.0, 10.0, 6.0);
|
||
v.push(g("Z", 200.0, 10.0, 206.0));
|
||
v.push(g("\u{301}", 16.0, 10.0, 16.0));
|
||
let t = layout(v);
|
||
assert_eq!(t.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), ["a", "b", "\u{301}", "Z"]);
|
||
}
|
||
|
||
#[test]
|
||
fn runs_differing_only_in_glyph_boundaries_are_not_redraws() {
|
||
// "ab" + "c" and "a" + "bc" have the same letters over the same places, but the glyph
|
||
// boundaries differ, so the second is not a redraw of the first and both stay.
|
||
let mut v = vec![g("ab", 10.0, 10.0, 16.0), g("c", 16.0, 10.0, 22.0)];
|
||
v.push(g("Z", 200.0, 10.0, 206.0));
|
||
v.push(g("a", 10.0, 10.0, 16.0));
|
||
v.push(g("bc", 16.0, 10.0, 22.0));
|
||
assert_eq!(layout(v).glyphs.len(), 5);
|
||
}
|
||
|
||
#[test]
|
||
fn many_combining_marks_stay_with_their_letters() {
|
||
// 400 letters on one line, then a zero-width mark at the start of each one, drawn after the whole line:
|
||
// the marks form one run of their own, and each goes back next to its letter, in order.
|
||
let letters: Vec<String> = (0..400).map(|i| char::from(b'a' + (i % 26) as u8).to_string()).collect();
|
||
let mut v = Vec::new();
|
||
for (i, c) in letters.iter().enumerate() {
|
||
let x = 10.0 + i as f32 * 6.0;
|
||
v.push(g(c, x, 10.0, x + 6.0));
|
||
}
|
||
for i in 0..letters.len() {
|
||
let x = 10.0 + i as f32 * 6.0;
|
||
v.push(g("\u{301}", x, 10.0, x));
|
||
}
|
||
let t = layout(v);
|
||
let expected: Vec<&str> = letters.iter().flat_map(|c| [c.as_str(), "\u{301}"]).collect();
|
||
assert_eq!(t.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), expected);
|
||
assert!(t.line_of.iter().all(|line| *line == 0));
|
||
}
|
||
|
||
/// `count` runs of three glyphs, each starting within 3 pt of x = 10 on one baseline, so they all overprint one
|
||
/// another. Every glyph has a text of its own, so no glyph is taken for a fake-bold copy. With `separated`, each run
|
||
/// follows a far-off glyph, which makes it a run of its own.
|
||
fn overprinted_runs(count: usize, separated: bool) -> Vec<TextGlyph> {
|
||
let mut v = Vec::new();
|
||
for k in 0..count {
|
||
let text: String = (0..3).map(|i| char::from_u32(0x4E00 + (3 * k + i) as u32).unwrap()).collect();
|
||
word(&mut v, &text, 10.0 + (k * 7 % 31) as f32 * 0.1, 10.0, 6.0);
|
||
if separated {
|
||
let far = char::from_u32(0x2500 + k as u32).unwrap().to_string();
|
||
v.push(g(&far, 500.0, 10.0, 506.0));
|
||
}
|
||
}
|
||
v
|
||
}
|
||
|
||
#[test]
|
||
fn a_dense_overprint_joins_its_runs_and_keeps_each_whole() {
|
||
// 150 runs of three glyphs: about 100 000 overlapping pairs, far more than the sweep's budget. The segment is
|
||
// joined as one component, so the sweep is skipped, and each run still comes out whole.
|
||
let v = overprinted_runs(150, false);
|
||
let refs: Vec<&TextGlyph> = v.iter().collect();
|
||
let height = |i: usize| (refs[i].rect[3] - refs[i].rect[1]).max(0.1);
|
||
let mut sc = Scratch { text: (0..150).map(|k| Run { start: 3 * k, end: 3 * k + 3 }).collect(), ..Default::default() };
|
||
assert!(collide(&refs, &height, 10.0, &mut sc), "more pairs than the budget");
|
||
assert_eq!(sc.units.len(), 1, "one component");
|
||
|
||
let v = overprinted_runs(150, true);
|
||
let runs: Vec<String> = (0..150).map(|k| v[4 * k..4 * k + 3].iter().map(|g| g.text.as_str()).collect()).collect();
|
||
let t = layout(v);
|
||
assert_eq!(t.glyphs.len(), 600);
|
||
for run in &runs {
|
||
assert!(!t.find(run).is_empty(), "{run:?} whole in {:?}", t.plain_text());
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn overlapping_rows_each_start_a_word() {
|
||
// 60 rows of three glyphs, each row starting 2 pt right of the one before and overprinting it, so every row
|
||
// is a forced word break. The rows are separated by far-off glyphs, which makes each one a run of its own.
|
||
// Every glyph has a text of its own, so no glyph is taken for a fake-bold copy.
|
||
let mut v = Vec::new();
|
||
let mut rows = Vec::new();
|
||
for k in 0..60 {
|
||
let text: String = (0..3).map(|i| char::from_u32(0x0400 + (3 * k + i) as u32).unwrap()).collect();
|
||
word(&mut v, &text, 10.0 + 2.0 * k as f32, 10.0, 6.0);
|
||
v.push(g(&char::from_u32(0x0500 + k as u32).unwrap().to_string(), 500.0, 10.0, 506.0));
|
||
rows.push(text);
|
||
}
|
||
let t = layout(v);
|
||
let expected: String = rows.join(" ");
|
||
assert!(t.plain_text().starts_with(&expected), "{:?}", t.plain_text());
|
||
}
|
||
|
||
#[test]
|
||
fn a_long_line_keeps_every_word_gap() {
|
||
// 1500 five-letter words on one line, a word gap after each: every gap is found, and only those.
|
||
let mut v = Vec::new();
|
||
let mut words = Vec::new();
|
||
for w in 0..1500 {
|
||
let text: String = (0..5).map(|i| char::from(b'a' + ((w * 7 + i * 3) % 26) as u8)).collect();
|
||
word(&mut v, &text, 10.0 + w as f32 * 36.0, 10.0, 6.0);
|
||
words.push(text);
|
||
}
|
||
assert_eq!(layout(v).plain_text(), words.join(" "));
|
||
}
|
||
|
||
#[test]
|
||
fn a_redraw_is_found_among_look_alike_runs_up_to_the_candidate_limit() {
|
||
// 40 runs of "abc" share a text and a grid cell, but each differs from every other by more than a fifth of a
|
||
// line in its second or third glyph, so none redraws another. A run of "abc" at the place of the newest run is
|
||
// found, as the newest candidates are checked first. One at the place of the oldest run is 40 candidates back,
|
||
// past the limit, so it is kept.
|
||
let abc = |v: &mut Vec<TextGlyph>, k: usize| {
|
||
let (b, c) = (16.0 + 2.5 * (k % 4) as f32, 22.0 + 2.5 * (k / 4) as f32);
|
||
v.push(g("a", 10.0, 10.0, 16.0));
|
||
v.push(g("b", b, 10.0, b + 6.0));
|
||
v.push(g("c", c, 10.0, c + 6.0));
|
||
};
|
||
let far = |v: &mut Vec<TextGlyph>| {
|
||
for _ in 0..4 {
|
||
let x = 500.0 + 10.0 * v.len() as f32;
|
||
v.push(g("|", x, 10.0, x + 6.0));
|
||
}
|
||
};
|
||
let mut v = Vec::new();
|
||
for k in 0..40 {
|
||
abc(&mut v, k);
|
||
far(&mut v);
|
||
}
|
||
abc(&mut v, 39);
|
||
far(&mut v);
|
||
assert_eq!(layout(v.clone()).glyphs.iter().filter(|g| g.text == "a").count(), 40);
|
||
abc(&mut v, 0);
|
||
assert_eq!(layout(v).glyphs.iter().filter(|g| g.text == "a").count(), 41);
|
||
}
|
||
|
||
#[test]
|
||
fn a_run_redrawn_at_the_same_place_is_printed_once() {
|
||
// "Hello world" drawn again 0.1 pt away (doubled text) prints once. The same words far
|
||
// below are a separate line, as they are not a redraw.
|
||
let ops = run_ops(&[("Hello world", "1 0 0 1 100 200"), ("Hello world", "1 0 0 1 100.1 200.1"), ("Hello world", "1 0 0 1 100 100")]);
|
||
assert_eq!(page_text(&ops), "Hello world\nHello world");
|
||
}
|
||
|
||
#[test]
|
||
fn a_redraw_is_found_past_an_earlier_run_with_the_same_key() {
|
||
// Two "Hello" runs share a text and a grid cell but do not redraw each other: the second is
|
||
// tracked wider. A third run redraws the second and is dropped. A far-off "Z" keeps each run
|
||
// a segment of its own.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "Hello", 10.0, 10.0, 6.0);
|
||
v.push(g("Z", 200.0, 10.0, 206.0));
|
||
word(&mut v, "Hello", 10.5, 10.0, 9.0);
|
||
v.push(g("Z", 300.0, 10.0, 306.0));
|
||
word(&mut v, "Hello", 10.6, 10.0, 9.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.glyphs.iter().filter(|g| g.text == "H").count(), 2, "{:?}", t.plain_text());
|
||
assert_eq!(t.glyphs.len(), 12);
|
||
}
|
||
|
||
#[test]
|
||
fn runs_that_only_touch_or_overlap_slightly_still_join() {
|
||
// "beta" is drawn first, then "Alpha" to its left: 2 pt apart (touching) or 2 pt overlapping
|
||
// (negative spacing). Both come out as one line in reading order. Where the word space goes
|
||
// for reversed fragments is not asserted here.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "beta", 42.0, 10.0, 6.0);
|
||
word(&mut v, "Alpha", 10.0, 10.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text().replace(' ', ""), "Alphabeta");
|
||
assert!(t.line_of.iter().all(|line| *line == 0));
|
||
let mut v = Vec::new();
|
||
word(&mut v, "beta", 38.0, 10.0, 6.0);
|
||
word(&mut v, "Alpha", 10.0, 10.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text(), "Alphabeta");
|
||
}
|
||
|
||
/// A three-row table, "Name Qty / Apple 12 / Pear 7": the columns sit far enough apart that
|
||
/// reading order takes one column, then the other.
|
||
fn table() -> PageText {
|
||
let mut v = Vec::new();
|
||
for (row, (name, qty)) in [("Name", "Qty"), ("Apple", "12"), ("Pear", "7")].into_iter().enumerate() {
|
||
let y = 10.0 + row as f32 * 14.0;
|
||
word(&mut v, name, 10.0, y, 6.0);
|
||
word(&mut v, qty, 100.0, y, 6.0);
|
||
}
|
||
layout(v)
|
||
}
|
||
|
||
/// Issue #740: a column selection takes only what is inside the rectangle.
|
||
#[test]
|
||
fn a_column_selection_takes_one_table_column() {
|
||
let t = table();
|
||
assert_eq!(t.plain_text(), "Name\nApple\nPear\nQty\n12\n7", "reading order is column by column");
|
||
let qty = t.glyphs_in([95.0, 0.0, 130.0, 60.0]);
|
||
assert_eq!(t.column_text(&qty), "Qty\n12\n7");
|
||
assert_eq!(t.glyph_rects(&qty).len(), 3, "one highlight per row");
|
||
// Corners in either order.
|
||
assert_eq!(t.glyphs_in([130.0, 60.0, 95.0, 0.0]), qty);
|
||
}
|
||
|
||
/// Across columns the text comes out row by row, cells separated by tabs.
|
||
#[test]
|
||
fn a_column_selection_across_columns_reads_row_by_row() {
|
||
let t = table();
|
||
let all = t.glyphs_in([0.0, 0.0, 200.0, 60.0]);
|
||
assert_eq!(t.column_text(&all), "Name\tQty\nApple\t12\nPear\t7");
|
||
// The middle row only, and only the start of "Apple": centres decide.
|
||
let part = t.glyphs_in([0.0, 25.0, 31.0, 33.0]);
|
||
assert_eq!(t.column_text(&part), "Appl");
|
||
assert_eq!(t.glyph_rects(&part), vec![[10.0, 24.0, 34.0, 34.0]]);
|
||
}
|
||
|
||
/// A drag along one row of a table that reads column by column selects that row, not the
|
||
/// rest of the first column and the top of the second.
|
||
#[test]
|
||
fn a_drag_along_one_table_row_selects_that_row() {
|
||
let t = table();
|
||
let (apple, two) = (4, 17);
|
||
assert_eq!(t.text_of(apple..two + 1), "Apple\nPear\nQty\n12", "reading order detours through the columns");
|
||
for (anchor, head) in [(apple, two), (two, apple)] {
|
||
let row = t.visual_between(anchor, head, None).expect("one row");
|
||
assert_eq!(t.column_text(&row), "Apple\t12");
|
||
assert_eq!(t.glyph_rects(&row).len(), 2, "one highlight per cell");
|
||
}
|
||
// Part of a row: from inside "Apple" to the "1" of "12".
|
||
let part = t.visual_between(6, 16, None).expect("one row");
|
||
assert_eq!(t.column_text(&part), "ple\t1");
|
||
}
|
||
|
||
/// A drag over several rows of that table selects by rows too: the rest of the top row from
|
||
/// where it started, then the bottom row up to where it ends.
|
||
#[test]
|
||
fn a_drag_over_table_rows_selects_those_rows() {
|
||
let t = table();
|
||
let (name, two) = (0, 17);
|
||
assert_eq!(t.text_of(name..two + 1), "Name\nApple\nPear\nQty\n12", "reading order takes \"Pear\" from the row below");
|
||
for (anchor, head) in [(name, two), (two, name)] {
|
||
let rows = t.visual_between(anchor, head, None).expect("rows");
|
||
assert_eq!(t.column_text(&rows), "Name\tQty\nApple\t12");
|
||
}
|
||
// From inside "Name" ("me") to the "1" of "12": the start of the top row and the end of
|
||
// the bottom one are left out.
|
||
let rows = t.visual_between(2, 16, None).expect("rows");
|
||
assert_eq!(t.column_text(&rows), "me\tQty\nApple\t1");
|
||
// Over three rows, ending in the other column: the middle row comes whole, though reading
|
||
// order (down the first column, then the second) would cover the same glyphs.
|
||
let rows = t.visual_between(1, 18, None).expect("rows");
|
||
assert_eq!(t.column_text(&rows), "ame\tQty\nApple\t12\nPear\t7");
|
||
// Down the second column only, reading order stays.
|
||
assert_eq!(t.visual_between(13, 18, None), None, "from \"Qty\" down to \"7\"");
|
||
}
|
||
|
||
/// A drag down the first column whose pointer ends out to the right, past the text of its
|
||
/// last row, crosses the columns: the rows. With the pointer over the column, reading order.
|
||
#[test]
|
||
fn a_pointer_ending_beside_the_column_takes_the_rows() {
|
||
let t = table();
|
||
let pear = 9;
|
||
assert_eq!(t.visual_between(0, pear, Some(20.0)), None, "over the first column");
|
||
let rows = t.visual_between(0, pear, Some(150.0)).expect("rows");
|
||
assert_eq!(t.column_text(&rows), "Name\tQty\nApple\t12\nP");
|
||
// Running text: the rows are reading order's own glyphs, so reading order stays.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "Heading", 10.0, 10.0, 6.0);
|
||
word(&mut v, "A longer line of text", 10.0, 22.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.visual_between(0, 20, Some(200.0)), None);
|
||
}
|
||
|
||
/// Side-by-side columns (a bilingual contract): a drag in the right column that ends on a list
|
||
/// marker hanging left of its text, past a gap like a gutter, still takes nothing from the left
|
||
/// column, where it never went.
|
||
#[test]
|
||
fn a_drag_in_the_right_column_takes_nothing_from_the_left() {
|
||
let mut v = Vec::new();
|
||
for (row, (left, right)) in [("Uno dos", "One two"), ("Tres cuatro", "Three four"), ("Cinco seis", "Five six")].into_iter().enumerate() {
|
||
let y = 10.0 + row as f32 * 12.0;
|
||
word(&mut v, left, 10.0, y, 6.0);
|
||
word(&mut v, right, 230.0, y, 6.0);
|
||
}
|
||
word(&mut v, "II.", 200.0, 46.0, 6.0);
|
||
word(&mut v, "Seven", 230.0, 46.0, 6.0);
|
||
let t = layout(v);
|
||
let one = (0..t.glyphs.len()).find(|&i| t.glyphs[i].rect[0] == 230.0 && t.glyphs[i].rect[1] == 10.0).expect("\"One\"");
|
||
let marker = (0..t.glyphs.len()).find(|&i| t.glyphs[i].rect[0] == 200.0).expect("\"II.\"");
|
||
let selected = t.visual_between(one, marker, Some(203.0)).unwrap_or_else(|| (one.min(marker)..=one.max(marker)).collect());
|
||
assert!(selected.iter().all(|&i| t.glyphs[i].rect[0] >= 200.0), "{:?}", t.column_text(&selected));
|
||
}
|
||
|
||
/// A justified line leaves a gap between two words wider than a column gutter, which no other
|
||
/// row of a short drag may cross; but it parts only that line, where a gutter parts the rows.
|
||
#[test]
|
||
fn a_justified_gap_is_not_a_gutter() {
|
||
let mut v = Vec::new();
|
||
for row in 0..8 {
|
||
word(&mut v, "Some words of a line", 10.0, 10.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
// Row 8: "Wide" then, 60 units on, "gap".
|
||
word(&mut v, "Wide", 10.0, 106.0, 6.0);
|
||
word(&mut v, "gap", 94.0, 106.0, 6.0);
|
||
let t = layout(v);
|
||
assert!(!t.gutter_between(20.0, 100.0, 106.0 - 40.0, 116.0 + 40.0, 10.0), "the rows above cross it");
|
||
assert!(!t.gutter_between(20.0, 100.0, 106.0, 116.0, 10.0), "on its own row it parts one line only");
|
||
assert!(!t.gutter_between(20.0, 200.0, 0.0, 200.0, 10.0), "past the text's right edge nothing is parted");
|
||
// A table's columns part every row.
|
||
assert!(table().gutter_between(20.0, 100.0, 0.0, 60.0, 10.0));
|
||
}
|
||
|
||
/// A heading across the page just above a table crosses the table's gutter, but a drag over
|
||
/// the table from its first cell to its last still takes the rows.
|
||
#[test]
|
||
fn a_heading_above_a_table_does_not_hide_its_gutter() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "A heading wider than the whole table", 10.0, -6.0, 6.0);
|
||
for (row, (name, qty)) in [("Name", "Qty"), ("Apple", "12"), ("Pear", "7")].into_iter().enumerate() {
|
||
let y = 10.0 + row as f32 * 14.0;
|
||
word(&mut v, name, 10.0, y, 6.0);
|
||
word(&mut v, qty, 100.0, y, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
let first = (0..t.glyphs.len()).find(|&i| t.glyphs[i].text == "N").expect("\"Name\"");
|
||
let last = (0..t.glyphs.len()).find(|&i| t.glyphs[i].text == "7").expect("\"7\"");
|
||
let x = (t.glyphs[last].rect[0] + t.glyphs[last].rect[2]) / 2.0;
|
||
let rows = t.visual_between(first, last, Some(x)).expect("rows");
|
||
assert_eq!(t.column_text(&rows), "Name\tQty\nApple\t12\nPear\t7");
|
||
}
|
||
|
||
/// Two columns of running text: one paragraph fills the left column and runs on at the top of
|
||
/// the right. A drag from its start to its end, or along the first row from one column into
|
||
/// the other, keeps reading order (the left column, then the right) instead of interleaving
|
||
/// the columns by rows.
|
||
#[test]
|
||
fn a_drag_across_columns_of_running_text_keeps_reading_order() {
|
||
let mut v = Vec::new();
|
||
let left =
|
||
["One paragraph starts at the top", "of the left column and runs down", "for a few ordinary lines of text", "until the column ends and then"];
|
||
let right = ["it carries on at the top of the", "right column where the reader", "expects it to continue."];
|
||
for (row, s) in left.into_iter().enumerate() {
|
||
word(&mut v, s, 10.0, 10.0 + row as f32 * 14.0, 6.0);
|
||
}
|
||
for (row, s) in right.into_iter().enumerate() {
|
||
word(&mut v, s, 240.0, 10.0 + row as f32 * 14.0, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
let last = t.glyphs.len() - 1;
|
||
let at = |i: usize| Some((t.glyphs[i].rect[0] + t.glyphs[i].rect[2]) / 2.0);
|
||
assert_eq!(t.visual_between(0, last, at(last)), None, "to the end of the paragraph");
|
||
let right_start = (0..t.glyphs.len()).find(|&i| t.glyphs[i].rect[0] == 240.0 && t.glyphs[i].rect[1] == 10.0).expect("\"it\"");
|
||
assert_eq!(t.visual_between(0, right_start + 1, at(right_start + 1)), None, "along the first row");
|
||
}
|
||
|
||
/// A column of running text beside a short sidebar (not a table: most of its rows have nothing
|
||
/// beside them): a drag from the bottom of the text up to the top of the sidebar keeps reading
|
||
/// order, the text to its end and then the sidebar's first line, not every row between.
|
||
#[test]
|
||
fn a_sidebar_beside_running_text_is_not_a_table() {
|
||
let mut v = Vec::new();
|
||
for row in 0..10 {
|
||
word(&mut v, "Some running text of a longer line", 10.0, 10.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
for (row, s) in ["Dates", "3 May: fair", "4 May: open day"].into_iter().enumerate() {
|
||
word(&mut v, s, 260.0, 10.0 + row as f32 * 20.0, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
let last_line_start =
|
||
(0..t.glyphs.len()).find(|&i| t.glyphs[i].rect[0] == 10.0 && t.glyphs[i].rect[1] == 10.0 + 9.0 * 12.0).expect("last line start");
|
||
let dates = (0..t.glyphs.len()).find(|&i| t.glyphs[i].rect[0] == 260.0 && t.glyphs[i].rect[1] == 10.0).expect("\"Dates\"");
|
||
let x = Some((t.glyphs[dates].rect[0] + t.glyphs[dates].rect[2]) / 2.0);
|
||
assert_eq!(t.visual_between(last_line_start, dates + 3, x), None, "from the last prose line up to the sidebar");
|
||
assert_eq!(t.visual_between(dates + 3, last_line_start, x), None, "and back");
|
||
}
|
||
|
||
/// Short terms beside their definitions (a description list) are not running text: a drag
|
||
/// across them takes the rows.
|
||
#[test]
|
||
fn terms_beside_definitions_still_take_the_rows() {
|
||
let mut v = Vec::new();
|
||
for (row, (term, def)) in
|
||
[("PDF/UA", "PDF for accessibility"), ("PDF/A", "PDF for long-term preservation"), ("PDF/E", "PDF for engineering workflows")]
|
||
.into_iter()
|
||
.enumerate()
|
||
{
|
||
let y = 10.0 + row as f32 * 14.0;
|
||
word(&mut v, term, 10.0, y, 6.0);
|
||
word(&mut v, def, 100.0, y, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
let first = 0;
|
||
let eng = t.find("engineering").into_iter().next().expect("\"engineering\"").start;
|
||
let x = Some((t.glyphs[eng].rect[0] + t.glyphs[eng].rect[2]) / 2.0);
|
||
let rows = t.visual_between(first, eng, x).expect("rows");
|
||
assert_eq!(t.column_text(&rows), "PDF/UA\tPDF for accessibility\nPDF/A\tPDF for long-term preservation\nPDF/E\tPDF for e");
|
||
}
|
||
|
||
/// Reading order stays the answer on one line, down one column, and where it doesn't leave
|
||
/// the rows the drag covers.
|
||
#[test]
|
||
fn a_drag_that_reading_order_already_covers_keeps_it() {
|
||
let t = table();
|
||
assert_eq!(t.visual_between(4, 8, None), None, "within \"Apple\"");
|
||
assert_eq!(t.visual_between(0, 10, None), None, "down the first column, from \"Name\" into \"Pear\"");
|
||
assert_eq!(t.visual_between(4, usize::MAX, None), None, "past the text");
|
||
// One row of two cells reads as one line, so reading order stays on the row.
|
||
let mut v = Vec::new();
|
||
word(&mut v, "Left", 10.0, 10.0, 6.0);
|
||
word(&mut v, "Right", 100.0, 10.0, 6.0);
|
||
let t = layout(v);
|
||
assert_eq!(t.plain_text(), "Left Right");
|
||
assert_eq!(t.visual_between(0, 8, None), None);
|
||
}
|
||
|
||
/// A report generator pads each cell of a row with spaces. A cell whose padding stops short of
|
||
/// the next cell (here 62 units, its last letter further from the next cell than a line reaches)
|
||
/// still reads as one row with it, instead of the next cell coming after the whole table.
|
||
#[test]
|
||
fn a_cell_padded_with_spaces_joins_the_next_cell_of_its_row() {
|
||
let line_of_cells = |cell: &str, next_x: f32| {
|
||
let mut v = Vec::new();
|
||
word(&mut v, cell, 10.0, 10.0, 6.0);
|
||
word(&mut v, "9.00", next_x, 10.0, 6.0);
|
||
let t = layout(v);
|
||
let last = t.glyphs.len() - 1;
|
||
t.line_of[0] == t.line_of[last]
|
||
};
|
||
assert!(line_of_cells("Item ", 120.0), "padded to x 58, the amount 62 further on");
|
||
assert!(!line_of_cells("Item", 120.0), "unpadded, the gap is a column gap");
|
||
assert!(!line_of_cells("Item ", 160.0), "padded, but the next cell is too far");
|
||
}
|
||
|
||
/// Past the end of a short row, the pointer stays on that row: a longer row just below,
|
||
/// nearer by the old distance, used to take the drag's end into it.
|
||
#[test]
|
||
fn a_point_level_with_a_row_takes_that_rows_nearest_glyph() {
|
||
let mut v = Vec::new();
|
||
word(&mut v, "Short", 10.0, 10.0, 6.0);
|
||
word(&mut v, "A much longer row", 10.0, 22.0, 6.0);
|
||
let t = layout(v);
|
||
// Level with "Short" (y 10..20, ending at x 40), 60 past it, above the long row.
|
||
assert_eq!(t.nearest(100.0, 15.0), Some(4), "the \"t\" of \"Short\"");
|
||
// In the gap between the rows the nearer glyph still wins.
|
||
let below = t.nearest(100.0, 21.5).and_then(|i| t.line_of.get(i).copied());
|
||
assert_eq!(below, Some(1), "just above the long row, nearer to it than to the short one");
|
||
assert_eq!(PageText::default().nearest(0.0, 0.0), None);
|
||
assert!(t.nearest(f32::NAN, 15.0).is_some(), "a NaN point still answers, never panics");
|
||
}
|
||
|
||
/// Two columns whose baselines don't line up: a point in the leading between two right-hand
|
||
/// lines, level with a left-hand line far away, takes the right-hand line next to it.
|
||
#[test]
|
||
fn a_point_between_lines_is_not_taken_by_a_far_line_level_with_it() {
|
||
let mut v = Vec::new();
|
||
for row in 0..3 {
|
||
word(&mut v, "Left text", 10.0, 10.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
for row in 0..2 {
|
||
word(&mut v, "Right text", 200.0, 16.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
// y 27: between the right lines (16..26 and 28..38), within the left line at 22..32.
|
||
let i = t.nearest(205.0, 27.0).expect("a glyph");
|
||
assert!(t.glyphs[i].rect[0] >= 200.0, "took {:?} at {:?}", t.glyphs[i].text, t.glyphs[i].rect);
|
||
}
|
||
|
||
/// The mirror image: a point in the gutter just right of the left column, between two of its
|
||
/// lines and level with a right-hand line, takes the left-hand line beside it.
|
||
#[test]
|
||
fn a_point_in_the_gutter_is_not_taken_by_the_far_column_level_with_it() {
|
||
let mut v = Vec::new();
|
||
for row in 0..3 {
|
||
word(&mut v, "Left text", 10.0, 10.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
for row in 0..2 {
|
||
word(&mut v, "Right text", 200.0, 16.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
// y 21: between the left lines (10..20 and 22..32), within the right line at 16..26.
|
||
let i = t.nearest(70.0, 21.0).expect("a glyph");
|
||
assert!(t.glyphs[i].rect[2] <= 64.0, "took {:?} at {:?}", t.glyphs[i].text, t.glyphs[i].rect);
|
||
}
|
||
|
||
/// The same, with the left line level with the point the longest of its column (ragged right):
|
||
/// the column's shorter lines still mark the gutter.
|
||
#[test]
|
||
fn a_long_level_line_does_not_hide_the_gutter_from_its_column() {
|
||
let mut v = Vec::new();
|
||
for (row, s) in ["Left text", "Left text longer", "Left text"].into_iter().enumerate() {
|
||
word(&mut v, s, 10.0, 10.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
for row in 0..2 {
|
||
word(&mut v, "Right text", 200.0, 16.0 + row as f32 * 12.0, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
let i = t.nearest(205.0, 27.0).expect("a glyph");
|
||
assert!(t.glyphs[i].rect[0] >= 200.0, "took {:?} at {:?}", t.glyphs[i].text, t.glyphs[i].rect);
|
||
}
|
||
|
||
/// An invoice's seal beside its QR code, the code drawn with a barcode font: eight flush rows of
|
||
/// twelve 4 × 6 pt glyphs, and five 8 pt lines of text 5 pt to their right, every other one on a
|
||
/// code row's baseline.
|
||
fn barcode_beside_text() -> PageText {
|
||
const SEAL: [&str; 5] = ["one two three", "four five six", "seven eight", "nine ten", "eleven twelve"];
|
||
let mut v = Vec::new();
|
||
for row in 0..8 {
|
||
let y = 100.0 + row as f32 * 6.0;
|
||
for k in 0..12 {
|
||
let c = char::from(b'A' + ((row * 5 + k) % 26) as u8);
|
||
let x = 10.0 + k as f32 * 4.0;
|
||
v.push(em_box(&c.to_string(), x, y, x + 4.0, y + 6.0));
|
||
}
|
||
}
|
||
for (line, text) in SEAL.into_iter().enumerate() {
|
||
let y = 100.0 + line as f32 * 9.0;
|
||
for (k, c) in text.chars().enumerate() {
|
||
let x = 63.0 + k as f32 * 4.8;
|
||
v.push(em_box(&c.to_string(), x, y, x + 4.8, y + 8.0));
|
||
}
|
||
}
|
||
layout(v)
|
||
}
|
||
|
||
/// The seal's lines read on together, not each joined to the code row beside it, and the code
|
||
/// reads after all the text.
|
||
#[test]
|
||
fn a_barcode_drawn_with_a_font_reads_apart_from_the_text_beside_it() {
|
||
let t = barcode_beside_text();
|
||
let text = t.plain_text();
|
||
let lines: Vec<&str> = text.lines().collect();
|
||
assert_eq!(lines.get(..5), Some(&["one two three", "four five six", "seven eight", "nine ten", "eleven twelve"][..]), "{text}");
|
||
assert_eq!(lines.len(), 13, "{text}");
|
||
assert!(lines[5..].iter().all(|l| l.len() == 12 && l.chars().all(|c| c.is_ascii_uppercase())), "{text}");
|
||
}
|
||
|
||
/// A point in the leading right of the seal's text, level with a row of the code, takes the
|
||
/// seal's line, and a drag down the seal selects none of the code.
|
||
#[test]
|
||
fn a_point_beside_a_barcode_takes_the_text_not_the_code_row() {
|
||
let t = barcode_beside_text();
|
||
let is_code = |i: usize| t.glyphs[i].rect[2] <= 58.0;
|
||
// Right of "four five six" (ends at 125.4), in the leading below it and level with code row 3.
|
||
let i = t.nearest(120.0, 117.5).expect("a glyph");
|
||
assert!(!is_code(i), "took the code's {:?} at {:?}", t.glyphs[i].text, t.glyphs[i].rect);
|
||
// Over the code, its row still wins.
|
||
let i = t.nearest(30.0, 117.5).expect("a glyph");
|
||
assert!(is_code(i));
|
||
// From "one" to the end of "nine ten", the pointer past it.
|
||
let (one, ten) = (t.nearest(65.0, 104.0).expect("one"), t.nearest(100.0, 131.0).expect("ten"));
|
||
let picked = t.visual_between(one, ten, Some(110.0)).unwrap_or_else(|| (one.min(ten)..=one.max(ten)).collect());
|
||
assert!(!picked.iter().any(|&i| is_code(i)), "{:?}", t.column_text(&picked));
|
||
}
|
||
|
||
/// A short word on the baseline of a barcode's first row, a label's width to its left, stays a
|
||
/// line of its own: the code row does not go on the word's line, and the code keeps all its rows.
|
||
#[test]
|
||
fn a_word_on_a_barcode_rows_baseline_does_not_take_the_row() {
|
||
let mut v = Vec::new();
|
||
for (k, c) in "Seal".chars().enumerate() {
|
||
let x = 10.0 + k as f32 * 4.0;
|
||
v.push(em_box(&c.to_string(), x, 100.0, x + 4.0, 106.0));
|
||
}
|
||
for row in 0..4 {
|
||
let y = 100.0 + row as f32 * 6.0;
|
||
for k in 0..12 {
|
||
let c = char::from(b'A' + ((row * 5 + k) % 26) as u8);
|
||
let x = 50.0 + k as f32 * 4.0;
|
||
v.push(em_box(&c.to_string(), x, y, x + 4.0, y + 6.0));
|
||
}
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "Seal\nABCDEFGHIJKL\nFGHIJKLMNOPQ\nKLMNOPQRSTUV\nPQRSTUVWXYZA");
|
||
}
|
||
|
||
/// A table beside a line of prose on one of its rows: the prose, left of everywhere the drag
|
||
/// went, does not count as a row with one cell, and a drag down the table still takes its rows.
|
||
#[test]
|
||
fn prose_left_of_a_table_does_not_hide_its_rows() {
|
||
let mut v = Vec::new();
|
||
for (row, (name, qty)) in [("Name", "Qty"), ("Apple", "12"), ("Pear", "7")].into_iter().enumerate() {
|
||
let y = 10.0 + row as f32 * 14.0;
|
||
word(&mut v, name, 200.0, y, 6.0);
|
||
word(&mut v, qty, 290.0, y, 6.0);
|
||
}
|
||
word(&mut v, "Some unrelated prose", 10.0, 17.0, 6.0);
|
||
let t = layout(v);
|
||
let at = |c: &str, x: f32| t.glyphs.iter().position(|g| g.text == c && (g.rect[0] - x).abs() < 0.5).expect("a glyph");
|
||
let (name, two) = (at("N", 200.0), at("2", 296.0));
|
||
let picked = t.visual_between(name, two, Some(t.glyphs[two].rect[2] + 4.0)).expect("rows");
|
||
assert_eq!(t.column_text(&picked), "Name\tQty\nApple\t12");
|
||
}
|
||
|
||
/// A double-click drag between two words of one table row, or of two rows, takes both whole
|
||
/// in either direction. A right-to-left word reads from its right end, so its first glyph in
|
||
/// reading order is not its left end.
|
||
#[test]
|
||
fn row_ends_take_both_words_whole() {
|
||
let t = table();
|
||
let rows = |t: &PageText, from: usize, to: usize| {
|
||
let (unit, other) = (t.word_at(from).expect("a word"), t.word_at(to).expect("a word"));
|
||
let (anchor, head) = t.row_ends(unit, other);
|
||
t.visual_between(anchor, head, Some(t.glyphs[to].rect[2])).map(|p| t.column_text(&p))
|
||
};
|
||
// "Name" 0..=3, "Apple" 4..=8, "Qty" 13..=15.
|
||
for (from, to, copied) in [(1, 14, "Name\tQty"), (14, 1, "Name\tQty"), (14, 6, "Qty\nApple"), (6, 14, "Qty\nApple")] {
|
||
assert_eq!(rows(&t, from, to).as_deref(), Some(copied), "{from} to {to}");
|
||
}
|
||
|
||
// Two columns of Hebrew words, drawn visually (each word's letters left to right reversed).
|
||
let mut v = Vec::new();
|
||
for (row, (a, b)) in [("םש", "תומכ"), ("חופת", "רשע"), ("סגא", "עבש")].into_iter().enumerate() {
|
||
let y = 10.0 + row as f32 * 14.0;
|
||
word(&mut v, a, 10.0, y, 6.0);
|
||
word(&mut v, b, 100.0, y, 6.0);
|
||
}
|
||
let t = layout(v);
|
||
let at = |x: f32| t.glyphs.iter().position(|g| (g.rect[0] - x).abs() < 0.5 && (g.rect[1] - 10.0).abs() < 0.5).expect("a glyph");
|
||
let (left, right) = (at(10.0), at(100.0));
|
||
for (from, to) in [(left, right), (right, left)] {
|
||
let picked = rows(&t, from, to).expect("rows");
|
||
assert!(picked.contains("שם") && picked.contains("כמות"), "{picked:?}");
|
||
}
|
||
}
|
||
|
||
/// A rectangle that misses every glyph, or is not a number, selects nothing.
|
||
#[test]
|
||
fn an_empty_or_degenerate_column_selection_is_empty() {
|
||
let t = table();
|
||
for r in [[300.0, 300.0, 400.0, 400.0], [f32::NAN, 0.0, 200.0, 60.0], [50.0, 50.0, 50.0, 50.0]] {
|
||
let none = t.glyphs_in(r);
|
||
assert!(none.is_empty(), "{r:?}");
|
||
assert_eq!(t.column_text(&none), "");
|
||
assert!(t.glyph_rects(&none).is_empty());
|
||
}
|
||
assert_eq!(PageText::default().column_text(&[0, 7, usize::MAX]), "", "indices past the text are ignored");
|
||
}
|
||
|
||
/// Right-to-left rows put their cells right to left.
|
||
#[test]
|
||
fn right_to_left_rows_read_right_to_left() {
|
||
let mut v = Vec::new();
|
||
// "שלום" (right) and "עולם" (left), each drawn visually.
|
||
word(&mut v, "םולש", 100.0, 10.0, 6.0);
|
||
word(&mut v, "םלוע", 10.0, 10.0, 6.0);
|
||
let t = layout(v);
|
||
let all = t.glyphs_in([0.0, 0.0, 200.0, 30.0]);
|
||
assert_eq!(t.column_text(&all), "שלום\tעולם");
|
||
}
|
||
|
||
/// Vertical lines (CJK vertical writing) come out one per row, in reading order.
|
||
#[test]
|
||
fn vertical_lines_keep_reading_order() {
|
||
// Written downwards: the em box's edge towards the next line is its left one.
|
||
let cell = |t: &str, x: f32, y: f32| TextGlyph {
|
||
text: t.into(),
|
||
rect: [x, y, x + 10.0, y + 10.0],
|
||
quad: [[x, y], [x, y + 10.0], [x + 10.0, y + 10.0], [x + 10.0, y]],
|
||
direction: [0.0, 1.0],
|
||
};
|
||
let t = PageText {
|
||
// Right column 日本 first, then the left column 語文, each top to bottom.
|
||
glyphs: vec![cell("日", 40.0, 10.0), cell("本", 40.0, 20.0), cell("語", 20.0, 10.0), cell("文", 20.0, 20.0)],
|
||
line_of: vec![0, 0, 1, 1],
|
||
space_before: vec![false; 4],
|
||
truncated: false,
|
||
};
|
||
let all = t.glyphs_in([0.0, 0.0, 60.0, 40.0]);
|
||
assert_eq!(t.column_text(&all), "日本\n語文");
|
||
// A drag from one vertical column into the next at the same height is not along a row:
|
||
// reading order stays (本 then 語文, down each column).
|
||
assert_eq!(t.visual_between(1, 3, Some(25.0)), None, "from 本 across to 文");
|
||
assert_eq!(t.visual_between(0, 2, Some(25.0)), None, "from 日 across to 語");
|
||
}
|
||
|
||
/// An embedded TrueType font with no `/Encoding`, flagged `flags`, its `/ToUnicode` (if
|
||
/// any) mapping only printable ASCII, as OCR engines write the text layer of a scan.
|
||
fn ocr_layer_text(flags: i64, ascii_to_unicode: bool) -> String {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let program = doc.add_object(Stream::new(dictionary! {}, include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec()));
|
||
let descriptor =
|
||
doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "Inter-Regular", "Flags" => flags, "FontFile2" => program });
|
||
let mut font = dictionary! { "Type" => "Font", "Subtype" => "TrueType", "BaseFont" => "Inter-Regular", "FontDescriptor" => descriptor };
|
||
if ascii_to_unicode {
|
||
let cmap = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Ascii def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 1 beginbfrange <20> <7E> <0020> endbfrange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
font.set("ToUnicode", doc.add_object(Stream::new(dictionary! {}, cmap.to_vec())));
|
||
}
|
||
let font = doc.add_object(font);
|
||
// WinAnsi bytes: "Rückfragen für Überhitzungsschutz: können, weiß, Café".
|
||
let mut ops = b"BT /F1 14 Tf 1 0 0 1 20 200 Tm (".to_vec();
|
||
ops.extend_from_slice(b"R\xfcckfragen f\xfcr \xdcberhitzungsschutz: k\xf6nnen, wei\xdf, Caf\xe9");
|
||
ops.extend_from_slice(b") Tj ET");
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(400), Object::Integer(400)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text()
|
||
}
|
||
|
||
#[test]
|
||
fn truetype_without_an_encoding_reads_its_codes_as_win_ansi() {
|
||
// Café: 0xE9 is /Oslash in StandardEncoding, so reading the codes as Standard first and
|
||
// WinAnsi only for the gaps would still give "CafØ".
|
||
let expected = "Rückfragen für Überhitzungsschutz: können, weiß, Café";
|
||
assert_eq!(ocr_layer_text(4, false), expected, "symbolic, no /ToUnicode");
|
||
assert_eq!(ocr_layer_text(32, true), expected, "nonsymbolic, /ToUnicode for ASCII only");
|
||
}
|
||
|
||
/// #3713: a Chinese label spread to the width of a longer one (分散對齊, as on Taiwanese forms)
|
||
/// is one show with character spacing, so every gap of the label is the same, while the value
|
||
/// beside it has none. The line's typical gap is therefore the value's zero, and from half a
|
||
/// line height upwards each of the label's gaps read as a word gap: 「受文者」 copied as
|
||
/// 「受 文 者」 and Find no longer matched it. A repeated gap is spacing, whatever its width.
|
||
#[test]
|
||
fn a_chinese_label_spread_by_character_spacing_keeps_its_characters_together() {
|
||
// `Tc` is added after every glyph of the string (ISO 32000-2 §9.3.2), so the gap before
|
||
// the value is the spacing too; the value's own glyphs follow at `0 Tc`.
|
||
let line = |tc: f32| {
|
||
let mut v = Vec::new();
|
||
let mut x = 0.0;
|
||
for ch in ["受", "文", "者"] {
|
||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||
x += 12.0 + tc;
|
||
}
|
||
for ch in ["如", "正", "本"] {
|
||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||
x += 12.0;
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
// A tenth of the font size up to a whole em: the issue's nine steps, the last three of
|
||
// which used to break.
|
||
for tc in [1.2, 2.4, 3.0, 3.6, 4.2, 4.8, 6.0, 9.0, 12.0] {
|
||
assert_eq!(line(tc), "受文者如正本", "{tc} pt of character spacing");
|
||
}
|
||
|
||
// A gap that stands on its own is still a word gap. The width is what the review caught: a
|
||
// whole line height swallowed any isolated gap under one em, so two cells of a form row set
|
||
// 9pt apart on a 12pt line copied as one word. Half a line height upwards is a gap, which is
|
||
// the width Hangul already used; below it is still spacing.
|
||
let cells = |gap: f32| {
|
||
let mut v = Vec::new();
|
||
for (i, ch) in ["姓", "名"].iter().enumerate() {
|
||
let x = i as f32 * 12.0;
|
||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||
}
|
||
for (i, ch) in ["王", "小", "明"].iter().enumerate() {
|
||
let x = 24.0 + gap + i as f32 * 12.0;
|
||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
// Two character widths, as before, and then the band that used to be lost: half a line
|
||
// height and up. 6.0 is the boundary itself, which is a gap.
|
||
for gap in [24.0, 18.0, 12.0, 9.0, 7.2, 6.0] {
|
||
assert_eq!(cells(gap), "姓名 王小明", "{gap} pt between the two cells");
|
||
}
|
||
// And below it, still spacing rather than a gap -- one isolated narrow gap must not start
|
||
// splitting a label that happens to carry one.
|
||
for gap in [5.4, 3.0, 1.2, 0.0] {
|
||
assert_eq!(cells(gap), "姓名王小明", "{gap} pt is spacing, not a gap");
|
||
}
|
||
}
|
||
|
||
/// Korean is written with spaces between words (띄어쓰기), and a file may write them as
|
||
/// position rather than as space characters, so the rule for Chinese and Japanese -- where a
|
||
/// gap between two characters is never a word gap -- must not reach Hangul (#3722 review).
|
||
#[test]
|
||
fn korean_words_separated_by_position_keep_their_spaces() {
|
||
let line = |gap: f32| {
|
||
let mut v = Vec::new();
|
||
let mut x = 0.0;
|
||
for word in ["안녕", "하세요", "여러분"] {
|
||
for ch in word.chars() {
|
||
v.push(em_box(&ch.to_string(), x, 0.0, x + 12.0, 12.0));
|
||
x += 12.0;
|
||
}
|
||
x += gap;
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
// Half the line height upwards is a word gap, as it was before the Chinese rule changed.
|
||
for gap in [6.0, 7.0, 9.0, 12.0] {
|
||
assert_eq!(line(gap), "안녕 하세요 여러분", "{gap} pt between the words");
|
||
}
|
||
// Below that it is letter spacing, which is unchanged.
|
||
assert_eq!(line(3.0), "안녕하세요여러분");
|
||
}
|
||
|
||
/// Halfwidth Hangul jamo are Hangul too: equal gaps between them from half a line height up are
|
||
/// word gaps, not the character spacing of spread Chinese text.
|
||
#[test]
|
||
fn halfwidth_hangul_separated_by_equal_gaps_keeps_its_spaces() {
|
||
let mut v = Vec::new();
|
||
let mut x = 0.0;
|
||
// A one-letter word between two others: its two word gaps repeat each other.
|
||
for word in ["\u{FFA1}\u{FFA2}", "\u{FFA4}", "\u{FFA7}\u{FFA8}"] {
|
||
for ch in word.chars() {
|
||
v.push(em_box(&ch.to_string(), x, 0.0, x + 6.0, 12.0));
|
||
x += 6.0;
|
||
}
|
||
x += 7.0;
|
||
}
|
||
assert_eq!(layout(v).plain_text(), "\u{FFA1}\u{FFA2} \u{FFA4} \u{FFA7}\u{FFA8}");
|
||
}
|
||
|
||
/// Issue #2929: a footnote reference (superscript) on a line stays in that line instead of
|
||
/// splitting out as a raised segment that steals the block's tail and pushes the host line
|
||
/// after the paragraph.
|
||
#[test]
|
||
fn paragraph_selection_includes_lines_with_footnote_references() {
|
||
for inline in [true, false] {
|
||
let ops = if inline {
|
||
"BT /F1 12 Tf 1 0 0 1 40 300 Tm (First line of the paragraph) Tj \
|
||
1 0 0 1 40 285 Tm (Second line with a note) Tj \
|
||
/F1 8 Tf 5.5 Ts (1) Tj 0 Ts \
|
||
/F1 12 Tf ( and more text) Tj \
|
||
1 0 0 1 40 270 Tm (Third line of the paragraph) Tj \
|
||
/F1 7 Tf 1 0 0 1 40 104 Tm (1) Tj \
|
||
/F1 10 Tf 1 0 0 1 47 100 Tm (Footnote at the bottom) Tj ET"
|
||
} else {
|
||
// Superscripts drawn in a separate pass after the body text.
|
||
"BT /F1 12 Tf 1 0 0 1 40 300 Tm (First line of the paragraph) Tj \
|
||
1 0 0 1 40 285 Tm (Second line with a note) Tj \
|
||
1 0 0 1 173 285 Tm (and more text) Tj \
|
||
1 0 0 1 40 270 Tm (Third line of the paragraph) Tj \
|
||
/F1 10 Tf 1 0 0 1 47 100 Tm (Footnote at the bottom) Tj \
|
||
/F1 8 Tf 1 0 0 1 165 290.5 Tm (1) Tj \
|
||
/F1 7 Tf 1 0 0 1 40 104 Tm (1) Tj ET"
|
||
};
|
||
let text = page_glyphs(ops);
|
||
let start = text.nearest(40.0, 95.0).unwrap();
|
||
let end = text.nearest(185.0, 128.0).unwrap();
|
||
assert_eq!(
|
||
text.text_of(start..end + 1),
|
||
"First line of the paragraph\nSecond line with a note1 and more text\nThird line of the paragraph",
|
||
"inline={inline}"
|
||
);
|
||
assert_eq!(text.line_rects(start..end + 1).len(), 3, "three selected lines, inline={inline}");
|
||
assert_eq!(
|
||
text.plain_text(),
|
||
"First line of the paragraph\nSecond line with a note1 and more text\nThird line of the paragraph\n1 Footnote at the bottom",
|
||
"inline={inline}"
|
||
);
|
||
}
|
||
|
||
// Superscript on the first line, multi-character bracketed reference `[12]` on the second
|
||
// line, and subscript on the third line (both inline and out-of-order).
|
||
for inline in [true, false] {
|
||
let ops = if inline {
|
||
"BT /F1 12 Tf 1 0 0 1 40 300 Tm (Opening claim) Tj \
|
||
/F1 8 Tf 5.5 Ts (1) Tj 0 Ts \
|
||
/F1 12 Tf ( in the first line) Tj \
|
||
1 0 0 1 40 285 Tm (Middle citation) Tj \
|
||
/F1 8 Tf 5.5 Ts ([12]) Tj 0 Ts \
|
||
/F1 12 Tf ( continues here) Tj \
|
||
1 0 0 1 40 270 Tm (Formula H) Tj \
|
||
/F1 8 Tf -3 Ts (2) Tj 0 Ts \
|
||
/F1 12 Tf (O in the third line) Tj ET"
|
||
} else {
|
||
"BT /F1 12 Tf 1 0 0 1 40 300 Tm (Opening claim) Tj \
|
||
1 0 0 1 125 300 Tm (in the first line) Tj \
|
||
1 0 0 1 40 285 Tm (Middle citation) Tj \
|
||
1 0 0 1 135 285 Tm (continues here) Tj \
|
||
1 0 0 1 40 270 Tm (Formula H) Tj \
|
||
1 0 0 1 101 270 Tm (O in the third line) Tj \
|
||
/F1 8 Tf 1 0 0 1 117 305.5 Tm (1) Tj \
|
||
1 0 0 1 117 290.5 Tm ([12]) Tj \
|
||
1 0 0 1 96.5 267 Tm (2) Tj ET"
|
||
};
|
||
let text = page_glyphs(ops);
|
||
assert_eq!(
|
||
text.plain_text(),
|
||
"Opening claim1 in the first line\nMiddle citation[12] continues here\nFormula H2O in the third line",
|
||
"inline={inline}"
|
||
);
|
||
assert_eq!(text.line_rects(0..text.glyphs.len()).len(), 3, "inline={inline}");
|
||
}
|
||
|
||
// Justified wide gap (18pt = 1.5 * h) after an inline superscript stays on the same line,
|
||
// and an out-of-order superscript kerned slightly over punctuation does not break the host
|
||
// word via overprint collision.
|
||
let justified = page_glyphs(
|
||
"BT /F1 12 Tf 1 0 0 1 40 300 Tm (Justified clause.) Tj \
|
||
/F1 8 Tf 5.5 Ts (1) Tj 0 Ts \
|
||
/F1 12 Tf 1 0 0 1 151 300 Tm (Next sentence on the same line) Tj \
|
||
1 0 0 1 40 285 Tm (Kerned clause.) Tj \
|
||
1 0 0 1 130 285 Tm (continues cleanly) Tj \
|
||
/F1 8 Tf 1 0 0 1 118 290.5 Tm (2) Tj ET",
|
||
);
|
||
assert_eq!(justified.plain_text(), "Justified clause.1 Next sentence on the same line\nKerned clause.2 continues cleanly");
|
||
assert_eq!(justified.line_rects(0..justified.glyphs.len()).len(), 2);
|
||
|
||
// A line that begins with a raised superscript marker and continues with taller body text
|
||
// adopts the body text's vertical band (Seg::extend_box first branch) so a later
|
||
// out-of-order superscript on that line still measures against the body baseline.
|
||
let leading_script = page_glyphs(
|
||
"BT /F1 8 Tf 1 0 0 1 40 300 Tm 6 Ts (1) Tj 0 Ts \
|
||
/F1 12 Tf ( See the appendix) Tj \
|
||
1 0 0 1 146 300 Tm (for details) Tj \
|
||
/F1 8 Tf 1 0 0 1 139 303.6 Tm (2) Tj ET",
|
||
);
|
||
assert_eq!(leading_script.plain_text(), "1 See the appendix2 for details");
|
||
let marker = leading_script.glyphs.first().unwrap().rect;
|
||
let body = leading_script.glyphs.iter().find(|g| g.text == "S").unwrap().rect;
|
||
let last = leading_script.glyphs.last().unwrap().rect;
|
||
let center = |r: [f32; 4]| ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0);
|
||
let (start_x, start_y) = center(marker);
|
||
let (end_x, end_y) = center(last);
|
||
let start = leading_script.nearest(start_x, start_y).unwrap();
|
||
let end = leading_script.nearest(end_x, end_y).unwrap();
|
||
assert_eq!(leading_script.text_of(start..end + 1), "1 See the appendix2 for details");
|
||
let rects = leading_script.line_rects(start..end + 1);
|
||
assert_eq!(rects.len(), 1);
|
||
assert!(marker[1] < body[1] && marker[3] < body[3], "marker must be raised above the body");
|
||
let close = |actual: f32, expected: f32| assert!((actual - expected).abs() < 0.001, "{actual} != {expected}");
|
||
// Highlight rectangles cover the actual glyphs, including the raised marker. They do
|
||
// not expose the segment's baseline band used for line grouping.
|
||
for (actual, expected) in rects[0].into_iter().zip([marker[0], marker[1], last[2], body[3]]) {
|
||
close(actual, expected);
|
||
}
|
||
close(rects[0][3] - rects[0][1], 14.8);
|
||
close(body[3] - 0.2 * 12.0, 100.0); // 300 pt PDF baseline on a 400 pt page.
|
||
|
||
// Pin that internal band too: replacing the first extend_box condition with `false`
|
||
// must fail here even when plain text and highlight rectangles remain unchanged.
|
||
let mut segment = Seg::new(Run { start: 0, end: 1 }, marker, marker[3] - marker[1], marker[2]);
|
||
segment.extend_box(&body, body[3] - body[1]);
|
||
for (actual, expected) in segment.bbox.into_iter().zip([marker[0], body[1], body[2], body[3]]) {
|
||
close(actual, expected);
|
||
}
|
||
close(segment.h, 12.0);
|
||
close(segment.bbox[3] - segment.bbox[1], 12.0);
|
||
close(segment.bbox[3] - 0.2 * segment.h, 100.0);
|
||
close(segment.cy(), (body[1] + body[3]) / 2.0);
|
||
}
|
||
|
||
#[test]
|
||
fn text_outside_the_crop_box_is_clipped() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let ops = [
|
||
"BT /F1 12 Tf 1 0 0 1 100 200 Tm (Inside crop) Tj ET",
|
||
"BT /F1 12 Tf 1 0 0 1 100 150 Tm /Span <</ActualText (ActualIn)>> BDC (in) Tj EMC ET",
|
||
// Keep every glyph of OutSpan outside the crop; a boundary-crossing glyph remains visible.
|
||
"BT /F1 12 Tf 1 0 0 1 -100 125 Tm /Span <</ActualText (CroppedSpan KeptSpan)>> BDC (OutSpan) Tj 1 0 0 1 100 125 Tm (KeptSpan) Tj EMC ET",
|
||
"BT /F1 12 Tf 1 0 0 1 5 200 Tm (LeftOut) Tj ET",
|
||
"BT /F1 12 Tf 1 0 0 1 360 200 Tm (RightOut) Tj ET",
|
||
"BT /F1 12 Tf 1 0 0 1 100 20 Tm (BelowOut) Tj ET",
|
||
"BT /F1 12 Tf 1 0 0 1 100 370 Tm (AboveOut) Tj ET",
|
||
"BT /F1 12 Tf 1 0 0 1 100 20 Tm /Span <</ActualText (ActualOut)>> BDC (out) Tj EMC ET",
|
||
"BT /F1 12 Tf 1 0 0 1 46 100 Tm (A) Tj ET",
|
||
]
|
||
.join("\n");
|
||
for rotate in [0, 90, 180, 270] {
|
||
for unit in [1, 2] {
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.as_bytes().to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! {
|
||
"Type" => "Page",
|
||
"Parent" => pages,
|
||
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(400), Object::Integer(400)],
|
||
"CropBox" => vec![Object::Integer(50), Object::Integer(60), Object::Integer(350), Object::Integer(340)],
|
||
"Rotate" => rotate,
|
||
"UserUnit" => unit,
|
||
"Resources" => dictionary! { "Font" => dictionary! { "F1" => font } },
|
||
"Contents" => content,
|
||
});
|
||
doc.objects.insert(pages, dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1 }.into());
|
||
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), "Inside crop\nActualIn\nKeptSpan\nA", "rotate={rotate} unit={unit}");
|
||
assert!(!text.find("Inside").is_empty(), "rotate={rotate} unit={unit}");
|
||
assert!(!text.find("ActualIn").is_empty(), "rotate={rotate} unit={unit}");
|
||
assert!(!text.find("KeptSpan").is_empty(), "rotate={rotate} unit={unit}");
|
||
for hidden in ["LeftOut", "RightOut", "BelowOut", "AboveOut", "ActualOut", "CroppedSpan", "OutSpan"] {
|
||
assert!(text.find(hidden).is_empty(), "{hidden} must be clipped at rotate={rotate} unit={unit}");
|
||
}
|
||
}
|
||
}
|
||
|
||
// A CropBox that is zero-area or disjoint from the MediaBox is read as a missing one
|
||
// (vendored hayro-syntax patch 38): the visible region is the MediaBox, as on a page without
|
||
// a CropBox, not a region of no area.
|
||
let text_with = |crop: Option<[i64; 4]>| {
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.as_bytes().to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let mut page = dictionary! {
|
||
"Type" => "Page",
|
||
"Parent" => pages,
|
||
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(400), Object::Integer(400)],
|
||
"Resources" => dictionary! { "Font" => dictionary! { "F1" => font } },
|
||
"Contents" => content,
|
||
};
|
||
if let Some(crop) = crop {
|
||
page.set("CropBox", crop.map(Object::Integer).to_vec());
|
||
}
|
||
let page = doc.add_object(page);
|
||
doc.objects.insert(pages, dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1 }.into());
|
||
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text()
|
||
};
|
||
let media = text_with(None);
|
||
assert!(media.contains("LeftOut") && media.contains("AboveOut") && !media.contains("OutSpan"), "{media:?}");
|
||
for crop in [[200, 200, 200, 200], [100, 200, 300, 200], [500, 500, 600, 600]] {
|
||
assert_eq!(text_with(Some(crop)), media, "{crop:?}");
|
||
}
|
||
}
|
||
|
||
/// One glyph per text object, as a CAD or word-processor PDF writer draws shaped text: `text` in Helvetica
|
||
/// remapped by `/ToUnicode`, base letters 600 units wide, combining marks 0 wide and placed at the pen after their
|
||
/// base shifted by `mark_dx` points (a mark-positioning offset), words 260 units apart, with a space glyph or
|
||
/// without one.
|
||
fn one_glyph_per_show(text: &str, mark_dx: f32, space_glyphs: bool) -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let is_mark = |c: char| unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM;
|
||
let mut chars: Vec<char> = Vec::new();
|
||
for c in text.chars() {
|
||
if !chars.contains(&c) {
|
||
chars.push(c);
|
||
}
|
||
}
|
||
let code = |c: char| 0x21 + chars.iter().position(|&k| k == c).unwrap();
|
||
let (size, base, space) = (20.0_f32, 600.0_f32, 260.0_f32);
|
||
let mut ops = String::new();
|
||
let mut x = 50.0_f32;
|
||
for c in text.chars() {
|
||
let at = if is_mark(c) { x + mark_dx } else { x };
|
||
if c != ' ' || space_glyphs {
|
||
ops.push_str(&format!("BT /F1 {size} Tf 1 0 0 1 {at:.3} 300 Tm <{:02X}> Tj ET\n", code(c)));
|
||
}
|
||
if c == ' ' {
|
||
x += space * size / 1000.0;
|
||
} else if !is_mark(c) {
|
||
x += base * size / 1000.0;
|
||
}
|
||
}
|
||
let width = |c: char| {
|
||
if is_mark(c) {
|
||
0
|
||
} else if c == ' ' {
|
||
260
|
||
} else {
|
||
600
|
||
}
|
||
};
|
||
let widths: Vec<Object> = chars.iter().map(|&c| Object::Integer(width(c))).collect();
|
||
let pairs: String = chars.iter().map(|&c| format!("<{:02X}> <{:04X}>\n", code(c), u32::from(c))).collect();
|
||
let cmap = format!(
|
||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /T def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange {} beginbfchar\n{pairs}endbfchar endcmap CMapName currentdict /CMap defineresource pop end end",
|
||
chars.len()
|
||
);
|
||
let mut doc = Document::with_version("1.7");
|
||
let unicode = doc.add_object(Stream::new(dictionary! {}, cmap.into_bytes()));
|
||
let mut differences = vec![Object::Integer(0x21)];
|
||
differences.extend(chars.iter().map(|_| Object::Name(b"a".to_vec())));
|
||
let font = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "FirstChar" => 0x21, "LastChar" => 0x20 + chars.len() as i64,
|
||
"Widths" => widths, "Encoding" => dictionary! { "Type" => "Encoding", "Differences" => differences }, "ToUnicode" => unicode
|
||
});
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(600), Object::Integer(400)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
/// #6517: Thai drawn one glyph per show operation, each zero-advance tone mark or above vowel starting a hair past
|
||
/// its base's advance (or exactly at it, or back over the base), reads in content order: no mark moves after the
|
||
/// next letter, and the word gaps read as spaces whether a space glyph is drawn or not. Copy and Find use this order.
|
||
#[test]
|
||
fn thai_marks_drawn_one_glyph_at_a_time_keep_their_place_and_words() {
|
||
let thai = "ห้อง ก๋วยเตี๋ยว น้ำ ที่นี่";
|
||
for mark_dx in [0.4, 0.0, -6.0] {
|
||
for space_glyphs in [false, true] {
|
||
let text = extract_page(&one_glyph_per_show(thai, mark_dx, space_glyphs), 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), thai, "marks {mark_dx} pt past the pen, space glyphs {space_glyphs}");
|
||
for word in ["ห้อง", "ก๋วยเตี๋ยว", "น้ำ", "ที่นี่"] {
|
||
assert_eq!(text.find_opts(word, true, true).len(), 1, "{word:?} found as a whole word in {:?}", text.plain_text());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Combining marks of other left-to-right scripts ride on their base the same way: Devanagari signs (virama,
|
||
/// anusvara, a below vowel; the spacing vowel sign ि is a letter of its own), and Latin combining accents.
|
||
#[test]
|
||
fn combining_marks_of_other_scripts_keep_their_place() {
|
||
for text in ["कुछ हिंदी स्कूल", "e\u{301}te\u{301} na\u{303}o"] {
|
||
let page = extract_page(&one_glyph_per_show(text, 0.4, false), 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(page.plain_text(), text);
|
||
}
|
||
}
|
||
|
||
/// A line drawn right to left glyph by glyph still reads by x, and a mark drawn right after its letter moves with
|
||
/// it. A mark that starts far from the glyph before it is not taken for a mark on that glyph: it goes by its own x.
|
||
#[test]
|
||
fn a_mark_moves_with_its_letter_in_a_line_drawn_backwards() {
|
||
let v = vec![g("c", 24.0, 10.0, 30.0), g("b", 18.0, 10.0, 24.0), g("\u{301}", 24.3, 10.0, 29.3), g("a", 12.0, 10.0, 18.0)];
|
||
assert_eq!(layout(v).plain_text(), "ab\u{301}c");
|
||
let v = vec![g("a", 12.0, 10.0, 18.0), g("b", 18.0, 10.0, 24.0), g("c", 24.0, 10.0, 30.0), g("\u{301}", 13.0, 10.0, 18.0)];
|
||
assert_eq!(layout(v).plain_text(), "a\u{301}bc");
|
||
}
|
||
|
||
/// A second mark stacked on a letter rides on the letter, not only on the mark before it: a mark drawn back over its
|
||
/// base, then a tone mark a hair past the base's advance, both stay before the next letter.
|
||
#[test]
|
||
fn a_stacked_mark_rides_on_its_base_letter() {
|
||
let v = vec![g("ก", 12.0, 10.0, 18.0), g("\u{e34}", 10.0, 10.0, 15.0), g("\u{e48}", 19.5, 10.0, 24.5), g("ข", 18.0, 10.0, 24.0)];
|
||
assert_eq!(layout(v).plain_text(), "ก\u{e34}\u{e48}ข");
|
||
}
|
||
|
||
/// A mark drawn raised by more than half an em over its letter (a tone mark lifted above an upper vowel) stays on the
|
||
/// letter's line and before the next letter.
|
||
#[test]
|
||
fn a_raised_mark_stays_with_its_letter() {
|
||
let v = vec![g("ก", 12.0, 10.0, 18.0), g("\u{e48}", 18.4, 16.0, 23.4), g("ข", 18.0, 10.0, 24.0), g("ค", 24.0, 10.0, 30.0)];
|
||
assert_eq!(layout(v).plain_text(), "ก\u{e48}ขค");
|
||
}
|
||
|
||
/// A word gap after a mark is measured from its letter's advance: a mark drawn a hair past the pen does not narrow it.
|
||
#[test]
|
||
fn a_word_gap_after_a_mark_is_measured_from_its_letter() {
|
||
let v = vec![g("a", 0.0, 10.0, 6.0), g("b", 6.0, 10.0, 12.0), g("\u{301}", 12.4, 10.0, 17.4), g("c", 13.8, 10.0, 19.8), g("d", 19.8, 10.0, 25.8)];
|
||
assert_eq!(layout(v).plain_text(), "ab\u{301} cd");
|
||
}
|
||
|
||
/// In a run squeezed to no width, a mark still follows its letter, even when it is drawn past the next letter.
|
||
#[test]
|
||
fn a_mark_in_a_zero_width_run_follows_its_letter() {
|
||
let v = vec![g("a", 10.0, 10.0, 10.0), g("\u{301}", 10.6, 10.0, 10.6), g("b", 10.3, 10.0, 10.3)];
|
||
assert_eq!(layout(v).plain_text(), "a\u{301}b");
|
||
}
|
||
|
||
/// One show string of `text` in Helvetica remapped by `/ToUnicode`, every glyph `width` units wide, combining marks
|
||
/// and spaces included, as a font whose `/Widths` give a mark an advance of its own draws it: each mark moves the pen,
|
||
/// and the next letter starts right at the mark's box.
|
||
fn one_show_string(text: &str, width: i64) -> Pdf {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut chars: Vec<char> = Vec::new();
|
||
for c in text.chars() {
|
||
if !chars.contains(&c) {
|
||
chars.push(c);
|
||
}
|
||
}
|
||
let code = |c: char| 0x21 + chars.iter().position(|&k| k == c).unwrap();
|
||
let codes: String = text.chars().map(|c| format!("{:02X}", code(c))).collect();
|
||
let ops = format!("BT /F1 14 Tf 20 220 Td <{codes}> Tj ET");
|
||
let widths: Vec<Object> = chars.iter().map(|_| Object::Integer(width)).collect();
|
||
let pairs: String = chars.iter().map(|&c| format!("<{:02X}> <{:04X}>\n", code(c), u32::from(c))).collect();
|
||
let cmap = format!(
|
||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /T def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange {} beginbfchar\n{pairs}endbfchar endcmap CMapName currentdict /CMap defineresource pop end end",
|
||
chars.len()
|
||
);
|
||
let mut doc = Document::with_version("1.7");
|
||
let unicode = doc.add_object(Stream::new(dictionary! {}, cmap.into_bytes()));
|
||
let mut differences = vec![Object::Integer(0x21)];
|
||
differences.extend(chars.iter().map(|_| Object::Name(b"a".to_vec())));
|
||
let font = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "FirstChar" => 0x21, "LastChar" => 0x20 + chars.len() as i64,
|
||
"Widths" => widths, "Encoding" => dictionary! { "Type" => "Encoding", "Differences" => differences }, "ToUnicode" => unicode
|
||
});
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(600), Object::Integer(400)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
Pdf::new(std::sync::Arc::new(bytes)).unwrap()
|
||
}
|
||
|
||
/// A Thai tone mark or above or below vowel whose font gives it an advance of its own (here 300 units, as every
|
||
/// glyph) moves the pen, so the next letter of the word starts a mark's width past its base. The cluster ends at the
|
||
/// mark: no space opens inside "ข้อความ", "เดิม" or "ผู้ใช้", and the space glyphs between the words still read as
|
||
/// spaces.
|
||
#[test]
|
||
fn a_thai_mark_with_its_own_advance_does_not_open_a_word_gap() {
|
||
let thai = "ข้อความเดิม น้ำ ผู้ใช้";
|
||
for width in [300, 600] {
|
||
let text = extract_page(&one_show_string(thai, width), 0, &InterpreterSettings::default()).unwrap();
|
||
assert_eq!(text.plain_text(), thai, "every glyph {width} units wide");
|
||
for word in ["ข้อความเดิม", "น้ำ", "ผู้ใช้"] {
|
||
assert_eq!(text.find_opts(word, true, true).len(), 1, "{word:?} found as a whole word in {:?}", text.plain_text());
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A one-page document showing `codes` in a Type 0 font with `encoding` over an embedded
|
||
/// `descendant` (`CIDFontType0` takes the bundled CFF program, `CIDFontType2` a TrueType one)
|
||
/// of the Adobe-Japan1 collection, with `to_unicode` as its `/ToUnicode` CMap when given.
|
||
fn japan1_page(encoding: &str, descendant: &str, to_unicode: Option<&[u8]>, codes: &str) -> String {
|
||
collection_page(("Adobe", "Japan1"), encoding, descendant, to_unicode, codes)
|
||
}
|
||
|
||
/// [`japan1_page`] for the character collection `(registry, ordering)`.
|
||
fn collection_page(collection: (&str, &str), encoding: &str, descendant: &str, to_unicode: Option<&[u8]>, codes: &str) -> String {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let (registry, ordering) = collection;
|
||
let mut doc = Document::with_version("1.7");
|
||
let (key, program): (&str, Vec<u8>) = if descendant == "CIDFontType0" {
|
||
let (data, _) = (InterpreterSettings::default().font_resolver)(&craft_pdf::interpret::font::FontQuery::Standard(
|
||
craft_pdf::interpret::font::StandardFont::Courier,
|
||
))
|
||
.expect("bundled Courier stand-in font");
|
||
("FontFile3", (*data).as_ref().to_vec())
|
||
} else {
|
||
("FontFile2", include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec())
|
||
};
|
||
let mut file = dictionary! {};
|
||
if descendant == "CIDFontType0" {
|
||
file.set("Subtype", "CIDFontType0C");
|
||
}
|
||
let program = doc.add_object(Stream::new(file, program));
|
||
let descriptor = doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "TestJapan1", "Flags" => 4, key => program });
|
||
let cid = doc.add_object(dictionary! {
|
||
"Type" => "Font", "Subtype" => descendant, "BaseFont" => "TestJapan1",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal(registry), "Ordering" => Object::string_literal(ordering), "Supplement" => 6 },
|
||
"FontDescriptor" => descriptor, "DW" => 1000, "CIDToGIDMap" => "Identity"
|
||
});
|
||
let mut font = dictionary! { "Type" => "Font", "Subtype" => "Type0", "BaseFont" => "TestJapan1", "Encoding" => encoding, "DescendantFonts" => vec![Object::Reference(cid)] };
|
||
if let Some(cmap) = to_unicode {
|
||
font.set("ToUnicode", doc.add_object(Stream::new(dictionary! {}, cmap.to_vec())));
|
||
}
|
||
let font = doc.add_object(font);
|
||
let content = doc.add_object(Stream::new(dictionary! {}, format!("BT /F1 20 Tf 1 0 0 1 20 250 Tm <{codes}> Tj ET").into_bytes()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text()
|
||
}
|
||
|
||
/// An embedded font of an Adobe character collection reads as text through the collection's
|
||
/// UCS2 CMap, code to CID to Unicode (ISO 32000-2 §9.10.2), where its `/ToUnicode` is missing or
|
||
/// has nothing for a code: with Identity-H or a predefined CMap such as `/H`, CFF or TrueType.
|
||
/// Only fonts that are not embedded took that route, so Japanese and Chinese pages whose fonts
|
||
/// are embedded without a `/ToUnicode` had no text to select, find or copy. `/ToUnicode` still
|
||
/// comes first where it maps a code.
|
||
#[test]
|
||
fn an_embedded_adobe_collection_font_reads_through_its_ucs2_cmap() {
|
||
// Adobe-Japan1 CIDs 34, 1125 and 843: A, 亜 and あ.
|
||
assert_eq!(japan1_page("Identity-H", "CIDFontType0", None, "00220465034B"), "A亜あ", "Identity-H, CFF, no /ToUnicode");
|
||
assert_eq!(japan1_page("Identity-H", "CIDFontType2", None, "00220465034B"), "A亜あ", "Identity-H, TrueType, no /ToUnicode");
|
||
// `/H` maps JIS X 0208 codes to CIDs: 3021 亜, 2422 あ, 2341 A.
|
||
assert_eq!(japan1_page("H", "CIDFontType2", None, "302124222341"), "亜あA", "predefined /H");
|
||
let empty = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Empty def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
assert_eq!(japan1_page("Identity-H", "CIDFontType2", Some(empty), "00220465034B"), "A亜あ", "a /ToUnicode with no mappings");
|
||
let one = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /One def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfchar <0022> <005A> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
assert_eq!(japan1_page("Identity-H", "CIDFontType0", Some(one), "00220465034B"), "Z亜あ", "/ToUnicode first, the UCS2 CMap for the rest");
|
||
}
|
||
|
||
/// The same route for the other Adobe collections, each through its own UCS2 CMap
|
||
/// (Adobe-GB1-UCS2, Adobe-CNS1-UCS2, Adobe-Korea1-UCS2), and for vertical writing (Identity-V)
|
||
/// and a predefined CMap over a CFF program. The pairs are read from the bundled CMaps.
|
||
#[test]
|
||
fn every_adobe_collection_reads_through_its_own_ucs2_cmap() {
|
||
for descendant in ["CIDFontType0", "CIDFontType2"] {
|
||
// Adobe-GB1 CID 4000 is 姓, Adobe-CNS1 CID 4000 is 團, Adobe-Korea1 CID 2000 is 밧; CID 34
|
||
// is A in each.
|
||
for (ordering, codes, text) in [("GB1", "00220FA0", "A姓"), ("CNS1", "00220FA0", "A團"), ("Korea1", "002207D0", "A밧")] {
|
||
assert_eq!(collection_page(("Adobe", ordering), "Identity-H", descendant, None, codes), text, "Adobe-{ordering}, {descendant}");
|
||
}
|
||
assert_eq!(japan1_page("Identity-V", descendant, None, "00220465034B"), "A亜あ", "Identity-V, {descendant}");
|
||
}
|
||
assert_eq!(japan1_page("H", "CIDFontType0", None, "302124222341"), "亜あA", "predefined /H, CFF");
|
||
}
|
||
|
||
/// A Type 0 font outside the Adobe collections has no UCS2 CMap: without a `/ToUnicode` its codes
|
||
/// give no text through this route (the CIDs mean nothing outside their collection).
|
||
#[test]
|
||
fn a_font_outside_the_adobe_collections_gets_no_text_from_a_ucs2_cmap() {
|
||
for descendant in ["CIDFontType0", "CIDFontType2"] {
|
||
assert_eq!(collection_page(("Example", "Custom"), "Identity-H", descendant, None, "00220465034B"), "", "{descendant}");
|
||
}
|
||
}
|
||
|
||
/// A Type 0 font whose `/ToUnicode` is written as a CID CMap (`begincidchar`, destinations as
|
||
/// numbers, as Word writes it) reads each number as the code's Unicode value (vendored
|
||
/// hayro-interpret patch 85), as glyph lookup already did and as pdftotext and PDFium extract it.
|
||
/// Read as a bfchar map only, such text extracted nothing (pdf.js `issue9367`).
|
||
#[test]
|
||
fn a_tounicode_written_as_cid_ranges_gives_text() {
|
||
let two = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Words def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 3 begincidchar <0001> 84 <0002> 101 <0004> 116 endcidchar 1 begincidrange <0003> <0003> 120 endcidrange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
assert_eq!(cid_range_to_unicode_text(two), "Text", "two-byte entries");
|
||
// Entries written with four-byte codes are found too (review on #6359).
|
||
let four = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Words def /CMapType 2 def 1 begincodespacerange <00000000> <FFFFFFFF> endcodespacerange 2 begincidchar <00000001> 84 <00000002> 101 endcidchar 1 begincidrange <00000003> <00000004> 120 endcidrange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
assert_eq!(cid_range_to_unicode_text(four), "Texy", "four-byte entries");
|
||
}
|
||
|
||
/// When a `/ToUnicode` gives one code both a bf entry and a CID entry, the bf entry is the
|
||
/// code's text (ISO 32000-2 §9.10.3 defines `/ToUnicode` by `beginbfchar` / `beginbfrange`); the
|
||
/// CID number is read only for codes no bf entry covers (vendored hayro-interpret patch 85).
|
||
#[test]
|
||
fn a_tounicode_bf_entry_wins_over_a_cid_entry_for_the_same_code() {
|
||
// Codes 1 and 3 have both kinds of entry: bf says `T` / `x`, CID says `X` / `Y`. Codes 2 and 4
|
||
// have CID entries only.
|
||
let two = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Words def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange 3 begincidchar <0001> 88 <0002> 101 <0004> 116 endcidchar 1 begincidrange <0003> <0003> 89 endcidrange 1 beginbfchar <0001> <0054> endbfchar 1 beginbfrange <0003> <0003> <0078> endbfrange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
assert_eq!(cid_range_to_unicode_text(two), "Text", "two-byte entries");
|
||
// The same with one-byte entries. For two-byte entries the CID lookup, tried at one byte
|
||
// first, already falls back to the bf entries at that length; one-byte entries are where
|
||
// reading CID entries before bf entries would show, as `XeYt`.
|
||
let one = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Words def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 3 begincidchar <01> 88 <02> 101 <04> 116 endcidchar 1 begincidrange <03> <03> 89 endcidrange 1 beginbfchar <01> <0054> endbfchar 1 beginbfrange <03> <03> <0078> endbfrange endcmap CMapName currentdict /CMap defineresource pop end end";
|
||
assert_eq!(cid_range_to_unicode_text(one), "Text", "one-byte entries");
|
||
}
|
||
|
||
/// The page [`a_tounicode_written_as_cid_ranges_gives_text`] and
|
||
/// [`a_tounicode_bf_entry_wins_over_a_cid_entry_for_the_same_code`] read: four codes in a Type 0 font
|
||
/// (Inter, Identity-H) whose `/ToUnicode` is `cmap`.
|
||
fn cid_range_to_unicode_text(cmap: &[u8]) -> String {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
let mut doc = Document::with_version("1.7");
|
||
let program = doc.add_object(Stream::new(dictionary! {}, include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec()));
|
||
let descriptor = doc.add_object(dictionary! { "Type" => "FontDescriptor", "FontName" => "Inter-Regular", "Flags" => 4, "FontFile2" => program });
|
||
let cid_font = doc.add_object(dictionary! {
|
||
"Type" => "Font",
|
||
"Subtype" => "CIDFontType2",
|
||
"BaseFont" => "Inter-Regular",
|
||
"CIDSystemInfo" => dictionary! { "Registry" => Object::string_literal("Adobe"), "Ordering" => Object::string_literal("Identity"), "Supplement" => 0 },
|
||
"FontDescriptor" => descriptor,
|
||
"CIDToGIDMap" => "Identity",
|
||
});
|
||
let to_unicode = doc.add_object(Stream::new(dictionary! {}, cmap.to_vec()));
|
||
let font = doc.add_object(dictionary! {
|
||
"Type" => "Font",
|
||
"Subtype" => "Type0",
|
||
"BaseFont" => "Inter-Regular",
|
||
"Encoding" => "Identity-H",
|
||
"DescendantFonts" => vec![Object::Reference(cid_font)],
|
||
"ToUnicode" => to_unicode,
|
||
});
|
||
let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 20 Tf 20 200 Td <0001000200030004> Tj ET".to_vec()));
|
||
let pages = doc.new_object_id();
|
||
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(400), Object::Integer(400)], "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content });
|
||
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
|
||
extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text().trim().to_string()
|
||
}
|
||
|
||
/// A page box that encloses no area is read as a missing one (vendored hayro-syntax patch 38,
|
||
/// ISO 32000-2 §14.11.2): a `/MediaBox [0 0 0 0]` as the default page, a `/CropBox [0 0 0 0]`,
|
||
/// or one with nothing in common with the media box, as the media box. The page's visible region
|
||
/// had no area, so its text was all outside it and none was extracted (pdf.js
|
||
/// `boundingBox_invalid`). Each case is checked on both paths: the text is extracted, and the page
|
||
/// renders at the size of the box that stands in, with the text's ink on it. A page's own box
|
||
/// without area gives way to an inherited one with area; an inherited box without area falls
|
||
/// through to the default as an own one does.
|
||
#[test]
|
||
fn text_on_a_page_whose_box_has_no_area_is_extracted() {
|
||
use lopdf::{Document, Object, Stream, dictionary};
|
||
type Boxes = &'static [(&'static str, [i64; 4])];
|
||
/// (case, inherited boxes, the page's own boxes, where the word goes, expected size).
|
||
type Case = (&'static str, Boxes, Boxes, (i64, i64), (u32, u32));
|
||
/// A one-page document whose `/Pages` node carries `inherited`, and whose page carries `own`
|
||
/// and draws "Boxed" at `(x, y)` in Helvetica 30 pt.
|
||
fn boxed(inherited: Boxes, own: Boxes, (x, y): (i64, i64)) -> Vec<u8> {
|
||
let rect = |r: &[i64; 4]| r.iter().map(|v| Object::Integer(*v)).collect::<Vec<_>>();
|
||
let mut doc = Document::with_version("1.7");
|
||
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
|
||
let pages = doc.new_object_id();
|
||
let ops = format!("BT /F1 30 Tf {x} {y} Td (Boxed) Tj ET");
|
||
let content = doc.add_object(Stream::new(dictionary! {}, ops.into_bytes()));
|
||
let mut page = dictionary! { "Type" => "Page", "Parent" => pages, "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, "Contents" => content };
|
||
for (key, r) in own {
|
||
page.set(*key, rect(r));
|
||
}
|
||
let page = doc.add_object(page);
|
||
let mut node = dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1};
|
||
for (key, r) in inherited {
|
||
node.set(*key, rect(r));
|
||
}
|
||
doc.objects.insert(pages, node.into());
|
||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||
doc.trailer.set("Root", catalog);
|
||
let mut bytes = Vec::new();
|
||
doc.save_to(&mut bytes).unwrap();
|
||
bytes
|
||
}
|
||
// US Letter (612 × 792 pt, hayro-syntax patch 44) covers 612 × 792 device pixels at scale 1.
|
||
const LETTER_PX: (u32, u32) = (612, 792);
|
||
let cases: [Case; 7] = [
|
||
("own MediaBox without area", &[], &[("MediaBox", [0, 0, 0, 0])], (25, 500), LETTER_PX),
|
||
("own CropBox without area", &[], &[("MediaBox", [0, 0, 800, 600]), ("CropBox", [0, 0, 0, 0])], (25, 500), (800, 600)),
|
||
(
|
||
"CropBox touching the media box at a corner",
|
||
&[],
|
||
&[("MediaBox", [0, 0, 600, 800]), ("CropBox", [600, 800, 1000, 1000])],
|
||
(25, 500),
|
||
(600, 800),
|
||
),
|
||
// Text past US Letter but inside the inherited box is kept.
|
||
(
|
||
"own MediaBox without area, inherited one with area",
|
||
&[("MediaBox", [0, 0, 1200, 1200])],
|
||
&[("MediaBox", [0, 0, 0, 0])],
|
||
(700, 900),
|
||
(1200, 1200),
|
||
),
|
||
(
|
||
"own CropBox without area, inherited one with area",
|
||
&[("CropBox", [0, 0, 300, 300])],
|
||
&[("MediaBox", [0, 0, 600, 800]), ("CropBox", [0, 0, 0, 0])],
|
||
(25, 100),
|
||
(300, 300),
|
||
),
|
||
("inherited MediaBox without area", &[("MediaBox", [0, 0, 0, 0])], &[], (25, 500), LETTER_PX),
|
||
("inherited CropBox outside the media box", &[("CropBox", [600, 600, 900, 900])], &[("MediaBox", [0, 0, 500, 500])], (25, 400), (500, 500)),
|
||
];
|
||
let mut failures = Vec::new();
|
||
for (case, inherited, own, at, size) in cases {
|
||
let bytes = boxed(inherited, own, at);
|
||
let pdf = Pdf::new(std::sync::Arc::new(bytes.clone())).unwrap();
|
||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).map(|t| t.plain_text().trim().to_string());
|
||
if text.as_deref() != Some("Boxed") {
|
||
failures.push(format!("{case}: text {text:?}"));
|
||
}
|
||
let mut renderer = crate::PageRenderer::new(std::sync::Arc::new(bytes), crate::RenderConfig::default());
|
||
let out = renderer.render(crate::RenderRequest { page: 0, kind: crate::RequestKind::Pixels, scale: 1.0, ..Default::default() });
|
||
let ink = out.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 128 && p[1] < 128 && p[2] < 128).count();
|
||
if out.error.is_some() || (out.width, out.height) != size || ink < 50 {
|
||
failures.push(format!(
|
||
"{case}: rendered {}×{} with {ink} dark pixels ({:?}), expected {}×{} with ink",
|
||
out.width, out.height, out.error, size.0, size.1
|
||
));
|
||
}
|
||
}
|
||
assert!(failures.is_empty(), "{failures:#?}");
|
||
}
|
||
|
||
/// The glyph under a point is the first whose box holds it, edges included; between glyphs, none.
|
||
#[test]
|
||
fn the_glyph_at_a_point_is_the_first_whose_box_holds_it() {
|
||
let text = PageText {
|
||
glyphs: vec![em_box("a", 0.0, 0.0, 10.0, 10.0), em_box("b", 8.0, 0.0, 20.0, 10.0)],
|
||
line_of: vec![0, 0],
|
||
space_before: vec![false, false],
|
||
truncated: false,
|
||
};
|
||
assert_eq!(text.glyph_at(5.0, 5.0), Some(0));
|
||
assert_eq!(text.glyph_at(9.0, 5.0), Some(0), "the first of overlapping boxes");
|
||
assert_eq!(text.glyph_at(20.0, 10.0), Some(1), "an edge is in");
|
||
assert_eq!(text.glyph_at(25.0, 5.0), None);
|
||
assert_eq!(PageText::default().glyph_at(0.0, 0.0), None);
|
||
}
|
||
|
||
/// A combining mark takes the direction of the letter it rides on (UAX #9 W1, nonspacing marks): a Latin accent at the
|
||
/// end of a Latin word on a right-to-left line stays after its letter, not on the far side of it.
|
||
#[test]
|
||
fn a_latin_mark_at_a_word_end_on_a_right_to_left_line_stays_after_its_letter() {
|
||
// Drawn left to right: "abé" (e and a combining acute riding on it), a space, then "שלום" right to left.
|
||
let mut v = vec![em_box("a", 0.0, 0.0, 6.0, 11.0), em_box("b", 6.0, 0.0, 12.0, 11.0), em_box("e", 12.0, 0.0, 18.0, 11.0)];
|
||
v.push(em_box("\u{301}", 14.0, 0.0, 14.0, 11.0));
|
||
v.push(em_box(" ", 18.0, 0.0, 21.5, 11.0));
|
||
let mut x = 21.5;
|
||
for c in ["ם", "ו", "ל", "ש", "ם", "ו", "ל", "ש"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
assert_eq!(layout(v).plain_text().trim_end(), "שלוםשלום abe\u{301}");
|
||
}
|
||
|
||
/// A line's edge has the line's direction (UAX #9 X10): on a line of mostly left-to-right text, a neutral taken back
|
||
/// over a space at the line's left edge is not inside right-to-left text, so it stays where its position puts it,
|
||
/// however close a Hebrew word is on its other side.
|
||
#[test]
|
||
fn a_taken_back_neutral_at_the_edge_of_a_left_to_right_line_keeps_its_place() {
|
||
let line = |words: &[&str]| {
|
||
let mut v = vec![em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box("(", 9.9, 0.0, 15.0, 11.0)];
|
||
let mut x = 15.0;
|
||
for word in words {
|
||
for c in word.chars() {
|
||
v.push(em_box(&c.to_string(), x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
x += 3.5;
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
// Mostly Latin: x order, "(" first.
|
||
assert_eq!(line(&["םולש", "Hello", "world", "again"]).trim(), "( שלום Hello world again");
|
||
// Mostly Hebrew: the line's edge is right-to-left, so "(" is taken back with the space, as "?" is in
|
||
// `a_space_taken_back_under_the_next_letter_stays_before_it`.
|
||
assert_eq!(line(&["םולש", "םלוע", "AB"]).trim_end(), "AB עולם שלום(");
|
||
}
|
||
|
||
/// Runs that overprint each other are placed by where their clusters start: a combining mark riding on the second
|
||
/// run's first letter and reaching left of the first run's start does not put the second run first.
|
||
#[test]
|
||
fn a_mark_reaching_left_of_its_letter_does_not_reorder_overprinting_runs() {
|
||
// A first run "ABCDEF", then a second run drawn back over it, its "c" starting 1 pt right of "A" and the acute on
|
||
// that "c" reaching 1.5 pt left of "A".
|
||
let mut v: Vec<TextGlyph> =
|
||
"ABCDEF".chars().zip(0u8..).map(|(c, k)| em_box(&c.to_string(), 100.0 + 6.0 * f32::from(k), 0.0, 106.0 + 6.0 * f32::from(k), 11.0)).collect();
|
||
v.push(em_box("c", 101.0, 0.0, 107.0, 11.0));
|
||
v.push(em_box("\u{301}", 98.5, 0.0, 102.5, 11.0));
|
||
v.push(em_box("d", 107.0, 0.0, 113.0, 11.0));
|
||
let text = layout(v).plain_text();
|
||
assert!(text.starts_with("ABCDEF"), "{text:?}");
|
||
assert!(text.contains("c\u{301}d"), "{text:?}");
|
||
}
|
||
|
||
/// A right-to-left mark rides on no glyph, so it keeps its own class: one placed after a Latin
|
||
/// letter, left of the Hebrew letter it belongs to, still reads with the Hebrew word, after its letter.
|
||
#[test]
|
||
fn a_hebrew_mark_after_a_latin_letter_stays_with_the_hebrew_word() {
|
||
let mut v = vec![em_box("a", 0.0, 0.0, 6.0, 11.0), em_box("b", 6.0, 0.0, 12.0, 11.0)];
|
||
v.push(em_box("\u{5B8}", 11.9, 0.0, 11.9, 11.0));
|
||
let mut x = 12.0;
|
||
for c in ["ם", "ו", "ל", "ש"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
let text = layout(v).plain_text();
|
||
// The mark follows its letter, the last of "שלום", before the Latin text.
|
||
assert_eq!(text, "שלום\u{5B8}ab");
|
||
}
|
||
|
||
/// Nonspacing marks count toward neither direction of a line: a line of four Latin letters and a
|
||
/// three-letter Hebrew word whose letters each carry two points reads in the same order as without
|
||
/// the points.
|
||
#[test]
|
||
fn marks_do_not_decide_a_lines_direction() {
|
||
let line = |marks: bool| {
|
||
let mut v: Vec<TextGlyph> =
|
||
["a", "b", "c", "d"].iter().zip(0u8..).map(|(c, k)| em_box(c, 6.0 * f32::from(k), 0.0, 6.0 * f32::from(k) + 6.0, 11.0)).collect();
|
||
let mut x = 27.5;
|
||
for c in ["ו", "ל", "ש"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
if marks {
|
||
v.push(em_box("\u{5B8}", x + 1.0, 0.0, x + 1.0, 11.0));
|
||
v.push(em_box("\u{5B4}", x + 2.0, 0.0, x + 2.0, 11.0));
|
||
}
|
||
x += 6.5;
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
// Compared on the letters alone: the points' own word gaps are not what this is about.
|
||
let letters = |s: String| s.chars().filter(|&c| c != '\u{5B8}' && c != '\u{5B4}' && c != ' ').collect::<String>();
|
||
let marked = line(true);
|
||
for point in ['\u{5B8}', '\u{5B4}'] {
|
||
assert_eq!(marked.chars().filter(|&c| c == point).count(), 3, "every point is kept: {marked:?}");
|
||
}
|
||
assert_eq!(letters(marked), letters(line(false)));
|
||
assert!(letters(line(true)).starts_with("abcd"), "a mostly Latin line reads Latin first");
|
||
}
|
||
|
||
/// A ligature glyph counts each of its letters toward a line's direction: a line of an "ffi" ligature, a word gap and
|
||
/// a two-letter Hebrew word reads as the same line with "f", "f" and "i" drawn one by one, Latin first.
|
||
#[test]
|
||
fn a_ligature_counts_each_of_its_letters_toward_a_lines_direction() {
|
||
let line = |latin: &[&str]| {
|
||
let mut v: Vec<TextGlyph> = Vec::new();
|
||
let step = 12.0 / latin.len() as f32;
|
||
for (k, t) in latin.iter().enumerate() {
|
||
let x = step * k as f32;
|
||
v.push(em_box(t, x, 0.0, x + step, 11.0));
|
||
}
|
||
v.push(em_box("ל", 16.0, 0.0, 22.5, 11.0));
|
||
v.push(em_box("ש", 22.5, 0.0, 29.0, 11.0));
|
||
layout(v).plain_text()
|
||
};
|
||
let split = line(&["f", "f", "i"]);
|
||
assert_eq!(split, "ffi של");
|
||
assert_eq!(line(&["ffi"]), split);
|
||
}
|
||
|
||
/// Punctuation of a right-to-left script is not a letter and doesn't decide a line's direction: two Latin letters,
|
||
/// a Hebrew letter and a maqaf and a sof pasuq after it read Latin first.
|
||
#[test]
|
||
fn right_to_left_punctuation_does_not_decide_a_lines_direction() {
|
||
let mut v = vec![em_box("a", 0.0, 0.0, 6.0, 11.0), em_box("b", 6.0, 0.0, 12.0, 11.0)];
|
||
let mut x = 16.0;
|
||
for c in ["\u{5C3}", "\u{5BE}", "ש"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
let text = layout(v).plain_text();
|
||
assert!(text.starts_with("ab"), "{text:?}");
|
||
}
|
||
|
||
/// An alphabetic nonspacing mark (U+0345) gives the text around a taken-back neutral no direction: a question mark
|
||
/// taken back over the space that starts a reverse-order show string reads as on the same line without the mark.
|
||
#[test]
|
||
fn an_alphabetic_mark_beside_a_taken_back_neutral_gives_it_no_direction() {
|
||
let line = |mark: bool| {
|
||
let mut v = vec![em_box(" ", 10.0, 0.0, 13.5, 11.0), em_box("?", 9.9, 0.0, 15.0, 11.0)];
|
||
let mut x = 15.0;
|
||
for c in ["ף", "י", "ע", "ס"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
x += 6.5;
|
||
}
|
||
if mark {
|
||
v.push(em_box("\u{345}", 14.0, 0.0, 14.0, 11.0));
|
||
}
|
||
layout(v).plain_text()
|
||
};
|
||
let without = line(false);
|
||
assert_eq!(line(true).replace('\u{345}', ""), without);
|
||
}
|
||
|
||
/// A mark of a left-to-right script that rides on no letter has no direction of its own: U+0345 (alphabetic, bidi
|
||
/// class NSM) drawn on the last letter of a Hebrew word, left of it and right after a Latin word, reads with the
|
||
/// Hebrew word, after that letter, as a Hebrew point drawn there does.
|
||
#[test]
|
||
fn an_unattached_alphabetic_mark_reads_with_the_glyphs_at_its_place() {
|
||
let mut v = vec![em_box("a", 0.0, 0.0, 6.0, 11.0), em_box("b", 6.0, 0.0, 12.0, 11.0)];
|
||
let mut x = 12.0;
|
||
for c in ["ם", "ו", "ל", "ש"] {
|
||
v.push(em_box(c, x, 0.0, x + 6.5, 11.0));
|
||
if c == "ם" {
|
||
v.push(em_box("\u{345}", 11.9, 0.0, 11.9, 11.0));
|
||
}
|
||
x += 6.5;
|
||
}
|
||
let text = layout(v).plain_text();
|
||
assert_eq!(text, "שלום\u{345}ab");
|
||
}
|