f-office 0.2.2

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Tests that write a small DOCX file as PDF and compare it with the pages that
//! `f-office-raster` draws.

use f_office_docx::testing::{self, WordParts as _};
use f_office_raster::{GrayPixmap, Pixmap};
use hayro::hayro_interpret::InterpreterSettings;
use hayro::hayro_syntax::Pdf;
use hayro::vello_cpu::color::palette::css::WHITE;
use hayro::{PixmapSettings, RenderCache, RenderSettings};

use super::{Document, Options};
use crate::test_fonts::{CARLITO_FONTS, CARLITO_RUN, carlito};

/// The resolution of the comparison.
const DPI: u32 = 144;

/// A page of 300 by 200 points with two paragraphs of 11-point Carlito, one of them underlined.
fn body() -> String {
    format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t xml:space="preserve">The quick brown fox jumps over the lazy dog, and then it runs back again to see whether the dog has noticed anything at all.</w:t></w:r></w:p><w:p><w:r><w:rPr>{CARLITO_FONTS}<w:u w:val="single"/></w:rPr><w:t>Underlined words</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="6000" w:h="4000"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr>"#
    )
}

/// Packs `body` as the body of the main document of a DOCX file, with empty document defaults,
/// so that the text keeps the defaults of ECMA-376 and not those of Word's template.
fn docx(body: &str) -> Vec<u8> {
    testing::docx(body).plain_styles().zip().unwrap()
}

/// Draws each page of a PDF with hayro at [`DPI`], in gray.
fn draw_pdf(pdf: &[u8], render_settings: RenderSettings) -> Vec<GrayPixmap> {
    let pdf = Pdf::new(pdf.to_vec()).unwrap();
    let cache = RenderCache::new();
    let scale = 2.0;
    let pixmap_settings = PixmapSettings {
        x_scale: scale,
        y_scale: scale,
        bg_color: WHITE,
    };
    pdf.pages()
        .iter()
        .map(|page| {
            let settings = InterpreterSettings::default();
            let drawn = hayro::render(page, &cache, &settings, &render_settings, &pixmap_settings);
            let rgba = Pixmap::new(
                u32::from(drawn.width()),
                u32::from(drawn.height()),
                drawn.data_as_u8_slice().to_vec(),
            )
            .unwrap();
            rgba.to_gray()
        })
        .collect()
}

/// The ink Jaccard of two images of one size: pixels with gray below 128 in both, divided by
/// pixels with gray below 128 in either.
fn ink_jaccard(first: &GrayPixmap, second: &GrayPixmap) -> f64 {
    assert_eq!(
        (first.width(), first.height()),
        (second.width(), second.height())
    );
    let ink = |gray: &u8| *gray < 128;
    let pairs = first.data().iter().zip(second.data());
    let (both, either) = pairs.fold((0_u32, 0_u32), |(both, either), (a, b)| {
        (
            both + u32::from(ink(a) && ink(b)),
            either + u32::from(ink(a) || ink(b)),
        )
    });
    f64::from(both) / f64::from(either)
}

/// The one-page sample is 9,344 bytes, most of which is the subset of Carlito. The whole font
/// has 628,032 bytes.
#[test]
fn writes_the_pages_of_a_docx_file_with_a_font_subset() {
    let fonts = carlito();
    let file = docx(&body());
    let document = Document::open(&file, &fonts, &Options::base())
        .unwrap()
        .value;
    let pdf = document.write_pdf(&fonts).unwrap().value;
    let written = f_office_pdf::write_pdf(document.display_list(), &fonts);
    assert_eq!(pdf, written.unwrap().value);
    assert!(pdf.len() < 12_000, "{}", pdf.len());
    assert_eq!(Pdf::new(pdf).unwrap().pages().len(), document.page_count());
}

/// Returns the ink Jaccard of each page as hayro draws the PDF with `settings` and as
/// `f-office-raster` draws the display list, both at 144 DPI.
fn jaccards_against_the_raster(settings: RenderSettings) -> Vec<f64> {
    let fonts = carlito();
    let file = docx(&body());
    let document = Document::open(&file, &fonts, &Options::base())
        .unwrap()
        .value;
    let drawn = draw_pdf(&document.write_pdf(&fonts).unwrap().value, settings);
    assert_eq!(drawn.len(), document.page_count());
    let pages = document.pages().iter().zip(&drawn);
    pages
        .map(|(page, from_pdf)| {
            let raster = f_office_raster::render_page(page, &fonts, DPI)
                .unwrap()
                .value;
            ink_jaccard(&raster.to_gray(), from_pdf)
        })
        .collect()
}

/// With hayro's default settings, the ink Jaccard against
/// `f-office-raster` is 0.817 on the sample page, not 1, because the two rasterizers differ.
/// hayro hints the glyph outlines and caches the pixels of each glyph, which both move glyph
/// edges onto other pixels, while `f-office-raster` fills unhinted outlines at their exact
/// positions. With hayro's hinting on and its cache off the Jaccard is 0.810, and with hinting
/// off and the cache on it is 0.835.
#[test]
fn draws_like_the_raster_of_the_display_list_with_default_hayro_settings() {
    for jaccard in jaccards_against_the_raster(RenderSettings::default()) {
        assert!((0.78..0.86).contains(&jaccard), "{jaccard}");
    }
}

/// With hayro's hinting and glyph cache off, both rasterizers fill the same unhinted outlines at
/// the same positions, and the ink Jaccard is 0.9998 on the sample page. This shows that the
/// PDF puts every glyph and rectangle where the display list puts it.
#[test]
fn draws_like_the_raster_of_the_display_list_without_hinting() {
    let plain = RenderSettings {
        hinting: false,
        glyph_caching: false,
        ..RenderSettings::default()
    };
    for jaccard in jaccards_against_the_raster(plain) {
        assert!(jaccard > 0.995, "{jaccard}");
    }
}