mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-16 10:56:06 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf90ad450b | ||
|
|
de977bcde6 | ||
|
|
4ba0595760 | ||
|
|
e6e8c61dbf | ||
|
|
1d150004f7 | ||
|
|
7ccfd4caef | ||
|
|
7b3b6f8041 | ||
|
|
fecb717f99 |
@@ -144,6 +144,7 @@ fn parts_and_media() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn many_distinct_media_add_in_linear_time() {
|
||||
// An import with tens of thousands of small distinct images (same length, differing only at
|
||||
// the end) used to compare each against every earlier one.
|
||||
@@ -645,6 +646,7 @@ fn para_of_objects(objs: Vec<InlineObject>) -> Paragraph {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn object_walks_are_linear_in_the_paragraph() {
|
||||
// #3614: loops of object_offsets + object_at recounted the objects before each one, so a
|
||||
// paragraph of 40,000 markers took seconds per walk.
|
||||
@@ -691,6 +693,7 @@ fn object_walks_are_linear_in_the_paragraph() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn deleting_across_many_lone_control_markers_is_not_quadratic() {
|
||||
// A millisecond now; the old delete took 18 s at 1,500 markers and 114 s at 3,000.
|
||||
let n = 3_000;
|
||||
@@ -725,6 +728,7 @@ fn control_markers_kept_are_sorted() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn lone_table_open_markers_linear_time() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(1, 1, 100.0);
|
||||
|
||||
@@ -27,6 +27,7 @@ fn cpu_cost(mut f: impl FnMut()) -> f64 {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn many_comments_save_without_quadratic_id_searches() {
|
||||
for imported in [true, false] {
|
||||
let small = comments(4_000, imported);
|
||||
|
||||
@@ -74,6 +74,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> (
|
||||
/// looked for each paragraph's markers in the whole set of markers, once per paragraph, so a
|
||||
/// document with 32,000 controls took four seconds to save where it takes a tenth of one now.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn a_document_with_many_inline_content_controls_saves_in_linear_time() {
|
||||
let scale = 4;
|
||||
let small = inline_controls(8_000);
|
||||
@@ -94,6 +95,7 @@ fn a_document_with_many_inline_content_controls_saves_in_linear_time() {
|
||||
/// The same for the controls written around whole paragraphs: the writer compared every control
|
||||
/// with every other one to find the ones that clash, so the save was quadratic in their number.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn a_document_with_many_block_content_controls_saves_in_linear_time() {
|
||||
let scale = 4;
|
||||
let small = block_controls(8_000);
|
||||
|
||||
@@ -152,6 +152,7 @@ fn many_fields_and_huge_attribute_values() {
|
||||
/// A paragraph with 2,000,000 attributes deflates to ~15 KB. Opening it is refused with a
|
||||
/// limit error, or the extras are dropped and the text survives (#3702, WC-06).
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn millions_of_attributes_on_one_paragraph_are_capped() {
|
||||
let attrs: String = (0..2_000_000).map(|i| format!(" a{i}=\"\"")).collect();
|
||||
let x = format!("<w:document {W_NS}><w:body><w:p{attrs}><w:r><w:t>kept</w:t></w:r></w:p></w:body></w:document>");
|
||||
@@ -222,6 +223,7 @@ fn malformed_or_hostile_bibliography_never_panics() {
|
||||
/// A file with a huge number of bibliography sources (duplicates and distinct ones) reads in
|
||||
/// linear time and keeps at most 10,000 of them.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn hostile_bibliography_source_count_is_capped() {
|
||||
let doc = format!("<w:document {W_NS}><w:body><w:p><w:r><w:t>body</w:t></w:r></w:p></w:body></w:document>");
|
||||
let mut sources = String::from(r#"<b:Sources xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography" StyleName="MLA">"#);
|
||||
|
||||
@@ -845,6 +845,7 @@ fn citation_source_lookups_keep_first_duplicates_case_and_style_order() {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn citation_refresh_source_lookup_work_scales_with_document_size() {
|
||||
fn doc(n: usize) -> Session {
|
||||
let mut p = Paragraph::new();
|
||||
|
||||
@@ -316,6 +316,7 @@ mod tests {
|
||||
|
||||
/// Drawing commands must not search every page again for each glued connector.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
let mut doc = Document::new();
|
||||
|
||||
@@ -799,6 +799,7 @@ fn deleting_a_comment_in_a_parent_cycle_ends() {
|
||||
/// A very long reply chain (as a hostile file could hold) is deleted in one pass over the
|
||||
/// comments, not one pass per reply: 50,000 replies would otherwise freeze the app.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn deleting_a_long_reply_chain_stays_fast() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.view.proofing = false;
|
||||
|
||||
@@ -102,6 +102,7 @@ fn tidy_matches_replacing_until_nothing_changes() {
|
||||
/// Nested empty brackets are removed in one pass: 40,000 pairs took seconds when each pass
|
||||
/// removed one level (#3680).
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn tidy_is_linear_on_nested_brackets() {
|
||||
let n = 40_000;
|
||||
let started = std::time::Instant::now();
|
||||
|
||||
@@ -1050,6 +1050,7 @@ fn rep_mode(text: &str, q: &str, with: &str, extra: serde_json::Value) -> String
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn hostile_find_patterns_are_bounded() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": &"a".repeat(5000)}));
|
||||
@@ -11918,6 +11919,7 @@ fn inspect_document_removes_the_note_of_a_hidden_reference() {
|
||||
/// #1344: many hidden pieces (index entries are hidden text) are removed quickly, and the
|
||||
/// found list is capped.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn inspect_document_removes_thousands_of_hidden_pieces() {
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_doc::{Paragraph, para_block};
|
||||
|
||||
@@ -450,6 +450,7 @@ fn long_names_are_cut_before_faces_copy_them() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn named_instances_and_collection_members_are_capped() {
|
||||
// #3716: a file's faces are capped before they are built, however the file multiplies them.
|
||||
let font = variable_font(300);
|
||||
|
||||
@@ -488,6 +488,7 @@ fn code_blocks_and_rules() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn deep_nesting_is_bounded() {
|
||||
let html = "<div><table><tr><td>".repeat(5000) + "x";
|
||||
let d = import("html", html.as_bytes()).unwrap().unwrap();
|
||||
@@ -566,6 +567,7 @@ fn latex_export_carries_no_commands_from_the_document() {
|
||||
/// past them for the last text made a megabyte of labels take tens of seconds), and labels
|
||||
/// separated by text are all kept.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn latex_labels_in_a_row_are_read_in_linear_time() {
|
||||
let started = std::time::Instant::now();
|
||||
for src in ["\\label{a} ".repeat(100_000) + "x", "\\label{a}".repeat(100_000) + "x", "\\hypertarget{a}{} ".repeat(100_000)] {
|
||||
@@ -743,6 +745,7 @@ fn decorative_picture_exports_with_empty_alt_text() {
|
||||
/// Hostile Markdown and HTML that rescanned the rest of the text from every `[`, `![`, `<` or `&`
|
||||
/// took quadratic time: a few hundred KB froze the importer for tens of seconds.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn hostile_importer_input_takes_linear_time() {
|
||||
use std::time::{Duration, Instant};
|
||||
let cases: [(&str, String); 5] = [
|
||||
@@ -764,6 +767,7 @@ fn hostile_importer_input_takes_linear_time() {
|
||||
/// bracket scan over them looking for a closing run through the rest of the text: superlinear
|
||||
/// time on hostile Markdown.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn unmatched_backtick_runs_take_linear_time() {
|
||||
use std::time::{Duration, Instant};
|
||||
// Runs of 1, 2, … 2000 backticks (2 MB), none of them closed.
|
||||
|
||||
@@ -307,7 +307,7 @@ fn decode_alpha(bytes: &[u8], decoded: &mut u64) -> Result<Option<Alpha>, OverBu
|
||||
fn alpha_in_crop(img: &Alpha, crop: [f32; 4]) -> Option<Vec<(f32, f32)>> {
|
||||
let (iw, ih) = (img.w, img.h);
|
||||
// The part the renderers draw (#1899): a sliver keeps its partly covered pixels.
|
||||
let [cl, ct, vw, vh] = craft_metafile::crop_window(crop);
|
||||
let [cl, ct, vw, vh] = crate::crop_window(crop);
|
||||
let (fw, fh) = (f64::from(iw), f64::from(ih));
|
||||
let x0 = ((fw * cl) as u32).min(iw);
|
||||
let y0 = ((fh * ct) as u32).min(ih);
|
||||
|
||||
@@ -59,6 +59,7 @@ mod ctx;
|
||||
mod floats;
|
||||
mod flow;
|
||||
mod headers;
|
||||
mod metafile;
|
||||
mod missing;
|
||||
mod notes;
|
||||
mod page;
|
||||
@@ -85,6 +86,7 @@ use headers::MAX_HEADER_ITEMS;
|
||||
#[cfg(test)]
|
||||
use headers::placed_cost;
|
||||
use headers::placed_cost_by;
|
||||
pub use metafile::{MAX_METAFILE_DASHES, crop_sides, crop_window, metafile_average_color, metafile_dashes, metafile_miter_limit};
|
||||
pub use missing::{MAX_MISSING_GLYPHS, MissingGlyphs, metafile_text_run, missing_watermark_glyphs, watermark_run};
|
||||
pub use notes::DECOR_STORY;
|
||||
pub(crate) use notes::NOTE_SEP_W;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Drawing rules the page renderer and the PDF export share for metafile pictures and picture
|
||||
//! crops, so the two outputs draw the same file the same way.
|
||||
|
||||
/// Most dashes and gaps one metafile stroke is split into. A path that a pen's pattern would split
|
||||
/// into more draws solid.
|
||||
pub const MAX_METAFILE_DASHES: f64 = 100_000.0;
|
||||
|
||||
/// The crop sides a picture is drawn with: each side of `crop` (left, top, right, bottom fractions
|
||||
/// of the source) at least 0. A negative side draws as no crop, not as padding around the source.
|
||||
pub fn crop_sides(crop: [f32; 4]) -> [f32; 4] {
|
||||
crop.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 })
|
||||
}
|
||||
|
||||
/// The part of a picture's source that `crop` keeps, as fractions of the source: [left, top,
|
||||
/// width, height] (`craft_metafile::crop_window` of [`crop_sides`]).
|
||||
pub fn crop_window(crop: [f32; 4]) -> [f64; 4] {
|
||||
craft_metafile::crop_window(crop_sides(crop))
|
||||
}
|
||||
|
||||
/// The miter limit a metafile pen is drawn with: its own when it is finite and at least 1,
|
||||
/// otherwise 10.
|
||||
pub fn metafile_miter_limit(limit: f32) -> f32 {
|
||||
if limit.is_finite() && limit >= 1.0 { limit } else { 10.0 }
|
||||
}
|
||||
|
||||
/// The dash lengths (page points) a metafile pen draws a path `length` points long with, or None
|
||||
/// for a solid line. `dash` is the placed pen's pattern (`craft_metafile::LineStyle::dash`, page
|
||||
/// points) and `pixel` is one output pixel in points.
|
||||
///
|
||||
/// A cosmetic pen (`cosmetic`: width 0) has its pattern scaled so that its shortest dash or gap is
|
||||
/// one pixel, at any zoom. A pattern with a negative or non-finite length draws solid, and so does
|
||||
/// one whose period is shorter than a pixel or that would split the path into more than
|
||||
/// [`MAX_METAFILE_DASHES`] dashes and gaps.
|
||||
pub fn metafile_dashes(dash: &[f32], cosmetic: bool, pixel: f64, length: f64) -> Option<Vec<f64>> {
|
||||
if dash.is_empty() || !pixel.is_finite() || pixel <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<f64> = dash.iter().map(|d| f64::from(*d)).collect();
|
||||
if !out.iter().all(|d| d.is_finite() && *d >= 0.0) {
|
||||
return None;
|
||||
}
|
||||
if cosmetic {
|
||||
let shortest = out.iter().copied().filter(|d| *d > 0.0).fold(f64::INFINITY, f64::min);
|
||||
if !shortest.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let k = pixel / shortest;
|
||||
out.iter_mut().for_each(|d| *d *= k);
|
||||
}
|
||||
let period: f64 = out.iter().sum();
|
||||
if !period.is_finite() || period < pixel {
|
||||
return None;
|
||||
}
|
||||
// Each length of the pattern starts a new dash or gap.
|
||||
let pieces = out.len() as f64 * if length.is_finite() { length.max(0.0) / period } else { f64::INFINITY };
|
||||
(pieces <= MAX_METAFILE_DASHES).then_some(out)
|
||||
}
|
||||
|
||||
/// The alpha-weighted average color of straight RGBA pixels (transparent when there are none): a
|
||||
/// metafile pattern fill whose tile is too small to show is filled with it.
|
||||
pub fn metafile_average_color(px: &[u8]) -> [u8; 4] {
|
||||
let (mut r, mut g, mut b, mut a, mut n) = (0u64, 0u64, 0u64, 0u64, 0u64);
|
||||
for p in px.as_chunks::<4>().0 {
|
||||
let w = u64::from(p[3]);
|
||||
r += u64::from(p[0]) * w;
|
||||
g += u64::from(p[1]) * w;
|
||||
b += u64::from(p[2]) * w;
|
||||
a += w;
|
||||
n += 1;
|
||||
}
|
||||
if a == 0 || n == 0 {
|
||||
return [0; 4];
|
||||
}
|
||||
[(r / a) as u8, (g / a) as u8, (b / a) as u8, (a / n) as u8]
|
||||
}
|
||||
@@ -151,13 +151,37 @@ pub fn watermark_run(wm: &wordcraft_doc::Watermark, max_chars: usize) -> Option<
|
||||
/// in the face its font name resolves to (no fallback face), so a character that face lacks shapes
|
||||
/// to glyph id 0. Strict export checks these same glyphs, so the check and the exporters can't
|
||||
/// drift.
|
||||
pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec<ShapedGlyph>) {
|
||||
let family = t.font.family.trim();
|
||||
let family = if family.is_empty() { METAFILE_DEFAULT_FONT } else { family };
|
||||
let face = wordcraft_fonts::word::resolve(family, t.font.weight >= 600, t.font.italic).face;
|
||||
let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c);
|
||||
(face, shaped)
|
||||
}
|
||||
|
||||
/// The face a metafile font with no face name is drawn in.
|
||||
const METAFILE_DEFAULT_FONT: &str = "Arial";
|
||||
/// The cell height (text units) of a metafile font whose height is 0, the file's default size.
|
||||
const METAFILE_DEFAULT_HEIGHT: f64 = 16.0;
|
||||
|
||||
/// A metafile text run laid out with a font's metrics: the em size (text units), the baseline's y
|
||||
/// and each glyph's (x, y), alignment included, in the run's text space (see
|
||||
/// `craft_metafile::Text::transform`).
|
||||
pub struct MetafileTextLayout {
|
||||
pub em: f64,
|
||||
pub baseline: f64,
|
||||
pub glyphs: Vec<(f64, f64)>,
|
||||
/// The rectangle of the character cells (x0, y0, x1, y1): from the leftmost to the rightmost
|
||||
/// pen position of the run, the font's ascent above the baseline and its descent below. An
|
||||
/// opaque background fills it.
|
||||
pub cell: [f64; 4],
|
||||
}
|
||||
|
||||
/// Lay out shaped glyphs for a metafile text run.
|
||||
/// Lays out the shaped glyphs of `t`, given as (cluster byte offset, x advance, x offset, y offset)
|
||||
/// in font units of a font with `upem` units per em, `ascent` above and `descent` below the
|
||||
/// baseline. The font height is the em size when negative and the cell height (ascent plus
|
||||
/// descent) when positive. The per-character advances `dx` place each cluster when there is one
|
||||
/// per character. None when the size is not finite and positive.
|
||||
pub fn layout_metafile_text(
|
||||
t: &craft_metafile::Text,
|
||||
upem: f64,
|
||||
@@ -166,10 +190,9 @@ pub fn layout_metafile_text(
|
||||
glyphs: &[(usize, f64, f64, f64)],
|
||||
) -> Option<MetafileTextLayout> {
|
||||
let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 };
|
||||
let cell_h = ascent + descent;
|
||||
let size = if t.font.height == 0.0 { 12.0 } else { f64::from(t.font.height.abs()) };
|
||||
let cell = t.font.height > 0.0;
|
||||
let em = if cell && cell_h.is_finite() && cell_h > 0.0 { size * upem / cell_h } else { size };
|
||||
let height = if t.font.height == 0.0 { METAFILE_DEFAULT_HEIGHT } else { f64::from(t.font.height) };
|
||||
let cell = ascent + descent;
|
||||
let em = if height > 0.0 && cell.is_finite() && cell > 0.0 { height * upem / cell } else { height.abs() };
|
||||
if !em.is_finite() || em <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
@@ -187,6 +210,8 @@ pub fn layout_metafile_text(
|
||||
});
|
||||
let mut out = Vec::with_capacity(glyphs.len());
|
||||
let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None);
|
||||
// The leftmost and rightmost pen positions: advances can move backward.
|
||||
let (mut lo, mut hi) = (0.0f64, 0.0f64);
|
||||
for &(cluster, adv, xo, yo) in glyphs {
|
||||
let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1);
|
||||
if last != Some(ci) {
|
||||
@@ -199,6 +224,10 @@ pub fn layout_metafile_text(
|
||||
};
|
||||
out.push((x + xo * k, -yo * k));
|
||||
pen += adv * k;
|
||||
(lo, hi) = (lo.min(pen), hi.max(pen));
|
||||
}
|
||||
if let Some(cum) = &dx {
|
||||
(lo, hi) = cum.iter().fold((0.0f64, 0.0f64), |(l, h), x| (l.min(*x), h.max(*x)));
|
||||
}
|
||||
let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen);
|
||||
let hoff = match t.h_align {
|
||||
@@ -212,14 +241,8 @@ pub fn layout_metafile_text(
|
||||
craft_metafile::VAlign::Bottom => -descent * k,
|
||||
};
|
||||
let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect();
|
||||
Some(MetafileTextLayout { em, baseline, glyphs })
|
||||
}
|
||||
|
||||
pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec<ShapedGlyph>) {
|
||||
let bold = t.font.weight >= 600;
|
||||
let face = wordcraft_fonts::word::resolve(&t.font.family, bold, t.font.italic).face;
|
||||
let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c);
|
||||
(face, shaped)
|
||||
let cell = [hoff + lo, baseline - ascent * k, hoff + hi, baseline + descent * k];
|
||||
Some(MetafileTextLayout { em, baseline, glyphs, cell })
|
||||
}
|
||||
|
||||
/// The characters of the watermark that draw as an empty box (glyph id 0), counted as
|
||||
|
||||
@@ -923,6 +923,7 @@ fn a_long_unbreakable_word_lays_out_in_linear_time() {
|
||||
|
||||
/// A word a megabyte long lays out in a fraction of a second: it used to take half a minute.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn a_megabyte_long_word_lays_out_quickly() {
|
||||
let d = long_word_beside_a_float(1_000_000);
|
||||
let t = std::time::Instant::now();
|
||||
@@ -1143,6 +1144,7 @@ fn a_word_with_alternating_advances_lays_out_in_linear_time() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn hidden_separators_with_automatic_hyphenation_lay_out_in_linear_time() {
|
||||
crate::test_fonts();
|
||||
// "hyphenation " n times with every space hidden: one joined word of 11n letters reaches the
|
||||
@@ -1175,6 +1177,7 @@ fn page_break_paragraphs(n: usize) -> Document {
|
||||
/// the section list by walking the whole body, so a document of n paragraphs paid n body-length
|
||||
/// scans: a two-megabyte file took half a minute before the first page was drawn.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn a_document_of_many_paragraphs_lays_out_in_linear_time() {
|
||||
let (t1, tk, ratio) = layout_time_ratio(page_break_paragraphs, 2_500, &LayoutOptions::default());
|
||||
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
|
||||
@@ -1182,6 +1185,7 @@ fn a_document_of_many_paragraphs_lays_out_in_linear_time() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn many_hidden_float_anchors_lay_out_in_linear_time() {
|
||||
crate::test_fonts();
|
||||
// n square-wrapped shapes, each anchored in its own hidden run (bold alternating, so runs do not
|
||||
|
||||
@@ -242,3 +242,62 @@ fn an_equation_run_names_each_glyphs_characters() {
|
||||
assert!(found.iter().any(|(t, g, _)| (t.contains('\u{1D44E}') || t == "ab") && *g == 2), "{found:?}");
|
||||
assert!(found.iter().all(|(_, g, r)| g == r), "{found:?}");
|
||||
}
|
||||
|
||||
/// A metafile text run with the given font height and advances, left-aligned at the baseline.
|
||||
fn meta_text(height: f32, dx: Vec<f32>) -> craft_metafile::Text {
|
||||
craft_metafile::Text {
|
||||
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
text: "ab".into(),
|
||||
dx,
|
||||
font: craft_metafile::Font { family: "Arial".into(), height, ..Default::default() },
|
||||
color: [0, 0, 0, 255],
|
||||
background: Some([255, 255, 255, 255]),
|
||||
h_align: craft_metafile::HAlign::Left,
|
||||
v_align: craft_metafile::VAlign::Baseline,
|
||||
clip: None,
|
||||
region: None,
|
||||
clips: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile font height of 0 is the file's default size: a 16-unit cell. A negative height is
|
||||
/// the em size, and a positive one the cell (ascent plus descent, 1200 units of a 1000-unit em
|
||||
/// here).
|
||||
#[test]
|
||||
fn metafile_text_heights() {
|
||||
let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)];
|
||||
let em = |h| crate::layout_metafile_text(&meta_text(h, Vec::new()), 1000.0, 900.0, 300.0, &glyphs).map(|l| l.em);
|
||||
let near = |a: Option<f64>, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-9);
|
||||
assert!(near(em(0.0), 16.0 * 1000.0 / 1200.0), "{:?}", em(0.0));
|
||||
assert!(near(em(-10.0), 10.0), "{:?}", em(-10.0));
|
||||
assert!(near(em(24.0), 20.0), "a positive height is the cell: {:?}", em(24.0));
|
||||
}
|
||||
|
||||
/// A cosmetic pen's dashes become whole output pixels (the shortest one pixel), a period under a
|
||||
/// pixel draws solid, and so does a pattern that would split the path into too many pieces.
|
||||
#[test]
|
||||
fn metafile_dashes_follow_the_output_pixel() {
|
||||
let cosmetic = crate::metafile_dashes(&[0.75, 0.25], true, 0.5, 100.0).unwrap_or_default();
|
||||
assert!(cosmetic.len() == 2 && (cosmetic[0] - 1.5).abs() < 1e-6 && (cosmetic[1] - 0.5).abs() < 1e-6, "{cosmetic:?}");
|
||||
assert_eq!(crate::metafile_dashes(&[3.0, 1.0], false, 0.5, 100.0), Some(vec![3.0, 1.0]));
|
||||
assert_eq!(crate::metafile_dashes(&[0.2, 0.2], false, 0.5, 100.0), None, "a period under a pixel");
|
||||
assert_eq!(crate::metafile_dashes(&[1.0, 1.0], false, 0.5, 1e6), None, "a million pieces");
|
||||
assert_eq!(crate::metafile_dashes(&[1.0, -1.0], false, 0.5, 100.0), None, "a negative length");
|
||||
assert_eq!(crate::metafile_dashes(&[0.0, 0.0], true, 0.5, 100.0), None, "no length at all");
|
||||
}
|
||||
|
||||
/// A negative crop side is no crop; the others stay as they are.
|
||||
#[test]
|
||||
fn negative_crop_sides_are_no_crop() {
|
||||
assert_eq!(crate::crop_sides([-0.5, 0.25, f32::NAN, 1.5]), [0.0, 0.25, 0.0, 1.5]);
|
||||
assert_eq!(crate::crop_window([-0.5, 0.0, 0.0, 0.0]), [0.0, 0.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// The opaque background of a run whose advances move backward covers every pen position, not
|
||||
/// only the run's total advance.
|
||||
#[test]
|
||||
fn metafile_text_cell_spans_backward_advances() {
|
||||
let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)];
|
||||
let lay = crate::layout_metafile_text(&meta_text(-10.0, vec![50.0, -40.0]), 1000.0, 800.0, 200.0, &glyphs).expect("a layout");
|
||||
assert_eq!(lay.cell, [0.0, -8.0, 50.0, 2.0]);
|
||||
}
|
||||
|
||||
@@ -117,6 +117,7 @@ fn resolve_uses_the_given_system_locale() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn context_mode_on_a_very_long_digit_run_stays_linear() {
|
||||
crate::test_fonts();
|
||||
// Every digit used to scan back over all the digits and spaces before it (O(n²)).
|
||||
|
||||
@@ -320,7 +320,7 @@ impl Exporter<'_> {
|
||||
s.set_fill(None);
|
||||
return;
|
||||
};
|
||||
let [cl, ct, vis_w, vis_h] = craft_metafile::crop_window(*crop).map(|v| v as f32);
|
||||
let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop).map(|v| v as f32);
|
||||
let (fw, fh) = (rect.w / vis_w, rect.h / vis_h);
|
||||
let Some(size) = Size::from_wh(fw.max(0.01), fh.max(0.01)) else { return };
|
||||
let fade = alpha < 0.999;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, glyph_outlines,
|
||||
left_to_right, norm, ok, paint_of, rgb, split_clusters, visual_order,
|
||||
Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rect, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id,
|
||||
glyph_outlines, left_to_right, norm, ok, paint_of, rect_path, rgb, split_clusters, visual_order,
|
||||
};
|
||||
|
||||
/// How a run of glyphs is painted: its colour, opacity and synthetic bold and italic.
|
||||
@@ -181,7 +181,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
|
||||
/// Draws a metafile text run as PDF text (outlines when the font cannot be embedded). `tf` maps
|
||||
/// the run's own space (see [`PlacedItem::Text`]) to the page.
|
||||
/// its text space (`craft_metafile::Text::transform`) to the page.
|
||||
pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &craft_metafile::Text, tf: kurbo::Affine) {
|
||||
let (face, shaped) = wordcraft_layout::metafile_text_run(t);
|
||||
let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect();
|
||||
@@ -198,6 +198,15 @@ impl Exporter<'_> {
|
||||
let (paint, opacity) = paint_of(t.color);
|
||||
s.push_transform(&Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]));
|
||||
s.set_stroke(None);
|
||||
// An opaque background mode fills the character cells first.
|
||||
if let Some(bg) = t.background {
|
||||
let [x0, y0, x1, y1] = lay.cell.map(|v| v as f32);
|
||||
if let Some(cell) = rect_path(&Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }) {
|
||||
let (paint, opacity) = paint_of(bg);
|
||||
s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero }));
|
||||
s.draw_path(&cell);
|
||||
}
|
||||
}
|
||||
s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero }));
|
||||
match font {
|
||||
Some(font) => {
|
||||
|
||||
+145
-26
@@ -1,28 +1,51 @@
|
||||
use super::exporter::Exporter;
|
||||
use super::paint::{append_path, norm};
|
||||
use super::{
|
||||
Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, Surface, Transform, rgb,
|
||||
Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, StrokeDash, Surface,
|
||||
Transform, krilla, rgb,
|
||||
};
|
||||
use craft_metafile::Item;
|
||||
use kurbo::Shape as _;
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
/// Largest picture side we embed (pixels).
|
||||
const MAX_IMAGE_SIDE: u32 = 30_000;
|
||||
|
||||
/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps are
|
||||
/// embedded images, one per picture item (None for paths and undecodable bitmaps).
|
||||
/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps and
|
||||
/// pattern tiles are embedded images, one per picture item (None for paths, text and undecodable
|
||||
/// bitmaps). Fills that share a tile share its image. `averages` holds each pattern fill's tile
|
||||
/// average color (transparent for other items), computed once a tile.
|
||||
pub(crate) struct Vector {
|
||||
pic: Picture,
|
||||
images: Vec<Option<Image>>,
|
||||
averages: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
/// Parses a metafile and embeds its bitmaps. None when the picture has no usable size.
|
||||
/// Parses a metafile and embeds its bitmaps and pattern tiles. None when the picture has no usable
|
||||
/// size.
|
||||
pub(crate) fn build_vector(bytes: &[u8]) -> Option<Vector> {
|
||||
let mut pic = craft_metafile::parse(bytes).ok()?;
|
||||
if !pic.has_size() {
|
||||
return None;
|
||||
}
|
||||
let images = pic.items.iter_mut().map(|it| it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h))).collect();
|
||||
Some(Vector { pic, images })
|
||||
let mut tiles: std::collections::HashMap<usize, (Option<Image>, [u8; 4])> = std::collections::HashMap::new();
|
||||
let (images, averages) = pic
|
||||
.items
|
||||
.iter_mut()
|
||||
.map(|it| match it {
|
||||
Item::Pattern { tile, .. } => tiles
|
||||
.entry(Arc::as_ptr(tile) as usize)
|
||||
.or_insert_with(|| {
|
||||
let n = (tile.width as usize).saturating_mul(tile.height as usize).saturating_mul(4);
|
||||
let img = (tile.width > 0 && tile.height > 0 && tile.rgba.len() == n)
|
||||
.then(|| Image::from_rgba8(tile.rgba.clone(), tile.width, tile.height));
|
||||
(img, wordcraft_layout::metafile_average_color(&tile.rgba))
|
||||
})
|
||||
.clone(),
|
||||
_ => (it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h)), [0; 4]),
|
||||
})
|
||||
.unzip();
|
||||
Some(Vector { pic, images, averages })
|
||||
}
|
||||
|
||||
/// A straight RGBA colour as a krilla colour and opacity.
|
||||
@@ -36,9 +59,10 @@ pub(crate) fn paint_of(c: [u8; 4]) -> (rgb::Color, NormalizedF32) {
|
||||
const HAIRLINE: f64 = 0.25;
|
||||
|
||||
/// Draws a metafile picture into the clip (the picture frame): paths are filled and stroked in page
|
||||
/// space (strokes keep their width under non-uniform scaling), bitmaps stretched, all faded by `alpha`.
|
||||
/// Every path sets its fill and stroke, so none carries over; strokes have round caps and joins. Text
|
||||
/// runs are drawn as text.
|
||||
/// space (strokes keep their width under non-uniform scaling), bitmaps stretched (or turned by their
|
||||
/// transform), pattern fills tiled, each item inside its clip region and clip paths, all faded by
|
||||
/// `alpha`. Every path sets its fill and stroke, so none carries over; strokes take the pen's caps,
|
||||
/// joins and dashes. Text runs are drawn as text.
|
||||
pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: &Rect, crop: &[f32; 4], clip: &Path, alpha: f32) {
|
||||
let target = kurbo::Rect::new(f64::from(r.x), f64::from(r.y), f64::from(r.x + r.w), f64::from(r.y + r.h));
|
||||
let fade = alpha < 0.999;
|
||||
@@ -46,9 +70,9 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
|
||||
s.push_opacity(norm(alpha));
|
||||
}
|
||||
s.push_clip_path(clip, &FillRule::NonZero);
|
||||
for it in v.pic.place(target, *crop) {
|
||||
for it in v.pic.place(target, wordcraft_layout::crop_sides(*crop)) {
|
||||
match it {
|
||||
PlacedItem::Path { path, fill, stroke, even_odd, .. } => {
|
||||
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => {
|
||||
let Some(p) = path_from(&path) else { continue };
|
||||
let fill = fill.map(|c| {
|
||||
let (paint, opacity) = paint_of(c);
|
||||
@@ -57,31 +81,63 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
|
||||
});
|
||||
let stroke = stroke.map(|(c, w)| {
|
||||
let (paint, opacity) = paint_of(c);
|
||||
Stroke {
|
||||
paint: paint.into(),
|
||||
width: w.max(HAIRLINE) as f32,
|
||||
opacity,
|
||||
line_cap: LineCap::Round,
|
||||
line_join: LineJoin::Round,
|
||||
..Default::default()
|
||||
}
|
||||
pen(paint.into(), opacity, w, &line, &path)
|
||||
});
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
s.set_fill(fill);
|
||||
s.set_stroke(stroke);
|
||||
s.draw_path(&p);
|
||||
pop_clips(s, n);
|
||||
}
|
||||
PlacedItem::Bitmap { index, rect, .. } => {
|
||||
PlacedItem::Bitmap { index, rect, transform, region, clips } => {
|
||||
let Some(Some(img)) = v.images.get(index) else { continue };
|
||||
let Some(size) = Size::from_wh(rect.width() as f32, rect.height() as f32) else { continue };
|
||||
s.push_transform(&Transform::from_translate(rect.x0 as f32, rect.y0 as f32));
|
||||
let c = transform.as_coeffs();
|
||||
// Upright and not mirrored: the bitmap fills `rect`.
|
||||
let upright = c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0;
|
||||
let (tf, size) = if upright {
|
||||
(Transform::from_translate(rect.x0 as f32, rect.y0 as f32), Size::from_wh(rect.width() as f32, rect.height() as f32))
|
||||
} else {
|
||||
// A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place.
|
||||
let c = c.map(|v| v as f32);
|
||||
(Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), Size::from_wh(1.0, 1.0))
|
||||
};
|
||||
let Some(size) = size else { continue };
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
s.push_transform(&tf);
|
||||
s.draw_image(img.clone(), size);
|
||||
s.pop();
|
||||
pop_clips(s, n);
|
||||
}
|
||||
PlacedItem::Pattern { .. } => {}
|
||||
PlacedItem::Text { index, transform, .. } => {
|
||||
if let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) {
|
||||
ex.vector_text(s, t, transform);
|
||||
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => {
|
||||
let Some(p) = path_from(&path) else { continue };
|
||||
let Some(craft_metafile::Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { continue };
|
||||
let rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
let paint = match v.images.get(index) {
|
||||
Some(Some(img)) => tile_pattern(s, img, t.width, t.height, tile).map(|p| (p.into(), norm(1.0))),
|
||||
_ => None,
|
||||
};
|
||||
let (paint, opacity) = paint.unwrap_or_else(|| {
|
||||
let (c, o) = paint_of(v.averages.get(index).copied().unwrap_or([0; 4]));
|
||||
(c.into(), o)
|
||||
});
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
s.set_fill(Some(Fill { paint, opacity, rule }));
|
||||
s.set_stroke(None);
|
||||
s.draw_path(&p);
|
||||
pop_clips(s, n);
|
||||
}
|
||||
PlacedItem::Text { index, transform, clip, region, clips } => {
|
||||
let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) else { continue };
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
let text_clip = clip.and_then(|c| path_from(&c.to_path(0.1)));
|
||||
if let Some(c) = &text_clip {
|
||||
s.push_clip_path(c, &FillRule::NonZero);
|
||||
}
|
||||
ex.vector_text(s, t, transform);
|
||||
if text_clip.is_some() {
|
||||
s.pop();
|
||||
}
|
||||
pop_clips(s, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +149,69 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes a metafile item's clip region and clip paths; pop them with [`pop_clips`] and the count
|
||||
/// returned. None (nothing pushed) when a clip has no area to draw in.
|
||||
fn push_clips(s: &mut Surface, region: Option<&kurbo::BezPath>, clips: &[Arc<craft_metafile::PlacedClip>]) -> Option<usize> {
|
||||
let mut paths = Vec::with_capacity(clips.len() + 1);
|
||||
if let Some(region) = region {
|
||||
paths.push((path_from(region)?, FillRule::NonZero));
|
||||
}
|
||||
for c in clips {
|
||||
paths.push((path_from(&c.path)?, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero }));
|
||||
}
|
||||
for (p, rule) in &paths {
|
||||
s.push_clip_path(p, rule);
|
||||
}
|
||||
Some(paths.len())
|
||||
}
|
||||
|
||||
fn pop_clips(s: &mut Surface, n: usize) {
|
||||
for _ in 0..n {
|
||||
s.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile pen for `path`: `width` (points, at least [`HAIRLINE`]), the pen's caps, joins,
|
||||
/// miter limit and dashes (`wordcraft_layout::metafile_dashes`, with the hairline as the pixel).
|
||||
fn pen(paint: krilla::paint::Paint, opacity: NormalizedF32, width: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> Stroke {
|
||||
let line_cap = match line.cap {
|
||||
craft_metafile::Cap::Round => LineCap::Round,
|
||||
craft_metafile::Cap::Square => LineCap::Square,
|
||||
craft_metafile::Cap::Flat => LineCap::Butt,
|
||||
};
|
||||
let line_join = match line.join {
|
||||
craft_metafile::Join::Round => LineJoin::Round,
|
||||
craft_metafile::Join::Bevel => LineJoin::Bevel,
|
||||
craft_metafile::Join::Miter => LineJoin::Miter,
|
||||
};
|
||||
let dash = if line.dash.is_empty() { None } else { wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, HAIRLINE, path.perimeter(1.0)) };
|
||||
Stroke {
|
||||
paint,
|
||||
width: width.max(HAIRLINE) as f32,
|
||||
miter_limit: wordcraft_layout::metafile_miter_limit(line.miter_limit),
|
||||
line_cap,
|
||||
line_join,
|
||||
opacity,
|
||||
dash: dash.map(|d| StrokeDash { array: d.iter().map(|v| *v as f32).collect(), offset: 0.0 }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A tiling pattern of `img` (`w` × `h` pixels); `tile` maps tile pixels to page space. None when
|
||||
/// the mapping is not finite.
|
||||
fn tile_pattern(s: &mut Surface, img: &Image, w: u32, h: u32, tile: kurbo::Affine) -> Option<krilla::paint::Pattern> {
|
||||
let c = tile.as_coeffs().map(|v| v as f32);
|
||||
if !c.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let size = Size::from_wh(w as f32, h as f32)?;
|
||||
let mut sb = s.stream_builder();
|
||||
let mut ps = sb.surface();
|
||||
ps.draw_image(img.clone(), size);
|
||||
ps.finish();
|
||||
let stream = sb.finish();
|
||||
Some(krilla::paint::Pattern { stream, transform: Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), width: w as f32, height: h as f32 })
|
||||
}
|
||||
|
||||
/// A kurbo path as a krilla path (None when empty).
|
||||
fn path_from(b: &kurbo::BezPath) -> Option<Path> {
|
||||
let mut pb = PathBuilder::new();
|
||||
|
||||
@@ -390,6 +390,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> (
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn long_fragmented_hidden_headings_export_in_linear_time() {
|
||||
// Headings of n chars in one-char runs: all hidden with bold alternating, and hidden and visible
|
||||
// alternating. Layout and the bookmark/tag titles once scanned every left-out range for every
|
||||
@@ -1305,6 +1306,211 @@ fn emf_rec(typ: u32, fields: &[i32]) -> Vec<u8> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The PDF of a document holding one 70 pt metafile picture, uncompressed.
|
||||
fn metafile_pdf(emf: Vec<u8>) -> String {
|
||||
String::from_utf8_lossy(&metafile_pdf_bytes(emf)).into_owned()
|
||||
}
|
||||
|
||||
fn metafile_pdf_bytes(emf: Vec<u8>) -> Vec<u8> {
|
||||
export(&metafile_doc(emf), &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap()
|
||||
}
|
||||
|
||||
/// The uncompressed PDF of a document holding one 70 pt metafile picture, and the picture's box
|
||||
/// on the first page in PDF space (points, y up).
|
||||
fn metafile_pdf_and_box(emf: Vec<u8>) -> (Vec<u8>, kurbo::Rect) {
|
||||
let d = metafile_doc(emf);
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap();
|
||||
let lay = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let page = &lay.pages[0];
|
||||
let h = f64::from(page.h);
|
||||
let r = wordcraft_layout::display::page_display(&d, page, &DisplayOptions::default())
|
||||
.into_iter()
|
||||
.find_map(|item| if let Draw::Image { rect, .. } = item { Some(rect) } else { None })
|
||||
.expect("the picture is laid out");
|
||||
let (x, y, w, ph) = (f64::from(r.x), f64::from(r.y), f64::from(r.w), f64::from(r.h));
|
||||
(bytes, kurbo::Rect::new(x, h - y - ph, x + w, h - y))
|
||||
}
|
||||
|
||||
/// The right half of a box.
|
||||
fn right_half(r: kurbo::Rect) -> kurbo::Rect {
|
||||
kurbo::Rect::new((r.x0 + r.x1) / 2.0, r.y0, r.x1, r.y1)
|
||||
}
|
||||
|
||||
/// Whether two boxes have the same edges, to within half a point.
|
||||
fn same_box(a: kurbo::Rect, b: kurbo::Rect) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.5)
|
||||
}
|
||||
|
||||
fn metafile_doc(emf: Vec<u8>) -> Document {
|
||||
let mut d = Document::new();
|
||||
let media = d.add_media(emf, "emf");
|
||||
let mut p = Paragraph::with_text("Figure: ", CharProps::default());
|
||||
let n = p.len();
|
||||
p.insert_object(
|
||||
n,
|
||||
InlineObject::Image {
|
||||
media,
|
||||
w: 70.0,
|
||||
h: 70.0,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
},
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
d.body = vec![para_block(p)];
|
||||
d
|
||||
}
|
||||
|
||||
/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a 32bppPARGB bitmap: the bitmap is
|
||||
/// embedded as an image, and the page draws it into the EmfPlusDrawImage rectangle.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_is_embedded() {
|
||||
let plus_rec = |typ: u16, flags: u16, data: &[u8]| {
|
||||
let mut v = typ.to_le_bytes().to_vec();
|
||||
v.extend(flags.to_le_bytes());
|
||||
v.extend(((12 + data.len()) as u32).to_le_bytes());
|
||||
v.extend((data.len() as u32).to_le_bytes());
|
||||
v.extend(data);
|
||||
v
|
||||
};
|
||||
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]));
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 2, 8, 0x000E_200B, 0]);
|
||||
image.extend([0u8, 0, 255, 255].repeat(4));
|
||||
let object = plus_rec(0x4008, 0x0500, &image);
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, 2.0, 2.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let draw = plus_rec(0x401A, 0, &draw);
|
||||
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
|
||||
comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat());
|
||||
let mut rec = 70u32.to_le_bytes().to_vec();
|
||||
rec.extend(((12 + comment.len()) as u32).to_le_bytes());
|
||||
rec.extend((comment.len() as u32).to_le_bytes());
|
||||
rec.extend(comment);
|
||||
let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])]));
|
||||
let images = pdf_images(&bytes);
|
||||
assert!(images.iter().any(|(w, h, ..)| (*w, *h) == (2, 2)), "the 2 × 2 bitmap is embedded");
|
||||
let drawn = pdf_drawn_images(&bytes);
|
||||
assert!(
|
||||
drawn.iter().any(|&(w, h, r)| (w, h) == (2, 2) && same_box(r, right_half(pic))),
|
||||
"the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}"
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn");
|
||||
}
|
||||
|
||||
/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB,
|
||||
/// 24bppRGB or 32bppRGB, or a compressed PNG or JPEG bitmap: the bitmap is embedded as an image,
|
||||
/// and the page draws it into the EmfPlusDrawImage rectangle.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_formats_are_embedded() {
|
||||
let plus_rec = |typ: u16, flags: u16, data: &[u8]| {
|
||||
let mut v = typ.to_le_bytes().to_vec();
|
||||
v.extend(flags.to_le_bytes());
|
||||
v.extend(((12 + data.len()) as u32).to_le_bytes());
|
||||
v.extend((data.len() as u32).to_le_bytes());
|
||||
v.extend(data);
|
||||
v
|
||||
};
|
||||
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
let encoded = |png: bool| {
|
||||
let red = [255u8, 0, 0].repeat(15);
|
||||
if png {
|
||||
let img = image::RgbImage::from_raw(5, 3, red).unwrap();
|
||||
wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap()
|
||||
} else {
|
||||
wordcraft_geom::picture::encode_jpeg(&red, 5, 3, 100).unwrap()
|
||||
}
|
||||
};
|
||||
// Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data.
|
||||
let cases: [(&str, i32, i32, i32, u32, i32, Vec<u8>); 5] = [
|
||||
("32bppARGB", 2, 2, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(4)),
|
||||
("24bppRGB", 2, 2, 8, 0x0002_1808, 0, [0u8, 0, 255, 0, 0, 255, 0, 0].repeat(2)),
|
||||
("32bppRGB", 2, 2, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(4)),
|
||||
("PNG", 5, 3, 0, 0, 1, encoded(true)),
|
||||
("JPEG", 5, 3, 0, 0, 1, encoded(false)),
|
||||
];
|
||||
for (name, w, h, stride, format, kind, data) in cases {
|
||||
let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]));
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]);
|
||||
image.extend(data);
|
||||
// Records are a multiple of 4 bytes long.
|
||||
image.resize(image.len().next_multiple_of(4), 0);
|
||||
let object = plus_rec(0x4008, 0x0500, &image);
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let draw = plus_rec(0x401A, 0, &draw);
|
||||
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
|
||||
comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat());
|
||||
let mut rec = 70u32.to_le_bytes().to_vec();
|
||||
rec.extend(((12 + comment.len()) as u32).to_le_bytes());
|
||||
rec.extend((comment.len() as u32).to_le_bytes());
|
||||
rec.extend(comment);
|
||||
let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])]));
|
||||
let images = pdf_images(&bytes);
|
||||
assert!(images.iter().any(|(iw, ih, ..)| (*iw, *ih) == (w as u32, h as u32)), "{name}: the {w} × {h} bitmap is embedded");
|
||||
let drawn = pdf_drawn_images(&bytes);
|
||||
assert!(
|
||||
drawn.iter().any(|&(iw, ih, r)| (iw, ih) == (w as u32, h as u32) && same_box(r, right_half(pic))),
|
||||
"{name}: the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}"
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "{name}: the gray placeholder box is not drawn");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dotted cosmetic pen (CREATEPEN, PS_DOT, width 0) draws hairline dots: its dashes and gaps are
|
||||
/// the hairline's width, not the file's device units scaled to the frame (0.7 pt here).
|
||||
#[test]
|
||||
fn metafile_cosmetic_dotted_pen_draws_hairline_dots() {
|
||||
let recs = [emf_rec(38, &[1, 2, 0, 0, 0]), emf_rec(37, &[1]), emf_rec(27, &[0, 50]), emf_rec(54, &[100, 50]), emf_rec(14, &[0; 3])];
|
||||
let raw = metafile_pdf(emf_file(&recs));
|
||||
assert!(raw.contains("[0.25 0.25]0 d"), "the dots are hairline-sized");
|
||||
}
|
||||
|
||||
/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below the hairline draws its line
|
||||
/// solid: no dash array is written.
|
||||
#[test]
|
||||
fn metafile_sub_pixel_dashes_draw_solid() {
|
||||
let mut emf = emf_file(&[]);
|
||||
// 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide.
|
||||
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000]));
|
||||
emf[72..80].copy_from_slice(&le32(&[10_000, 10_000]));
|
||||
let pen = emf_rec(95, &[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]);
|
||||
let recs = [pen, emf_rec(37, &[1]), emf_rec(27, &[0, 500]), emf_rec(54, &[1000, 500]), emf_rec(14, &[0; 3])];
|
||||
emf.extend(recs.concat());
|
||||
let raw = metafile_pdf(emf);
|
||||
assert!(raw.contains(" w ") && !raw.contains("]0 d"), "a stroke with no dash array");
|
||||
}
|
||||
|
||||
/// A clip region (INTERSECTCLIPRECT) adds a clip around the rectangle it clips.
|
||||
#[test]
|
||||
fn metafile_clip_region_is_a_clip() {
|
||||
let clips = |raw: &str| raw.matches("\nW\nn").count() + raw.matches("\nW*\nn").count();
|
||||
let draw = |clip: bool| {
|
||||
let mut recs = vec![emf_rec(39, &[1, 0, 0x0000_00FF, 0]), emf_rec(37, &[1])];
|
||||
if clip {
|
||||
recs.push(emf_rec(30, &[0, 0, 50, 100]));
|
||||
}
|
||||
recs.extend([emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]);
|
||||
metafile_pdf(emf_file(&recs))
|
||||
};
|
||||
let (with, without) = (clips(&draw(true)), clips(&draw(false)));
|
||||
assert!(without > 0 && with == without + 1, "one clip more with the region: {with} and {without}");
|
||||
}
|
||||
|
||||
/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED) fills through a tiling pattern, not with a
|
||||
/// solid color.
|
||||
#[test]
|
||||
fn metafile_hatch_brush_is_a_tiling_pattern() {
|
||||
let recs = [emf_rec(39, &[1, 2, 0x0000_00FF, 1]), emf_rec(37, &[1]), emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])];
|
||||
let raw = metafile_pdf(emf_file(&recs));
|
||||
assert!(raw.contains("/PatternType 1"), "the hatch is a tiling pattern");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_strokes_use_round_caps_and_joins() {
|
||||
// A 4-unit black pen (handle 1) outlines a rectangle, so the stroke is drawn with round caps and joins.
|
||||
@@ -1425,6 +1631,17 @@ fn emf_text_records(text: &str) -> Vec<Vec<u8>> {
|
||||
vec![font, emf_rec(37, &[1]), emf_rec(24, &[0]), out]
|
||||
}
|
||||
|
||||
/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text
|
||||
/// run's character cells are filled red behind the text.
|
||||
#[test]
|
||||
fn metafile_text_fills_its_opaque_background() {
|
||||
let mut recs = vec![emf_rec(25, &[0x0000_00FF])];
|
||||
recs.extend(emf_text_records("Hi"));
|
||||
recs.push(emf_rec(14, &[0; 3]));
|
||||
let raw = metafile_pdf(emf_file(&recs));
|
||||
assert!(raw.contains("1 0 0 rg"), "the character cells are filled red");
|
||||
}
|
||||
|
||||
/// #1764: the text of an EMF picture (EXTTEXTOUTW) is drawn, so it is in the PDF's text layer.
|
||||
#[test]
|
||||
fn metafile_text_records_are_drawn_as_text() {
|
||||
@@ -1700,6 +1917,7 @@ fn comments_print_in_balloons_beside_scaled_pages() {
|
||||
/// references) exports in time proportional to its length: each link looked its bookmark up by
|
||||
/// walking the whole document, so NIH's 67-page protocol template took 10.6 s (0.9 s now).
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn internal_links_export_in_linear_time() {
|
||||
let doc = |n: usize| {
|
||||
let mut d = Document::new();
|
||||
@@ -2159,6 +2377,40 @@ fn pdf_images(bytes: &[u8]) -> Vec<(u32, u32, Vec<String>, Vec<Vec<u8>>)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The images the pages draw, through hayro's interpreter: pixel width and height, and the box each
|
||||
/// one is drawn into, in PDF space (points, y up).
|
||||
fn pdf_drawn_images(bytes: &[u8]) -> Vec<(u32, u32, kurbo::Rect)> {
|
||||
use hayro_interpret::font::Glyph;
|
||||
use hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
|
||||
interpret_page,
|
||||
};
|
||||
struct Ex(Vec<(u32, u32, kurbo::Rect)>);
|
||||
impl Device<'_> for Ex {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, _: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {}
|
||||
fn draw_image(&mut self, image: Image<'_, '_>, t: kurbo::Affine) {
|
||||
// The transform maps the image's pixel grid onto the page.
|
||||
let (w, h) = (image.width(), image.height());
|
||||
self.0.push((w, h, t.transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, f64::from(w), f64::from(h)))));
|
||||
}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse");
|
||||
let cache = InterpreterCache::new();
|
||||
let mut ex = Ex(Vec::new());
|
||||
for page in pdf.pages().iter() {
|
||||
let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
|
||||
interpret_page(page, &mut ctx, &mut ex);
|
||||
}
|
||||
ex.0
|
||||
}
|
||||
|
||||
/// The fill opacities (`ca`) of the PDF's graphics states.
|
||||
fn pdf_fill_opacities(bytes: &[u8]) -> Vec<f32> {
|
||||
use hayro_syntax::object::Object;
|
||||
@@ -2870,6 +3122,7 @@ fn only_safe_link_targets_become_annotations() {
|
||||
/// without one), found in one pass: a long run of glyphs sharing a cluster used to rescan the rest
|
||||
/// of the run for every glyph.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn cluster_ends_match_the_next_larger_cluster_in_linear_time() {
|
||||
let brute = |cl: &[usize], len: usize| -> Vec<usize> {
|
||||
(0..cl.len()).map(|i| cl.iter().skip(i + 1).copied().find(|n| *n > cl[i]).unwrap_or(len)).collect::<Vec<_>>()
|
||||
|
||||
@@ -856,7 +856,7 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
return;
|
||||
};
|
||||
let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
|
||||
let [cl, ct, vis_w, vis_h] = craft_metafile::crop_window(*crop);
|
||||
let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop);
|
||||
let sx = r.width() / (pw * vis_w);
|
||||
let sy = r.height() / (ph * vis_h);
|
||||
ctx.set_transform(view);
|
||||
|
||||
+188
-40
@@ -140,28 +140,50 @@ pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> {
|
||||
Some((w * k, h * k, ext))
|
||||
}
|
||||
|
||||
/// A metafile (WMF/EMF) picture, parsed once. The geometry comes placed by the metafile crate; the
|
||||
/// bitmaps are pixmaps, one per picture item (None for paths and undecodable bitmaps).
|
||||
/// A metafile (WMF/EMF/EMF+) picture, parsed once. The geometry comes placed by the metafile crate;
|
||||
/// the bitmaps and pattern tiles are pixmaps, one per picture item (None for paths, text and
|
||||
/// undecodable bitmaps). Fills that share a tile share its pixmap. `averages` holds each pattern
|
||||
/// fill's tile average color (transparent for other items), computed once a tile.
|
||||
pub(crate) struct Vector {
|
||||
pic: Picture,
|
||||
pixmaps: Vec<Option<Arc<Pixmap>>>,
|
||||
averages: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
impl Vector {
|
||||
/// Approximate memory held: pixels and path segments.
|
||||
fn bytes(&self) -> usize {
|
||||
let px: usize = self.pixmaps.iter().flatten().map(|p| p.width() as usize * p.height() as usize * 4).sum();
|
||||
let segs: usize = self
|
||||
.pic
|
||||
.items
|
||||
.iter()
|
||||
.map(|it| match it {
|
||||
Item::Path { segs, .. } => segs.len() * std::mem::size_of::<Seg>(),
|
||||
Item::Bitmap { .. } | Item::Pattern { .. } => 0,
|
||||
Item::Text(t) => t.text.len() + t.dx.len() * 4,
|
||||
})
|
||||
.sum();
|
||||
px + segs
|
||||
/// Approximate memory held: pixmaps, the pattern tiles' own pixels, path segments, dash
|
||||
/// patterns, clip regions, clip lists, clip paths and text, each shared allocation once.
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut total = self.averages.len() * 4;
|
||||
for p in self.pixmaps.iter().flatten() {
|
||||
if seen.insert(Arc::as_ptr(p) as usize) {
|
||||
total = total.saturating_add(p.width() as usize * p.height() as usize * 4);
|
||||
}
|
||||
}
|
||||
let seg = std::mem::size_of::<Seg>();
|
||||
for it in &self.pic.items {
|
||||
let (own, region, clips) = match it {
|
||||
Item::Path { segs, line, region, clips, .. } => ((segs.len() * seg).saturating_add(line.dash.len() * 4), region, clips),
|
||||
Item::Pattern { segs, tile, region, clips, .. } => {
|
||||
let tile_bytes = if seen.insert(Arc::as_ptr(tile) as usize) { tile.rgba.len() } else { 0 };
|
||||
((segs.len() * seg).saturating_add(tile_bytes), region, clips)
|
||||
}
|
||||
Item::Bitmap { region, clips, .. } => (0, region, clips),
|
||||
Item::Text(t) => (t.text.len() + t.dx.len() * 4, &t.region, &t.clips),
|
||||
};
|
||||
// Each item holds its own copy of the clip region's rectangles and its own list of the
|
||||
// clip paths it shares.
|
||||
let region = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>());
|
||||
let list = clips.len() * std::mem::size_of::<Arc<craft_metafile::ClipPath>>();
|
||||
total = total.saturating_add(own).saturating_add(region).saturating_add(list);
|
||||
for c in clips {
|
||||
if seen.insert(Arc::as_ptr(c) as usize) {
|
||||
total = total.saturating_add(c.segs.len() * seg);
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,25 +206,45 @@ pub(crate) fn vector_for(doc: &Document, key: &str) -> Option<Arc<Vector>> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Parses a metafile and decodes its bitmaps. None when the picture has no usable size.
|
||||
fn build_vector(bytes: &[u8]) -> Option<Vector> {
|
||||
/// Parses a metafile and decodes its bitmaps and pattern tiles. None when the picture has no
|
||||
/// usable size.
|
||||
pub(crate) fn build_vector(bytes: &[u8]) -> Option<Vector> {
|
||||
let mut pic = craft_metafile::parse(bytes).ok()?;
|
||||
if !pic.has_size() {
|
||||
return None;
|
||||
}
|
||||
// The pixels move into the pixmaps; the picture keeps only the geometry.
|
||||
let pixmaps = pic.items.iter_mut().map(|it| it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new)).collect();
|
||||
Some(Vector { pic, pixmaps })
|
||||
// The pixels move into the pixmaps; the picture keeps only the geometry. A tile shared by
|
||||
// several fills is converted and averaged once.
|
||||
let mut tiles: HashMap<usize, (Option<Arc<Pixmap>>, [u8; 4])> = HashMap::new();
|
||||
let (pixmaps, averages) = pic
|
||||
.items
|
||||
.iter_mut()
|
||||
.map(|it| match it {
|
||||
Item::Pattern { tile, .. } => tiles
|
||||
.entry(Arc::as_ptr(tile) as usize)
|
||||
.or_insert_with(|| {
|
||||
(premul_pixmap(tile.width, tile.height, &tile.rgba).map(Arc::new), wordcraft_layout::metafile_average_color(&tile.rgba))
|
||||
})
|
||||
.clone(),
|
||||
_ => (it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new), [0; 4]),
|
||||
})
|
||||
.unzip();
|
||||
Some(Vector { pic, pixmaps, averages })
|
||||
}
|
||||
|
||||
fn rgba_color(c: [u8; 4]) -> peniko::Color {
|
||||
peniko::Color::from_rgba8(c[0], c[1], c[2], c[3])
|
||||
}
|
||||
|
||||
/// Pattern tiles smaller than this (device pixels on both sides) are drawn as the tile's average
|
||||
/// color: a sub-pixel pattern would only alias.
|
||||
const MIN_TILE_PX: f64 = 1.5;
|
||||
|
||||
/// Draws a metafile picture into `r` (page points): fills and strokes in page space (so strokes keep
|
||||
/// their width under non-uniform scaling), bitmaps stretched, all clipped to `r` and faded by `alpha`.
|
||||
/// Strokes have round caps and joins, as GDI draws them, and are at least one device pixel wide, so
|
||||
/// cosmetic (width 0) pens show as hairlines at any zoom.
|
||||
/// their width under non-uniform scaling), bitmaps stretched (or turned by their transform),
|
||||
/// pattern fills tiled, each item inside its clip region and clip paths, all clipped to `r` and
|
||||
/// faded by `alpha`. Strokes take the pen's caps, joins and dashes and are at least one device
|
||||
/// pixel wide, so cosmetic (width 0) pens show as hairlines at any zoom.
|
||||
pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, crop: &[f32; 4], alpha: f32, view: Affine) {
|
||||
ctx.set_transform(view);
|
||||
let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 };
|
||||
@@ -212,9 +254,9 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
|
||||
}
|
||||
ctx.push_clip_layer(&r.to_path(0.1));
|
||||
let pixel = device_pixel(view);
|
||||
for it in v.pic.place(*r, *crop) {
|
||||
for it in v.pic.place(*r, wordcraft_layout::crop_sides(*crop)) {
|
||||
match it {
|
||||
PlacedItem::Path { path, fill, stroke, even_odd, .. } => {
|
||||
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
if let Some(f) = fill {
|
||||
ctx.set_paint(rgba_color(f));
|
||||
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
@@ -222,26 +264,71 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
|
||||
}
|
||||
if let Some((s, w)) = stroke {
|
||||
ctx.set_paint(rgba_color(s));
|
||||
ctx.set_stroke(kurbo::Stroke::new(w.max(pixel)).with_caps(kurbo::Cap::Round).with_join(kurbo::Join::Round));
|
||||
ctx.set_stroke(pen(w, pixel, &line, &path));
|
||||
ctx.stroke_path(&path);
|
||||
}
|
||||
}
|
||||
PlacedItem::Bitmap { index, rect, .. } => {
|
||||
let Some(Some(pm)) = v.pixmaps.get(index) else { continue };
|
||||
}),
|
||||
PlacedItem::Bitmap { index, rect, transform, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Some(pm)) = v.pixmaps.get(index) else { return };
|
||||
let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
|
||||
ctx.set_paint(vello_cpu::Image {
|
||||
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
|
||||
sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium),
|
||||
});
|
||||
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph));
|
||||
ctx.fill_rect(&rect);
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
PlacedItem::Pattern { .. } => {}
|
||||
PlacedItem::Text { index, transform, .. } => {
|
||||
if let Some(Item::Text(t)) = v.pic.items.get(index) {
|
||||
draw_vector_text(ctx, t, view * transform);
|
||||
let c = transform.as_coeffs();
|
||||
// Upright and not mirrored: the bitmap fills `rect`.
|
||||
if c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0 {
|
||||
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph));
|
||||
ctx.fill_rect(&rect);
|
||||
} else {
|
||||
// A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place.
|
||||
ctx.set_paint_transform(transform * Affine::scale_non_uniform(1.0 / pw, 1.0 / ph));
|
||||
ctx.fill_path(&(transform * kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1)));
|
||||
}
|
||||
ctx.reset_paint_transform();
|
||||
}),
|
||||
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { return };
|
||||
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
// `tile` maps one tile pixel to page points: the tile's sides are its columns and
|
||||
// its rows under that, in device pixels. The tile is drawn when either side is at
|
||||
// least `MIN_TILE_PX`.
|
||||
let c = (view * tile).as_coeffs();
|
||||
let across = c[0].hypot(c[1]) * f64::from(t.width);
|
||||
let down = c[2].hypot(c[3]) * f64::from(t.height);
|
||||
match v.pixmaps.get(index) {
|
||||
Some(Some(pm)) if across.max(down) >= MIN_TILE_PX => {
|
||||
ctx.set_paint(vello_cpu::Image {
|
||||
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
|
||||
sampler: peniko::ImageSampler {
|
||||
x_extend: peniko::Extend::Repeat,
|
||||
y_extend: peniko::Extend::Repeat,
|
||||
quality: peniko::ImageQuality::Low,
|
||||
alpha: 1.0,
|
||||
},
|
||||
});
|
||||
ctx.set_paint_transform(tile);
|
||||
ctx.fill_path(&path);
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
_ => {
|
||||
ctx.set_paint(rgba_color(v.averages.get(index).copied().unwrap_or([0; 4])));
|
||||
ctx.fill_path(&path);
|
||||
}
|
||||
}
|
||||
}),
|
||||
PlacedItem::Text { index, transform, clip, region, clips } => {
|
||||
clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Item::Text(t)) = v.pic.items.get(index) else { return };
|
||||
if let Some(c) = clip {
|
||||
ctx.push_clip_layer(&c.to_path(0.1));
|
||||
}
|
||||
draw_vector_text(ctx, t, view * transform);
|
||||
ctx.set_transform(view);
|
||||
if clip.is_some() {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
});
|
||||
ctx.set_transform(view);
|
||||
}
|
||||
}
|
||||
@@ -253,15 +340,76 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws a metafile text run: `tf` maps the run's own space (see [`PlacedItem::Text`]) to the device.
|
||||
/// Draws `draw` inside a metafile item's clip region and every one of its clip paths (page
|
||||
/// points, under the current transform). No region is the default clip.
|
||||
fn clipped(
|
||||
ctx: &mut RenderContext,
|
||||
region: Option<&kurbo::BezPath>,
|
||||
clips: &[Arc<craft_metafile::PlacedClip>],
|
||||
draw: impl FnOnce(&mut RenderContext),
|
||||
) {
|
||||
if let Some(region) = region {
|
||||
ctx.set_fill_rule(peniko::Fill::NonZero);
|
||||
ctx.push_clip_layer(region);
|
||||
}
|
||||
for c in clips {
|
||||
ctx.set_fill_rule(if c.even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
ctx.push_clip_layer(&c.path);
|
||||
}
|
||||
ctx.set_fill_rule(peniko::Fill::NonZero);
|
||||
draw(ctx);
|
||||
for _ in 0..clips.len() + usize::from(region.is_some()) {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile pen for `path` as a stroke `width` wide (page points, at least one device `pixel`):
|
||||
/// its caps, joins, miter limit and dashes (`wordcraft_layout::metafile_dashes`).
|
||||
fn pen(width: f64, pixel: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> kurbo::Stroke {
|
||||
let cap = match line.cap {
|
||||
craft_metafile::Cap::Round => kurbo::Cap::Round,
|
||||
craft_metafile::Cap::Square => kurbo::Cap::Square,
|
||||
craft_metafile::Cap::Flat => kurbo::Cap::Butt,
|
||||
};
|
||||
let join = match line.join {
|
||||
craft_metafile::Join::Round => kurbo::Join::Round,
|
||||
craft_metafile::Join::Bevel => kurbo::Join::Bevel,
|
||||
craft_metafile::Join::Miter => kurbo::Join::Miter,
|
||||
};
|
||||
let stroke = kurbo::Stroke::new(width.max(pixel))
|
||||
.with_caps(cap)
|
||||
.with_join(join)
|
||||
.with_miter_limit(f64::from(wordcraft_layout::metafile_miter_limit(line.miter_limit)));
|
||||
if line.dash.is_empty() {
|
||||
return stroke;
|
||||
}
|
||||
match wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, pixel, path.perimeter(1.0)) {
|
||||
Some(dash) => stroke.with_dashes(0.0, dash),
|
||||
None => stroke,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws a metafile text run: `tf` maps its text space (`craft_metafile::Text::transform`) to the
|
||||
/// device.
|
||||
fn draw_vector_text(ctx: &mut RenderContext, t: &craft_metafile::Text, tf: Affine) {
|
||||
let (face, shaped) = wordcraft_layout::metafile_text_run(t);
|
||||
let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect();
|
||||
let Some(lay) = wordcraft_layout::layout_metafile_text(t, face.upem, face.ascent, face.descent, &glyphs) else { return };
|
||||
let k = lay.em / face.upem.max(1.0);
|
||||
let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
|
||||
// An opaque background mode fills the character cells first.
|
||||
if let Some(bg) = t.background {
|
||||
let [x0, y0, x1, y1] = lay.cell;
|
||||
let cell = tf * kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1);
|
||||
let b = cell.bounding_box();
|
||||
if x1 > x0 && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_GLYPH_PIXELS * 16.0) && b.overlaps(canvas) {
|
||||
ctx.set_transform(Affine::IDENTITY);
|
||||
ctx.set_paint(rgba_color(bg));
|
||||
ctx.fill_path(&cell);
|
||||
}
|
||||
}
|
||||
ctx.set_paint(rgba_color(t.color));
|
||||
let db = FontDb::global();
|
||||
let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
|
||||
let mut oversized = 0usize;
|
||||
for (g, (x, y)) in shaped.iter().zip(&lay.glyphs) {
|
||||
let o = db.outline(&face, g.gid);
|
||||
|
||||
@@ -1041,6 +1041,275 @@ fn metafile_picture_is_drawn_as_vectors() {
|
||||
assert!(left[..3].iter().all(|c| *c > 200), "left half should be paper, not the grey box: {left:?}");
|
||||
}
|
||||
|
||||
/// #6636: an EMF+ only file (no plain EMF drawing records) whose EmfPlusDrawImage draws a
|
||||
/// 32bppPARGB bitmap over the right half: the bitmap's pixels are drawn.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_is_drawn() {
|
||||
// EmfPlusObject 0, an image (type 5): a 2 × 1 bitmap in PixelFormat32bppPARGB, opaque red
|
||||
// and then red at half opacity (premultiplied BGRA 0, 0, 128, 128).
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]);
|
||||
image.extend([0u8, 0, 255, 255, 0, 0, 128, 128]);
|
||||
let object = plus_rec(0x4008, 0x0500, &image);
|
||||
// EmfPlusDrawImage of image 0: the whole bitmap (pixel units) into x 50..100, y 0..100.
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, 2.0, 1.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let emf = emf_plus_file(&[object, plus_rec(0x401A, 0, &draw)]);
|
||||
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
let (opaque, half, left) = (at(0.6), at(0.9), at(0.25));
|
||||
assert!(is_red(opaque), "the bitmap's opaque red is drawn on the right half: {opaque:?}");
|
||||
// Premultiplied half-opacity red over white paper is (255, 127, 127); read as straight
|
||||
// color it would be about (191, 127, 127).
|
||||
assert!(half[0] > 235 && (110..145).contains(&half[1]) && (110..145).contains(&half[2]), "half-opacity red: {half:?}");
|
||||
assert!(is_paper(left), "left half should be paper: {left:?}");
|
||||
}
|
||||
|
||||
/// #6636: EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB, and a
|
||||
/// compressed PNG or JPEG bitmap, in an EMF+ only file.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_formats_are_drawn() {
|
||||
let encoded = |png: bool| {
|
||||
let red = [255u8, 0, 0].repeat(64);
|
||||
if png {
|
||||
let img = image::RgbImage::from_raw(8, 8, red).unwrap();
|
||||
wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap()
|
||||
} else {
|
||||
wordcraft_geom::picture::encode_jpeg(&red, 8, 8, 100).unwrap()
|
||||
}
|
||||
};
|
||||
// Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data.
|
||||
let cases: [(&str, i32, i32, i32, u32, i32, Vec<u8>); 5] = [
|
||||
("32bppARGB", 2, 1, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(2)),
|
||||
("24bppRGB", 2, 1, 8, 0x0002_1808, 0, vec![0, 0, 255, 0, 0, 255, 0, 0]),
|
||||
("32bppRGB", 2, 1, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(2)),
|
||||
("PNG", 8, 8, 0, 0, 1, encoded(true)),
|
||||
("JPEG", 8, 8, 0, 0, 1, encoded(false)),
|
||||
];
|
||||
for (name, w, h, stride, format, kind, data) in cases {
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]);
|
||||
image.extend(data);
|
||||
// Records are a multiple of 4 bytes long.
|
||||
image.resize(image.len().next_multiple_of(4), 0);
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), plus_rec(0x401A, 0, &draw)]);
|
||||
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
let (right, left) = (at(0.75), at(0.25));
|
||||
assert!(is_red(right), "{name}: the red bitmap is drawn on the right half: {right:?}");
|
||||
assert!(is_paper(left), "{name}: left half should be paper: {left:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An EMF+ record for [`emf_plus_file`]: type, flags and data.
|
||||
fn plus_rec(typ: u16, flags: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut v = typ.to_le_bytes().to_vec();
|
||||
v.extend(flags.to_le_bytes());
|
||||
v.extend(((12 + data.len()) as u32).to_le_bytes());
|
||||
v.extend((data.len() as u32).to_le_bytes());
|
||||
v.extend(data);
|
||||
v
|
||||
}
|
||||
|
||||
/// An EMF+ only file with the frame of [`red_right_half_emf`]: an EmfPlusHeader (96 dpi), then
|
||||
/// `records`, then EmfPlusEndOfFile, in one comment record.
|
||||
fn emf_plus_file(records: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
|
||||
comment.extend(plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96])));
|
||||
comment.extend(records.concat());
|
||||
comment.extend(plus_rec(0x4002, 0, &[]));
|
||||
let mut payload = (comment.len() as u32).to_le_bytes().to_vec();
|
||||
payload.extend(comment);
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
emf.extend([emf_rec(70, &payload), emf_rec(14, &[0; 12])].concat());
|
||||
emf
|
||||
}
|
||||
|
||||
/// Renders a document holding one 70 pt metafile picture with `crop` at `scale`: the page and the
|
||||
/// picture's frame (points).
|
||||
fn emf_on_page(emf: Vec<u8>, crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) {
|
||||
emf_on_page_sized(emf, (70.0, 70.0), crop, scale)
|
||||
}
|
||||
|
||||
/// [`emf_on_page`] with the picture `size` (points).
|
||||
fn emf_on_page_sized(emf: Vec<u8>, size: (f32, f32), crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) {
|
||||
let mut d = Document::new();
|
||||
let media = d.add_media(emf, "emf");
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
let obj = wordcraft_doc::para::InlineObject::Image {
|
||||
media,
|
||||
w: size.0,
|
||||
h: size.1,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop,
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
p.insert_object(0, obj, &Default::default()).unwrap();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let opts = RenderOptions::default();
|
||||
let rect = page_display(&d, &l.pages[0], &opts.display)
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Draw::Image { rect, .. } => Some(*rect),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a picture on the page");
|
||||
(render_page(&d, &l.pages[0], scale, &opts), rect)
|
||||
}
|
||||
|
||||
/// Whether a pixel is close to pure red.
|
||||
fn is_red(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60
|
||||
}
|
||||
|
||||
/// Whether a pixel is paper.
|
||||
fn is_paper(p: [u8; 4]) -> bool {
|
||||
p[..3].iter().all(|c| *c > 200)
|
||||
}
|
||||
|
||||
/// A clip region (INTERSECTCLIPRECT to the left half) keeps a red rectangle over the whole
|
||||
/// picture to that half; once RESTOREDC drops it, a second rectangle across the bottom shows on
|
||||
/// both halves.
|
||||
#[test]
|
||||
fn metafile_clip_region_clips_and_ends() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0]));
|
||||
let recs = [
|
||||
brush,
|
||||
emf_rec(37, &le32(&[1])),
|
||||
emf_rec(33, &[]),
|
||||
emf_rec(30, &le32(&[0, 0, 50, 100])),
|
||||
emf_rec(43, &le32(&[0, 0, 100, 60])),
|
||||
emf_rec(34, &le32(&[-1])),
|
||||
emf_rec(43, &le32(&[0, 80, 100, 100])),
|
||||
emf_rec(14, &[0; 12]),
|
||||
];
|
||||
emf.extend(recs.concat());
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32);
|
||||
assert!(is_red(at(0.25, 0.3)), "inside the clip: {:?}", at(0.25, 0.3));
|
||||
assert!(is_paper(at(0.75, 0.3)), "outside the clip: {:?}", at(0.75, 0.3));
|
||||
assert!(is_red(at(0.75, 0.9)), "after the clip is restored away: {:?}", at(0.75, 0.9));
|
||||
}
|
||||
|
||||
/// The vector cache counts each item's copy of the clip region: 100 rectangles drawn inside a
|
||||
/// clip region hold 100 copies of its rectangle more than without it.
|
||||
#[test]
|
||||
fn metafile_cache_counts_clip_regions() {
|
||||
let bytes = |clip: bool| {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
if clip {
|
||||
emf.extend(emf_rec(30, &le32(&[0, 0, 50, 100])));
|
||||
}
|
||||
for i in 0..100 {
|
||||
emf.extend(emf_rec(43, &le32(&[i % 50, 0, i % 50 + 10, 10])));
|
||||
}
|
||||
emf.extend(emf_rec(14, &[0; 12]));
|
||||
media::build_vector(&emf).map(|v| v.bytes())
|
||||
};
|
||||
let (with, without) = (bytes(true).expect("a picture"), bytes(false).expect("a picture"));
|
||||
assert!(with >= without + 100 * 16, "{with} and {without}");
|
||||
}
|
||||
|
||||
/// A hatch tile squeezed to well under a pixel tall but several pixels wide (the picture is 70 pt
|
||||
/// wide and 2 pt tall) keeps its vertical lines: the row crosses red lines and the background
|
||||
/// between them, not one blended color.
|
||||
#[test]
|
||||
fn metafile_narrow_hatch_tile_keeps_its_lines() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1]));
|
||||
// The stock NULL_PEN leaves the rectangle without an outline.
|
||||
let no_pen = emf_rec(37, &le32(&[0x8000_0008_u32 as i32]));
|
||||
emf.extend([brush, emf_rec(37, &le32(&[1])), no_pen, emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat());
|
||||
let (img, rect) = emf_on_page_sized(emf, (70.0, 2.0), [0.0; 4], 1.0);
|
||||
let y = (rect.y + rect.h / 2.0) as u32;
|
||||
let row: Vec<u8> = ((rect.x + 2.0) as u32..(rect.x + rect.w - 2.0) as u32).map(|x| img.pixel(x, y)[1]).collect();
|
||||
assert!(row.iter().any(|g| *g < 160) && row.iter().any(|g| *g > 240), "red lines and background: {row:?}");
|
||||
}
|
||||
|
||||
/// A clip path (a rectangle path over the left half, SELECTCLIPPATH with RGN_COPY) keeps a red
|
||||
/// rectangle over the whole picture to that half.
|
||||
#[test]
|
||||
fn metafile_clip_path_clips() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0]));
|
||||
let recs = [
|
||||
brush,
|
||||
emf_rec(37, &le32(&[1])),
|
||||
emf_rec(59, &[]),
|
||||
emf_rec(43, &le32(&[0, 0, 50, 100])),
|
||||
emf_rec(60, &[]),
|
||||
emf_rec(67, &le32(&[5])),
|
||||
emf_rec(43, &le32(&[0, 0, 100, 100])),
|
||||
emf_rec(14, &[0; 12]),
|
||||
];
|
||||
emf.extend(recs.concat());
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
assert!(is_red(at(0.25)), "inside the clip path: {:?}", at(0.25));
|
||||
assert!(is_paper(at(0.75)), "outside the clip path: {:?}", at(0.75));
|
||||
}
|
||||
|
||||
/// A bitmap under a world transform that turns it a quarter turn clockwise about the picture's
|
||||
/// center (EmfPlusSetWorldTransform): its left pixel (red) is drawn at the top and its right pixel
|
||||
/// (blue) at the bottom.
|
||||
#[test]
|
||||
fn emf_plus_turned_bitmap_is_drawn_turned() {
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]);
|
||||
// BGRA: red, then blue.
|
||||
image.extend([0u8, 0, 255, 255, 255, 0, 0, 255]);
|
||||
let turn = plus_rec(0x402A, 0, &[0.0f32, 1.0, -1.0, 0.0, 100.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, 2.0, 1.0, 25.0, 25.0, 50.0, 50.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), turn, plus_rec(0x401A, 0, &draw)]);
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32);
|
||||
let (top_right, bottom_left) = (at(0.65, 0.37), at(0.35, 0.62));
|
||||
assert!(is_red(top_right), "red at the top: {top_right:?}");
|
||||
assert!(bottom_left[2] > 200 && bottom_left[0] < 60, "blue at the bottom: {bottom_left:?}");
|
||||
}
|
||||
|
||||
/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below a pixel draws its line solid
|
||||
/// instead of splitting it into dashes too small to see.
|
||||
#[test]
|
||||
fn metafile_sub_pixel_dashes_draw_solid() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
// 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide.
|
||||
emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000]));
|
||||
emf[72..80].copy_from_slice(&le32(&[10_000, 10_000]));
|
||||
// EXTCREATEPEN 1: PS_GEOMETRIC | PS_ENDCAP_FLAT | PS_USERSTYLE, 80 units wide, black, two
|
||||
// entries of 1 unit.
|
||||
let pen = emf_rec(95, &le32(&[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]));
|
||||
let recs = [pen, emf_rec(37, &le32(&[1])), emf_rec(27, &le32(&[0, 500])), emf_rec(54, &le32(&[1000, 500])), emf_rec(14, &[0; 12])];
|
||||
emf.extend(recs.concat());
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let y = (rect.y + rect.h * 0.5) as u32;
|
||||
let (x0, x1) = ((rect.x + 5.0) as u32, (rect.x + rect.w - 5.0) as u32);
|
||||
let dark = (x0..x1).filter(|&x| img.pixel(x, y)[..3].iter().all(|c| *c < 60)).count();
|
||||
assert_eq!(dark, (x1 - x0) as usize, "the line is solid black");
|
||||
}
|
||||
|
||||
/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED, HS_VERTICAL) fills with its red lines over
|
||||
/// the background, not with a solid red.
|
||||
#[test]
|
||||
fn metafile_hatch_brush_draws_its_lines() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1]));
|
||||
emf.extend([brush, emf_rec(37, &le32(&[1])), emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat());
|
||||
let scale = 4.0;
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], scale);
|
||||
let y = ((rect.y + rect.h / 2.0) * scale) as u32;
|
||||
let (x0, x1) = (((rect.x + 2.0) * scale) as u32, ((rect.x + rect.w - 2.0) * scale) as u32);
|
||||
let red = (x0..x1).filter(|&x| img.pixel(x, y)[1] < 128).count();
|
||||
let n = (x1 - x0) as usize;
|
||||
assert!(red > 0 && red < n * 3 / 4, "the row crosses red lines and the background between them: {red} of {n} red");
|
||||
}
|
||||
|
||||
/// #1899: a crop that keeps a sliver of the picture (3% here; a header's bar can be 2.7% of a
|
||||
/// page-sized metafile) stretches that sliver over the frame, as the file says, for vector and
|
||||
/// bitmap pictures alike. Both pictures are paper on the left half and red on the right.
|
||||
@@ -1084,6 +1353,43 @@ fn a_crop_keeping_a_sliver_fills_the_frame_with_it() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A negative crop side draws as no crop on that side, for vector and bitmap pictures alike: a
|
||||
/// left side of -0.5 does not pad the source, so the frame at 55% shows the source at 55% (red).
|
||||
#[test]
|
||||
fn a_negative_crop_side_draws_uncropped() {
|
||||
let img = image::RgbaImage::from_fn(100, 100, |x, _| image::Rgba(if x >= 50 { [255, 0, 0, 255] } else { [255; 4] }));
|
||||
let png = wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap();
|
||||
for (bytes, ext) in [(red_right_half_emf(), "emf"), (png, "png")] {
|
||||
let mut d = Document::new();
|
||||
let media = d.add_media(bytes, ext);
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
let obj = wordcraft_doc::para::InlineObject::Image {
|
||||
media,
|
||||
w: 70.0,
|
||||
h: 70.0,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop: [-0.5, 0.0, 0.0, 0.0],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
p.insert_object(0, obj, &Default::default()).unwrap();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let opts = RenderOptions::default();
|
||||
let rect = page_display(&d, &l.pages[0], &opts.display)
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Draw::Image { rect, .. } => Some(*rect),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a picture on the page");
|
||||
let img = render_page(&d, &l.pages[0], 1.0, &opts);
|
||||
let px = img.pixel((rect.x + rect.w * 0.55) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
assert!(is_red(px), "{ext}: {px:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cosmetic_metafile_pen_is_one_device_pixel_wide() {
|
||||
// MOVETO (0, 50), LINETO (100, 50) with the default cosmetic black pen: a hairline across the middle.
|
||||
@@ -1168,6 +1474,29 @@ fn metafile_text_records_are_painted() {
|
||||
assert!(dark > 50, "the text is painted inside the picture: {dark} dark pixels");
|
||||
}
|
||||
|
||||
/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text
|
||||
/// run's character cells are filled red behind the black text.
|
||||
#[test]
|
||||
fn metafile_text_fills_its_opaque_background() {
|
||||
let mut font = emf_rec(82, &le32(&[1, -20, 0, 0, 0, 400, 0, 0]));
|
||||
let mut name: Vec<u8> = "Arial".encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
|
||||
name.resize(64, 0);
|
||||
font.extend(name);
|
||||
font[4..8].copy_from_slice(&104u32.to_le_bytes());
|
||||
let mut text = emf_rec(84, &le32(&[0, 0, 100, 100, 1, 0, 0, 5, 40, 4, 76, 0, 0, 0, 0, 0, 0]));
|
||||
text.extend("WWWW".encode_utf16().flat_map(|u| u.to_le_bytes()));
|
||||
text[4..8].copy_from_slice(&84u32.to_le_bytes());
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let bk = emf_rec(25, &le32(&[0x0000_00FF]));
|
||||
emf.extend([bk, font, emf_rec(37, &le32(&[1])), emf_rec(24, &le32(&[0])), text, emf_rec(14, &[0; 12])].concat());
|
||||
let scale = 2.0;
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], scale);
|
||||
let (x0, y0) = ((rect.x * scale) as u32, (rect.y * scale) as u32);
|
||||
let (x1, y1) = (((rect.x + rect.w) * scale) as u32, ((rect.y + rect.h) * scale) as u32);
|
||||
let red = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| is_red(img.pixel(x, y))).count();
|
||||
assert!(red > 50, "the character cells are filled red: {red} red pixels");
|
||||
}
|
||||
|
||||
/// An EMF text run whose anchor sits inside the picture but whose font is billions of units
|
||||
/// tall: each glyph's curves would span billions of device pixels, which the rasteriser
|
||||
/// subdivides for ever. Glyphs that big (or off the raster) are left out; the page renders.
|
||||
|
||||
@@ -56,6 +56,7 @@ fn listing_stops_at_the_field_budget() {
|
||||
// Finding 16: rich text with alternating formatting is built in one pass, not run by run with
|
||||
// every earlier run merged again.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn rich_text_with_many_runs_is_linear() {
|
||||
let html: String = "<i>a</i>b".repeat(50_000);
|
||||
let t = Instant::now();
|
||||
@@ -82,6 +83,7 @@ fn call(b: &mut Bridge, s: &mut Session, method: &str, args: Value) -> Result<Va
|
||||
|
||||
// Finding 32: Document_convert checks each distinct id once against one list of the fields.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn convert_with_one_id_repeated_is_one_check() {
|
||||
let mut doc = Document::from_text("");
|
||||
// Checking each id against a fresh list of the fields took 81 s with 300 of them; with 1,000
|
||||
|
||||
@@ -21,7 +21,7 @@ crate name links to its source tree.
|
||||
| L0 | [`geom`](../crates/geom/src) | 1,271 | Units (points, twips, EMU, inches, cm), rectangles and measurement parsing |
|
||||
| L1 | [`doc`](../crates/doc/src) | 23,719 | Document model: stories, paragraphs, runs, tables, sections, styles, numbering, fields, notes, comments, revisions and equations; edit primitives and bidi |
|
||||
| L1 | [`fonts`](../crates/fonts/src) | 7,088 | Font database, metrics, outlines, HarfRust shaping, Word font substitution and OpenType MATH |
|
||||
| L1 | [`metafile`](../crates/metafile/src) | 3,614 | Shared Windows Metafile parsing and drawing primitives used by format readers and renderers |
|
||||
| L1 (external) | [`craft-metafile`](https://github.com/storytold/craft-libs/tree/main/crates/metafile) | — | WMF, EMF and EMF+ reader shared with the other Craft apps: paths, pattern fills, bitmaps and text with their clips, placed into a picture frame for the renderers |
|
||||
| L1 (external) | [`craft-proof`](https://github.com/storytold/craft-libs/tree/main/crates/proof) (package alias `wordcraft-proof`) | — | Proofing moved to craft-libs (CP1, 2026-11): fifteen spelling dictionaries: English (US, GB, CA), Polish, Portuguese, Italian, Croatian, Turkish, Russian, Czech, Indonesian and Spanish (Spain, Mexico, Latin America, Uruguay); language modules provide spelling, suggestions and grammar, while Bulgarian and German have hyphenation only. Its word lists and patterns are craft-i18n's `language-data/`, embedded from `CRAFT_I18N_DIR` at the commit in `craft-i18n.rev` (CI and releases set `CRAFT_I18N_REQUIRED=1`); without them English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off (Bulgarian, Turkish and Russian hyphenate by rule) |
|
||||
| L2 | [`docbin`](../crates/docbin/src) | 8,815 | Word 97–2003 `.doc` reader (FIB, piece table, FKPs, SPRMs, stylesheet, lists, tables, notes, pictures) over a CFB container |
|
||||
| L2 | [`docx`](../crates/docx/src) | 37,376 | OOXML WordprocessingML reader/writer (Transitional and Strict), OMML, custom properties and preserved VBA parts |
|
||||
|
||||
@@ -93,7 +93,7 @@ Weights are the share of a Word user's file traffic (estimate). Read/write: ✅
|
||||
| Encrypted/password-protected `.doc` (XOR/RC4) | <1% | R | 🟡 | — | ~60% | 1–2 | `crates/docbin/src/tests/encrypted.rs` | XOR obfuscation, RC4 and RC4 CryptoAPI open with a password (`docbin` `crypt.rs`, #1079). An AES header (`fAES`) is refused with a clear message: [MS-OFFCRYPTO] defines AES only for encrypted packages, which open through the `.docx` reader (gap 9) |
|
||||
| `.md` Markdown | — | (no) | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word |
|
||||
| `.tex` LaTeX | — | — | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word (#11), incl. math |
|
||||
| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf` at their own frame size (#802), drawn by `crates/metafile`. Not yet: SVG, TIFF, ICO, HEIC |
|
||||
| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf`, EMF+ records included (#6636), at their own frame size (#802), drawn with craft-libs' `craft-metafile`. Not yet: SVG, TIFF, ICO, HEIC |
|
||||
| `.png` page images | — | (Save as picture, Mac) | — | ✅ | — | — | `io_ext.rs` | |
|
||||
| `.json` document model | — | — | ✅ | ✅ | — | — | engine tests | For agents. A table cell's span is any number in the file; Insert Column and Merge Cells count it as at most 63 columns, as the `.docx` reader does (#3637) |
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ pub const TABLE: &[(&str, Class)] = &[
|
||||
("control-key", Class::Standalone),
|
||||
("doc", Class::Layer(1)),
|
||||
("fonts", Class::Layer(1)),
|
||||
("metafile", Class::Layer(1)),
|
||||
("layout", Class::Layer(2)),
|
||||
("docx", Class::Layer(2)),
|
||||
("docbin", Class::Layer(2)),
|
||||
|
||||
Reference in New Issue
Block a user