use f_office_fonts::SymbolFont;
use f_office_paint::paper_forms::{DocumentedSide, PaperForm, page_entry};
use f_office_paint::{Orientation, PictureCrop};
use super::{
Decimal, Error, Facts, Layer, Merged, OffOr, Overrides, Profile, Section, Setting, Target,
WriterTable,
};
use crate::configuration::{Configuration, NumberSeparators};
use crate::grid::DOT;
use f_office_units::Length;
const TARGETS: [(&str, Option<&str>, i64, i64); 3] = [
("word-mac", None, 2480 * DOT, DOT),
(
"word-web",
Some("word-mac"),
2381 * Length::UNITS_PER_POINT / 4,
Length::UNITS_PER_POINT / 4,
),
(
"word-win",
Some("word-mac"),
4961 * Length::UNITS_PER_INCH / 600,
Length::UNITS_PER_INCH / 600,
),
];
#[test]
fn reads_every_target_and_its_profile() {
assert_eq!(Target::all().count(), TARGETS.len());
for (target, row) in Target::all().zip(TARGETS) {
check_target(target, row);
}
}
#[test]
fn written_width_source_uses_the_evidenced_font_path() {
use crate::quirks::WrittenWidths::{HintedAdvanceAt1000, RoundsAdvance};
for (target, expected) in [
("word-mac", RoundsAdvance),
("word-web", HintedAdvanceAt1000),
("word-win", HintedAdvanceAt1000),
] {
assert_eq!(
Profile::of(target.parse().unwrap())
.unwrap()
.quirks()
.written_widths,
expected
);
}
}
#[test]
fn writer_adjustment_count_is_the_targets() {
use crate::quirks::WriterAdjustments::{ExactIdeal, SingleCount, TwoSums};
for (target, expected) in [
("word-mac", ExactIdeal),
("word-web", SingleCount),
("word-win", TwoSums),
] {
assert_eq!(
Profile::of(target.parse().unwrap())
.unwrap()
.quirks()
.writer_adjustments,
expected
);
}
}
fn check_target(target: Target, (id, inherits, a4_width, dot): (&str, Option<&str>, i64, i64)) {
assert_eq!(target.to_string(), id);
assert_eq!(id.parse::<Target>(), Ok(target));
let profile = Profile::of(target).unwrap();
assert!(profile.to_string().starts_with(&format!("{id} 1 (")));
let width = profile.writer().page_side(Length::from_units(15_120_000));
assert_eq!(width.units(), a4_width, "{id}");
assert_eq!(profile.device().dots(1).units(), dot, "{id}");
let facts = Facts::of(target).unwrap();
assert_eq!(
(facts.id.as_str(), facts.inherits.as_deref()),
(id, inherits)
);
}
#[test]
fn writes_jpeg_pictures_again_only_where_the_writer_does() {
let quality = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.jpeg_quality()
.map(f_office_paint::JpegQuality::get)
};
assert_eq!(quality("word-win"), Some(75));
assert_eq!(quality("word-web"), Some(75));
assert_eq!(quality("word-mac"), None);
}
#[test]
fn resamples_dense_pictures_only_where_the_writer_does() {
let points = |p: i64| Length::from_units(Length::UNITS_PER_POINT * p);
let size = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.resampled_size((600, 450), (points(108), points(81)), None)
.map(|(pixels, _)| pixels)
};
assert_eq!(size("word-win"), Some((299, 224)));
assert_eq!(size("word-web"), None);
assert_eq!(size("word-mac"), None);
let dense = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.resampled_size((900, 675), (points(108), points(81)), None)
.map(|(pixels, _)| pixels)
};
assert_eq!(dense("word-web"), Some((449, 337)));
assert_eq!(dense("word-mac"), None);
}
#[test]
fn keeps_palette_pictures_to_limits_of_their_own_only_where_the_writer_does() {
let points = |p: i64| Length::from_units(Length::UNITS_PER_POINT * p);
let one_bit = Some(f_office_paint::PaletteClass::OneBit);
let size = |id: &str, pixels| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.resampled_size(pixels, (points(108), points(81)), one_bit)
};
let centre = f_office_paint::Resampler::CentrePixel;
assert_eq!(size("word-win", (1_124, 842)), None);
assert_eq!(size("word-win", (1_125, 844)), Some(((899, 674), centre)));
let count = std::num::NonZeroU32::new(1 << 17).unwrap();
let filter = f_office_paint::Resampler::Filter(f_office_paint::LinearLimit::Pixels(count));
assert_eq!(size("word-web", (1_125, 844)), Some(((449, 337), filter)));
assert_eq!(size("word-mac", (1_125, 844)), None);
}
#[test]
fn writes_baselines_with_five_significant_digits_where_the_writer_does() {
let digits = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.digits()
.map(std::num::NonZeroU32::get)
};
assert_eq!(digits("word-win"), Some(5));
assert_eq!(digits("word-web"), Some(5));
assert_eq!(digits("word-mac"), None);
let steps = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.rectangle_steps()
.map(std::num::NonZeroU32::get)
};
assert_eq!(steps("word-win"), Some(3_000));
assert_eq!(steps("word-web"), None);
assert_eq!(steps("word-mac"), None);
}
#[test]
fn counts_baseline_steps_where_the_writer_does() {
let baseline_steps = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.baseline_steps()
.map(std::num::NonZeroU32::get)
};
assert_eq!(baseline_steps("word-web"), Some(2_880));
assert_eq!(baseline_steps("word-win"), None);
assert_eq!(baseline_steps("word-mac"), None);
}
#[test]
fn keeps_two_decimals_where_the_writer_does() {
let least = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.least_decimals()
};
assert_eq!(least("word-win"), 2);
assert_eq!(least("word-web"), 2);
assert_eq!(least("word-mac"), 0);
}
#[test]
fn writes_cropped_pictures_as_their_visible_part_only_where_the_writer_does() {
let crop = |id: &str| {
Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.picture_crop()
};
assert_eq!(crop("word-win"), PictureCrop::VisiblePartAtScale);
assert_eq!(crop("word-web"), PictureCrop::VisiblePart);
assert_eq!(crop("word-mac"), PictureCrop::WholeFileUnderClip);
}
#[test]
fn counts_stretch_steps_with_factors_only_where_the_writer_does() {
let writer = |id: &str| Profile::of(id.parse().unwrap()).unwrap().writer();
let without = |id: &str| writer(id).with_stretch_factors((0, 1), &[]).unwrap();
assert_ne!(writer("word-web"), without("word-web"));
assert_eq!(writer("word-mac"), without("word-mac"));
assert_eq!(writer("word-win"), without("word-win"));
}
#[test]
fn reads_a_decimal_number_as_a_fraction() {
use super::decimal_fraction;
assert_eq!(decimal_fraction("0.031"), Some((31, 1000)));
assert_eq!(decimal_fraction("-2"), Some((-2, 1)));
assert_eq!(decimal_fraction("1.018640"), Some((1_018_640, 1_000_000)));
for text in ["", ".5", "1.2.3", "x", "1e3"] {
assert_eq!(decimal_fraction(text), None, "{text}");
}
}
#[test]
fn reads_the_stretch_factors_of_written_page_heights() {
use super::stretch_factors;
let points = |p: i64| Length::from_units(Length::UNITS_PER_POINT * p);
assert_eq!(
stretch_factors("792 1.003165, 841.75 1"),
Ok(vec![
(points(792), (1_003_165, 1_000_000)),
(Length::from_units(21_380_450), (1, 1)),
])
);
assert_eq!(stretch_factors(""), Ok(Vec::new()));
let key = Error::Value("stretch_factors");
for list in ["792", "792 1 2", "0 1", "792 -1", "0.00001 1"] {
assert_eq!(stretch_factors(list), Err(key.clone()), "{list}");
}
}
fn start_offset(id: &str) -> f_office_paint::WriterOffset {
match Profile::of(id.parse().unwrap())
.unwrap()
.device()
.advances()
{
crate::grid::Advances::RightEdge { start, .. } => start,
crate::grid::Advances::PdfSteps => f_office_paint::WriterOffset::NONE,
}
}
fn page_steps(offset: f_office_paint::Offset) -> (f_office_paint::Fraction, i64) {
match offset {
f_office_paint::Offset::Page { steps, parts, .. } => (steps, parts),
_ => ((0, 1), 0),
}
}
const fn written_side(dots: i64) -> i64 {
dots * DOT / 2
}
const LETTER: PaperForm = PaperForm::inches("Letter", 8_500, 11_000);
const A3: PaperForm = PaperForm::millimetres("A3", 297, 420);
const A4: PaperForm = PaperForm::millimetres("A4", 210, 297);
fn entry_steps(dots: i64, side: DocumentedSide) -> f_office_paint::Fraction {
let writer = (16, 3_000, 600);
let entry = page_entry(dots, side.form_side(600), writer).unwrap();
f_office_paint::paper_forms::entry_steps(entry, dots, writer).unwrap()
}
#[test]
fn gives_two_sizes_near_a4_the_entries_that_word_s_lines_fit() {
let windows = start_offset("word-win");
let entry = |((count, per), parts): (f_office_paint::Fraction, i64), dots: i64| {
let (count, per, parts, dots) = (
i128::from(count),
i128::from(per),
i128::from(parts),
i128::from(dots),
);
f_office_units::binary32::Binary32::nearest(parts * (5 * dots * per + count), dots * per)
};
let fit = |count| ((count, 100_000), 16);
for ((width, height), (across, down)) in [
((4_961, 7_017), (472_645, 500_296)),
((4_958, 7_017), (508_057, 500_296)),
] {
let (on_across, on_down) = windows.on_page(
written_side(width),
written_side(height),
Orientation::Portrait,
);
assert_eq!(
entry(page_steps(on_across), width),
entry(fit(across), width)
);
assert_eq!(entry(page_steps(on_down), height), entry(fit(down), height));
}
}
#[test]
fn gives_measured_sizes_their_steps_in_their_orientation() {
let windows = start_offset("word-win");
let on_page = |(width, height), orientation| {
let (across, down) =
windows.on_page(written_side(width), written_side(height), orientation);
(page_steps(across), page_steps(down))
};
let steps = |count| ((count, 100_000), 16);
let (dots, (across, down)) = crate::params::PAGE_4961_7016_STEPS;
assert_eq!(dots, (4_961, 7_016));
assert_eq!(
on_page(dots, Orientation::Portrait),
(steps(across), steps(down))
);
let (dots, (across, down)) = crate::params::PAGE_7016_4961_STEPS;
assert_eq!(dots, (7_016, 4_961));
assert_eq!(
on_page(dots, Orientation::Landscape),
(steps(across), steps(down))
);
let a3 = |dots, side| (entry_steps(dots, side), 16);
let (across, down) = (A3.across, A3.down);
assert_eq!(
on_page((7_016, 4_961), Orientation::Portrait),
(a3(7_016, across), a3(4_961, down))
);
assert_eq!(
on_page((7_016, 9_921), Orientation::Portrait),
(a3(7_016, across), a3(9_921, down))
);
}
#[test]
fn gives_every_other_page_the_entries_of_its_paper_form() {
let windows = start_offset("word-win");
let (across, down) = windows.on_page(
written_side(4_962),
written_side(7_014),
Orientation::Portrait,
);
assert_eq!(page_steps(across), (entry_steps(4_962, A4.across), 16));
assert_eq!(page_steps(down), (entry_steps(7_014, A4.down), 16));
assert_ne!(page_steps(across).0, (473_073, 100_000));
}
#[test]
fn gives_a_letter_page_its_own_steps_across_and_letters_factor_down() {
let windows = start_offset("word-win");
let letter = (473_073, 100_000);
let a3_down = entry_steps(5_100, A3.down);
for (orientation, down) in [
(Orientation::Portrait, a3_down),
(Orientation::Landscape, (472_515, 100_000)),
] {
let on_page = |width, height| {
let (across, down) =
windows.on_page(written_side(width), written_side(height), orientation);
(page_steps(across).0, page_steps(down).0)
};
assert_eq!(on_page(5_100, 6_600), ((472_515, 100_000), letter));
assert_eq!(on_page(6_600, 5_100), (letter, down));
}
}
#[test]
fn holds_the_drivers_papers_and_the_documented_rotated_forms() {
let forms = crate::params::PAPER_FORMS;
assert_eq!(forms.len(), 107);
let first_rotated = forms
.iter()
.position(|form| form.orientation == Orientation::Landscape);
assert_eq!(first_rotated, Some(84));
let names: std::collections::BTreeSet<&str> = forms.iter().map(|form| form.name).collect();
assert_eq!(names.len(), forms.len());
for form in forms {
let rotated = form.orientation == Orientation::Landscape;
assert_eq!(rotated, form.name.ends_with("_ROTATED"), "{}", form.name);
}
let rule = crate::params::PAPER_FORM_CLASS_RULE;
assert_eq!((forms.first(), rule.last), (Some(&LETTER), LETTER));
assert_eq!(rule.holding, [A4, A3]);
}
#[test]
fn offsets_the_starts_of_win_starts_by_the_steps_of_words_pages() {
let windows = start_offset("word-win");
let across = |(width, height): (i64, i64), dot: i64| {
let portrait = Orientation::Portrait;
let (offset, _) = windows.on_page(written_side(width), written_side(height), portrait);
offset.of(written_side(dot), written_side(width))
};
assert_eq!(across((5_100, 6_600), 1_585), 610);
assert_eq!(across((5_100, 6_600), 1_586), 1_219);
assert_eq!(across((4_961, 7_016), 1_540), 610);
assert_eq!(across((4_961, 7_016), 1_544), 1_219);
}
#[test]
fn gives_measured_sizes_only_in_the_profile_of_word_win() {
let sizes = |id| matches!(start_offset(id), f_office_paint::WriterOffset::Sizes(_));
assert_eq!(
["word-win", "word-mac", "word-web"].map(sizes),
[true, false, false]
);
}
#[test]
fn gives_each_writer_its_linear_limit() {
let inch = Length::from_units(Length::UNITS_PER_INCH);
let limit = |id: &str| {
let answer = Profile::of(id.parse().unwrap())
.unwrap()
.writer()
.resampled_size((600, 600), (inch, inch), None);
match answer {
Some((_, f_office_paint::Resampler::Filter(limit))) => Some(limit),
_ => None,
}
};
let count = |n| std::num::NonZeroU32::new(n).unwrap();
assert_eq!(
limit("word-win"),
Some(f_office_paint::LinearLimit::Side(count(419)))
);
assert_eq!(
limit("word-web"),
Some(f_office_paint::LinearLimit::Pixels(count(1 << 17)))
);
}
#[test]
fn sets_a_quirk_in_place_of_the_profiles_own() {
use crate::quirks::Markup;
for target in Target::all() {
let profile = Profile::of(target).unwrap();
let own = profile.quirks().markup;
let same = profile.with_variant(own);
assert_eq!(same.quirks(), profile.quirks());
assert_eq!(same.device(), profile.device());
assert_eq!(same.writer(), profile.writer());
assert_eq!(same.reader_settings(), profile.reader_settings());
let other = [Markup::PrintsMarkupArea, Markup::PrintsNoMarkup]
.into_iter()
.find(|markup| *markup != own)
.unwrap();
assert_eq!(profile.with_variant(other).quirks().markup, other);
}
}
#[test]
fn lists_the_variant_that_each_target_takes_of_every_quirk() {
let facts = Facts::all().unwrap();
let own = |id: &str| -> std::collections::BTreeMap<&str, &str> {
facts
.iter()
.filter(|fact| fact.id == id)
.flat_map(|fact| &fact.entries)
.filter(|(entry, _)| entry.section == Section::Quirks)
.map(|(entry, _)| (entry.name.as_str(), entry.value.as_str()))
.collect()
};
for fact in &facts {
let variants = Profile::of(fact.id.parse().unwrap()).unwrap().variants();
let quirks: Vec<_> = variants.iter().map(|(quirk, _)| *quirk).collect();
assert_eq!(quirks, crate::quirks::NAMES, "{}", fact.id);
let mut written = fact.inherits.as_deref().map_or_default(own);
written.extend(own(&fact.id));
assert_eq!(
variants
.into_iter()
.collect::<std::collections::BTreeMap<_, _>>(),
written
);
}
}
#[test]
fn says_whether_a_target_takes_a_variant_named_by_its_quirk() {
for target in Target::all() {
let profile = Profile::of(target).unwrap();
for (quirk, variant) in profile.variants() {
let taken = format!("{quirk}::{variant}");
assert_eq!(profile.chooses(&taken), Some(true), "{taken}");
}
assert_eq!(profile.chooses("Markup::Never"), None);
assert_eq!(profile.chooses("Never::PrintsNoMarkup"), None);
assert_eq!(profile.chooses("Markup"), None);
}
let win = Profile::of("word-win".parse().unwrap()).unwrap();
assert_eq!(win.chooses("Markup::PrintsMarkupArea"), Some(false));
}
fn layer(json: &str) -> Layer {
serde_json::from_str(json).unwrap()
}
fn writer_table(json: &str) -> WriterTable {
layer(&format!(r#"{{"writer":{json}}}"#)).writer
}
fn setting<T: serde::de::DeserializeOwned>(written: &str) -> Result<Setting<T>, String> {
serde_json::from_str(&format!(r#"{{"value":{written}}}"#)).map_err(|e| e.to_string())
}
fn resolved(id: &str, configuration: &str, overrides: &str) -> Result<Profile, Error> {
let mut chosen = Configuration::of(id.parse().unwrap());
chosen.merge(&serde_json::from_str(configuration).unwrap(), &mut |_| {});
let overrides = if overrides == "{}" {
Overrides::default()
} else {
Overrides::default().with_layer("test", layer(overrides))
};
Profile::resolve(&chosen, &overrides)
}
fn with(id: &str, json: &str) -> Result<Profile, Error> {
resolved(id, "{}", json)
}
fn configured(id: &str, json: &str) -> Result<Profile, Error> {
resolved(id, json, "{}")
}
#[test]
fn names_a_font_environment_for_each_target() {
for target in Target::all() {
let profile = Profile::of(target).unwrap();
assert_eq!(
profile.font_environment_path(),
format!("fonts/{target}.toml")
);
assert_eq!(
profile.origin("fonts.environment"),
Some(target.to_string().as_str())
);
let environment = profile.font_environment();
assert_ne!(environment.faces(), []);
assert!(std::ptr::eq(
environment,
Profile::of(target).unwrap().font_environment()
));
}
}
#[test]
fn keeps_each_font_environment_as_its_table_writes_it() {
for target in Target::all() {
let profile = Profile::of(target).unwrap();
let table = super::environment_table(profile.font_environment_path()).unwrap();
let mut written = super::fonts::table(profile.font_environment());
written.symbol_font.clone_from(&table.symbol_font);
assert!(written == *table, "{target}");
}
}
#[test]
fn keeps_whole_widths_of_symbol_fonts_in_each_font_environment() {
for target in Target::all() {
let profile = Profile::of(target).unwrap();
let table = super::environment_table(profile.font_environment_path()).unwrap();
for (family, entry) in &table.symbol_font {
let place = format!("{target}: {family}");
assert!(SymbolFont::of(family).is_some(), "{place}");
assert!(entry.units_per_em.is_some_and(|units| units > 0), "{place}");
check_symbol_codes(&place, entry);
}
}
}
fn check_symbol_keys(place: &str, entry: &super::fonts::SymbolFontEntry) {
let missing = super::fonts::SymbolFontEntry::MISSING_GLYPH;
let private_use = |key: &String| {
key == missing
|| u32::from_str_radix(key, 16).is_ok_and(|code| (0xF020..=0xF0FF).contains(&code))
};
assert!(entry.advance.keys().all(private_use), "{place}");
assert!(entry.advance.contains_key(missing), "{place}");
}
fn check_symbol_codes(place: &str, entry: &super::fonts::SymbolFontEntry) {
let most = entry.measured_sizes.unwrap_or(0);
check_symbol_keys(place, entry);
for (key, sizes) in entry.wider.iter().chain(&entry.narrower) {
assert!(entry.advance.contains_key(key), "{place} {key}");
assert!(
sizes.windows(2).all(|pair| pair[0] < pair[1]),
"{place} {key}"
);
assert!(
sizes.iter().all(|&size| (1..=most).contains(&size)),
"{place} {key}"
);
}
for (key, sizes) in &entry.wider {
let narrower = entry.narrower.get(key).map_or(&[][..], Vec::as_slice);
assert!(
sizes.iter().all(|size| !narrower.contains(size)),
"{place} {key}"
);
}
}
#[test]
fn takes_the_widths_of_a_symbol_font_of_a_later_layer_as_one_value() {
let mut own: super::fonts::Table = serde_json::from_str(
r#"{"symbol_font": {"Symbol": {"units_per_em": 2048, "advance": {"F020": 512, "F041": 1479}, "wider": {"F041": [57]}}}}"#,
)
.unwrap();
let later: super::fonts::Table = serde_json::from_str(
r#"{"symbol_font": {"Symbol": {"units_per_em": 1000, "advance": {"F041": 700}}}}"#,
)
.unwrap();
let mut paths = Vec::new();
own.merge(&later, &mut |path| paths.push(path.join(".")));
assert_eq!(own.symbol_font, later.symbol_font);
assert_eq!(paths, ["symbol_font.Symbol"]);
}
#[test]
fn names_the_base_target_as_the_default() {
let base = Target::all().next().unwrap();
assert_eq!(Target::base(), base);
assert_eq!(Target::default().to_string(), "word-win");
let unknown = "word-ios".parse::<Target>().unwrap_err();
assert_eq!(unknown, Error::UnknownTarget("word-ios".to_owned()));
assert_eq!(unknown.to_string(), "no target is named \"word-ios\"");
}
#[test]
fn lists_each_value_with_the_value_that_it_overrides() {
let facts = Facts::all().unwrap();
let base = &facts[0];
assert!(
base.entries
.iter()
.all(|(_, overridden)| overridden.is_none())
);
let web = &facts[1];
let (entry, overridden) = web
.entries
.iter()
.find(|(entry, _)| entry.name == "page_steps_per_inch")
.unwrap();
assert_eq!(
(entry.section, entry.value.as_str(), overridden.as_deref()),
(Section::Writer, "288", Some("300"))
);
}
#[test]
fn lists_the_entries_of_a_layer_as_written() {
let entries = super::facts::entries(&layer(
r#"{"quirks":{"DescentRounding":{"value":"TruncateToTwips"}},
"writer":{"digits":{"value":5},"offset":{"value":"off"}}}"#,
));
let entries: Vec<_> = entries
.iter()
.map(|e| (e.section, e.name.as_str(), e.value.as_str()))
.collect();
assert_eq!(
entries,
[
(Section::Writer, "digits", "5"),
(Section::Writer, "offset", "\"off\""),
(Section::Quirks, "DescentRounding", "TruncateToTwips"),
]
);
}
#[test]
fn takes_an_added_family_as_present_for_every_use_of_the_font_environment() {
let built_in = Profile::of("word-win".parse().unwrap()).unwrap();
let fonts = built_in.font_environment();
assert!(fonts.lacks("Andalus"));
assert_eq!(fonts.family_substitute("Andalus"), Some("Arial"));
assert_eq!(fonts.metafile_face("Andalus", 0, 0), Some("Arial"));
let added = configured("word-win", r#"{"fonts":{"installed":{"Andalus":true}}}"#).unwrap();
let fonts = added.font_environment();
assert!(!fonts.lacks("Andalus"));
assert_eq!(fonts.family_substitute("Andalus"), None);
assert_eq!(fonts.metafile_face("Andalus", 0, 0), None);
assert_eq!(added.added_families().collect::<Vec<_>>(), ["Andalus"]);
}
#[test]
fn takes_a_removed_family_as_one_that_the_target_lacks() {
let built_in = Profile::of("word-win".parse().unwrap()).unwrap();
assert!(!built_in.font_environment().lacks("Arial"));
let removed = configured("word-win", r#"{"fonts":{"installed":{"Arial":false}}}"#).unwrap();
assert!(removed.font_environment().lacks("Arial"));
assert_eq!(removed.added_families().count(), 0);
}
#[test]
fn refuses_a_layer_that_is_not_one() {
for json in [
r#"{"colour":{"red":{"value":1}}}"#,
r#"{"writer":{"a":{"value":1}}}"#,
r#"{"writer":{"digits":{}}}"#,
r#"{"writer":{"digits":{"value":"x"}}}"#,
r#"{"writer":{"digits":{"value":1,"note":"n"}}}"#,
r#"{"quirks":{"Markup":{"value":3}}}"#,
r#"{"params":{"LINE":{"value":16}}}"#,
r#"{"fonts":{"available":{"Aptos":"yes"}}}"#,
r#"{"layout":{"device_dots_per_inch":{"value":600}}}"#,
r#"{"configuration":{"printer":{"resolution":600}}}"#,
] {
assert!(serde_json::from_str::<Layer>(json).is_err(), "{json}");
}
assert_eq!(
with("word-win", r#"{"version":0}"#),
Err(Error::Value("version"))
);
}
#[test]
fn refuses_an_override_that_sets_what_only_a_profile_or_the_configuration_sets() {
for (json, key) in [
(r#"{"product":"p"}"#, "product"),
(r#"{"renderer":"r"}"#, "renderer"),
(
r#"{"fonts":{"environment":"fonts/word-mac.toml"}}"#,
"fonts.environment",
),
(r#"{"configuration":{"zone_minutes":60}}"#, "configuration"),
] {
assert_eq!(
with("word-win", json),
Err(Error::BuiltInKey(key)),
"{json}"
);
}
assert_eq!(
with("word-win", r#"{"inherits":"word-mac"}"#),
Err(Error::Inherits("test".to_owned()))
);
assert!(with("word-win", r#"{"id":"mine","inherits":"word-win"}"#).is_ok());
}
#[test]
fn says_what_is_wrong_with_a_profile() {
let cases = [
(Error::Missing("id"), "a profile has no id"),
(Error::Value("a"), "a profile has a wrong value for a"),
(
Error::Pair("a", "b"),
"a profile sets only one of a and b, which are \"off\" or set together",
),
(
Error::Group(&["a", "b", "c"]),
"a profile sets only some of a, b, c, which are \"off\" or set together",
),
(
Error::BuiltInKey("product"),
"an override sets product, which only a profile or the configuration sets",
),
(
Error::NotRead("fonts.use"),
"the configuration sets fonts.use, which F-Office does not read yet",
),
];
for (error, message) in cases {
assert_eq!(error.to_string(), message);
}
}
#[test]
fn names_the_variant_of_every_quirk_for_every_target() {
use crate::quirks::Markup;
for (target, markup) in [
("word-mac", Markup::PrintsMarkupArea),
("word-web", Markup::PrintsNoMarkup),
("word-win", Markup::PrintsNoMarkup),
] {
let configuration = Profile::of(target.parse().unwrap()).unwrap();
assert_eq!(configuration.quirks().markup, markup, "{target}");
}
let base = &Merged::of(Target::base()).unwrap().layer;
let quirks = |name: &str, variant: &str| {
super::quirks(&base.clone().with_quirk(name, variant)).map(|quirks| quirks.markup)
};
assert_eq!(
quirks("Markup", "PrintsNoMarkup"),
Ok(Markup::PrintsNoMarkup)
);
assert_eq!(
quirks("Nothing", "X"),
Err(Error::UnknownQuirk("Nothing".to_owned()))
);
assert_eq!(quirks("Markup", "Never"), Err(Error::Value("Markup")));
assert_eq!(
super::quirks(&Layer::default()),
Err(Error::Missing("Markup"))
);
}
#[test]
fn names_every_key_of_a_palette_density_that_a_profile_sets_only_some_of() {
let density = |values: [&str; 4]| {
let keys: Vec<String> = (super::PALETTE_DENSITY_KEYS.iter().zip(values))
.map(|(key, value)| format!(r#""{key}":{{"value":{value}}}"#))
.collect();
let writer = writer_table(&format!("{{{}}}", keys.join(",")));
super::palette_density(&writer).map(|density| density.map(|d| d.one_bit_ppi.get()))
};
let off = "\"off\"";
let group = Error::Group(&super::PALETTE_DENSITY_KEYS);
assert_eq!(density(["750", off, off, off]), Err(group.clone()));
assert_eq!(density(["750", "600", "562", off]), Err(group));
assert_eq!(density([off; 4]), Ok(None));
assert_eq!(density(["750", "600", "562", "395"]), Ok(Some(600)));
}
#[test]
fn names_both_keys_of_a_pair_that_a_profile_sets_only_one_of() {
let density = |limit: &str, ppi: &str| {
let writer = writer_table(&format!(
r#"{{"picture_limit_ppi":{{"value":{limit}}},"picture_ppi":{{"value":{ppi}}}}}"#
));
super::picture_density(&writer)
.map(|density| density.map(|d| (d.limit_ppi.get(), d.ppi.get())))
};
let pair = Error::Pair("picture_limit_ppi", "picture_ppi");
assert_eq!(density("\"off\"", "200"), Err(pair.clone()));
assert_eq!(density("275", "\"off\""), Err(pair));
assert_eq!(density("\"off\"", "\"off\""), Ok(None));
assert_eq!(density("275", "200"), Ok(Some((275, 200))));
}
#[test]
fn reads_a_setting_that_can_be_off_with_one_spelling_for_each_meaning() {
let count = |written| {
setting::<OffOr>(written).map(|setting| super::count_or_off(Some(&setting), "digits"))
};
assert_eq!(count("\"off\""), Ok(Ok(None)));
assert_eq!(
count("5").map(|digits| digits.map(|digits| digits.map(std::num::NonZeroU32::get))),
Ok(Ok(Some(5)))
);
for written in ["0", "-5", "4294967296"] {
assert_eq!(count(written), Ok(Err(Error::Value("digits"))), "{written}");
}
assert!(count("\"none\"").is_err());
let quality = |written| {
super::off_or(
Some(&setting(written).unwrap()),
"jpeg_quality",
|quality| {
u8::try_from(quality)
.ok()
.and_then(f_office_paint::JpegQuality::new)
},
)
};
assert_eq!(
quality("100").map(|q| q.map(f_office_paint::JpegQuality::get)),
Ok(Some(100))
);
assert_eq!(quality("101"), Err(Error::Value("jpeg_quality")));
}
#[test]
fn reads_a_step_from_its_steps_per_inch() {
let step = |written| super::step_per_inch(Some(&setting(written).unwrap()), "steps");
assert_eq!(step("2880"), Ok(Some(Length::from_units(635))));
assert_eq!(step("600"), Ok(Some(Length::from_units(3_048))));
assert_eq!(step("\"off\""), Ok(None));
for written in ["7", "-40", "0"] {
assert_eq!(step(written), Err(Error::Value("steps")), "{written}");
}
}
#[test]
fn reads_the_separators_of_numbers() {
let separators = configured("word-win", r#"{"number_separators":",."}"#)
.map(|profile| profile.reader_settings());
let base = Profile::of("word-win".parse().unwrap()).unwrap();
let chosen = base
.reader_settings()
.with_number_separators(Some(NumberSeparators::new(',', '.').unwrap()));
assert_eq!(separators, Ok(chosen));
for written in ["..", ".", "0,"] {
let json = format!(r#"{{"number_separators":"{written}"}}"#);
assert!(
serde_json::from_str::<Configuration>(&json).is_err(),
"{written}"
);
}
}
#[test]
fn reads_the_form_of_the_writers_offset_with_its_own_keys() {
let offsets = |json: &str| {
super::writer_offsets(
super::Id::default(),
(
crate::quirks::PageOffsetSizes::OneFactor,
crate::quirks::PageOffsetProduct::Exact,
),
&writer_table(json),
)
};
let none = f_office_paint::WriterOffset::NONE;
assert_eq!(offsets(r#"{"offset":{"value":"off"}}"#), Ok((none, none)));
let share = r#"{"offset":{"value":"share_of_place"},
"start_offset_share":{"value":2400},
"start_offset_bias_half_emus":{"value":18},
"start_offset_step_half_emus":{"value":635}}"#;
let across = f_office_paint::WriterOffset::EveryPage(f_office_paint::Offset::Share {
share: 2_400,
bias: 18,
step: 635,
});
assert_eq!(offsets(share), Ok((across, none)));
assert_eq!(
offsets(r#"{"offset":{"value":"page_steps"}}"#),
Err(Error::Missing("offset_page_steps_per_inch"))
);
assert_eq!(
offsets(r#"{"offset":{"value":"none"}}"#),
Err(Error::Value("offset"))
);
}
#[test]
fn reads_a_whole_number_in_the_range_that_its_key_takes() {
let value = |number: i64| Setting { value: number };
let wrong = Some(Error::Value("k"));
assert_eq!(super::positive(Some(&value(3)), "k"), Ok(3));
assert_eq!(super::positive(Some(&value(0)), "k").err(), wrong);
assert_eq!(super::whole(Some(&value(0)), "k"), Ok(0));
assert_eq!(super::whole(Some(&value(-1)), "k").err(), wrong);
assert_eq!(super::number::<u8>(300, "k", |_| true).err(), wrong);
assert!(setting::<i64>("0.5").is_err());
}
#[test]
fn reads_decimal_numbers_as_written() {
let decimal = |written| setting::<Decimal>(written).map(|setting| setting.value.0);
assert_eq!(decimal("-2"), Ok((-2, 1)));
assert_eq!(decimal("0.031"), Ok((31, 1000)));
assert!(decimal("\"0.5\"").is_err());
assert_eq!(Decimal((31, 1000)).to_string(), "0.031");
assert_eq!(Decimal((-2, 1)).to_string(), "-2");
assert_eq!(
serde_json::to_string(&Decimal((31, 1000))).unwrap(),
"0.031"
);
}
#[test]
fn names_a_missing_key_in_its_error() {
assert_eq!(super::whole(None, "other"), Err(Error::Missing("other")));
}
#[test]
fn reads_how_the_writer_writes_a_cropped_picture_by_its_name() {
let crop = |written: &str| {
let setting = Setting {
value: written.to_owned(),
};
super::variant(Some(&setting), "picture_crop", &super::PICTURE_CROPS)
};
assert_eq!(crop("visible_part"), Ok(PictureCrop::VisiblePart));
assert_eq!(
crop("visible_part_at_scale"),
Ok(PictureCrop::VisiblePartAtScale)
);
assert_eq!(
crop("whole_file_under_clip"),
Ok(PictureCrop::WholeFileUnderClip)
);
assert_eq!(crop("clip"), Err(Error::Value("picture_crop")));
}
#[test]
fn records_the_layer_that_set_each_value() {
let win = resolved(
"word-win",
r#"{"zone_minutes":60,"fonts":{"installed":{"Aptos":true}}}"#,
r#"{"quirks":{"Markup":{"value":"PrintsMarkupArea"}}}"#,
)
.unwrap();
for (path, origin) in [
("id", "word-win"),
("version", "word-win"),
("configuration.printer.dots_per_inch", "word-win"),
("writer.vertical_stretch_steps", "word-mac"),
("configuration.zone_minutes", "configuration"),
("writer.page_steps_per_inch", "word-win"),
("quirks.Markup", "test"),
("quirks.LinkedStyles", "word-mac"),
("fonts.environment", "word-win"),
("configuration.fonts.installed.Aptos", "configuration"),
] {
assert_eq!(win.origin(path), Some(origin), "{path}");
}
let mac = Profile::of("word-mac".parse().unwrap()).unwrap();
let (family, styles) = super::environment_table("fonts/word-mac.toml")
.unwrap()
.face
.iter()
.find(|(family, _)| {
!(super::environment_table("fonts/word-win.toml")
.unwrap()
.face)
.contains_key(*family)
})
.unwrap();
let style = styles.keys().next().unwrap();
let path = format!(
"fonts.face.{}.{}.version",
super::path_key(family),
super::path_key(style)
);
assert_eq!(mac.origin(&path), Some("word-mac"), "{path}");
assert_eq!(win.origin(&path), None, "{path}");
assert_eq!(win.origin("nothing"), None);
}
#[test]
fn a_later_layer_wins() {
use crate::quirks::Markup;
let overrides = Overrides::default()
.with_layer(
"one",
Layer::default().with_quirk("Markup", "PrintsMarkupArea"),
)
.with_layer(
"two",
Layer::default().with_quirk("Markup", "PrintsNoMarkup"),
);
let configuration =
Profile::resolve(&Configuration::of("word-win".parse().unwrap()), &overrides).unwrap();
assert_eq!(configuration.quirks().markup, Markup::PrintsNoMarkup);
assert_eq!(configuration.origin("quirks.Markup"), Some("two"));
}
#[test]
fn builds_the_device_from_a_quirk_set_in_place_and_refuses_a_wrong_one() {
use crate::quirks::GridAdvances;
let profile = Profile::of("word-win".parse().unwrap()).unwrap();
let rounded = profile.with_variant(GridAdvances::RoundToPdfSteps);
assert_eq!(
rounded.quirks().grid_advances,
GridAdvances::RoundToPdfSteps
);
assert_ne!(rounded.device(), profile.device());
let quirk = |id: &str, name: &str, variant: &str| {
Profile::resolve(
&Configuration::of(id.parse().unwrap()),
&Overrides::default().with_quirk(name, variant),
)
};
assert_eq!(
quirk("word-mac", "GridAdvances", "RightEdgeSteps"),
Err(Error::Missing("glyph_step_bias_half_emus"))
);
assert_eq!(
quirk("word-win", "Nothing", "X"),
Err(Error::UnknownQuirk("Nothing".to_owned()))
);
assert_eq!(
quirk("word-win", "Markup", "Never"),
Err(Error::Value("Markup"))
);
}
#[test]
fn an_empty_layer_keeps_the_profiles_values() {
for target in Target::all() {
let profile = Profile::of(target).unwrap();
let empty = Profile::resolve(
&Configuration::of(target),
&Overrides::default().with_layer("empty", Layer::default()),
)
.unwrap();
assert_eq!(empty.device(), profile.device(), "{target}");
assert_eq!(empty.writer(), profile.writer(), "{target}");
assert_eq!(
empty.reader_settings(),
profile.reader_settings(),
"{target}"
);
assert_eq!(empty.quirks(), profile.quirks(), "{target}");
assert_eq!(
empty.font_environment(),
profile.font_environment(),
"{target}"
);
}
}
fn printer(dots: i64) -> String {
format!(r#"{{"printer":{{"dots_per_inch":{dots}}}}}"#)
}
#[test]
fn a_printer_resolution_sets_the_device_dot_only() {
let profile = Profile::of("word-win".parse().unwrap()).unwrap();
for (dots, dot) in [
(300, 6096),
(600, 3048),
(1200, 1524),
(2400, 762),
(3000, 610),
] {
let laid_out = configured("word-win", &printer(dots)).unwrap();
assert_eq!(laid_out.device_dot(), Length::from_units(dot), "{dots}");
assert_eq!(laid_out.quirks(), profile.quirks());
}
}
#[test]
fn a_printer_of_another_resolution_has_no_page_offset_unless_an_override_sets_one() {
use f_office_paint::WriterOffset;
let profile = Profile::of("word-win".parse().unwrap()).unwrap();
let none = profile
.writer()
.with_horizontal_offset(WriterOffset::NONE)
.with_vertical_offset(WriterOffset::NONE);
for (dots, writer) in [(600, profile.writer()), (1200, none), (3000, none)] {
assert_eq!(
configured("word-win", &printer(dots)).unwrap().writer(),
writer,
"{dots}"
);
}
let off = configured("word-win", r#"{"printer":{"page_offset":"none"}}"#).unwrap();
assert_eq!(off.writer(), none);
let off = with("word-win", r#"{"writer":{"offset":{"value":"off"}}}"#).unwrap();
assert_eq!(off.writer(), none);
let kept = resolved(
"word-win",
&printer(1200),
r#"{"writer":{"offset":{"value":"page_steps"}}}"#,
)
.unwrap();
assert_eq!(kept.writer(), profile.writer());
}
#[test]
fn refuses_a_printer_resolution_that_the_layout_cannot_lay_out_for() {
assert_eq!(
configured("word-win", &printer(3_657_600)),
Err(Error::Value("printer.dots_per_inch"))
);
assert!(serde_json::from_str::<Configuration>(&printer(0)).is_err());
}
fn choosing(chosen: &[(&str, &str)]) -> Layer {
chosen
.iter()
.fold(Layer::default(), |layer, (name, variant)| {
layer.with_quirk(name, variant)
})
}
#[test]
fn an_override_that_sets_the_profiles_own_variants_keeps_its_values() {
for target in Target::all() {
let profile = Profile::of(target).unwrap();
let chosen = Profile::resolve(
&Configuration::of(target),
&Overrides::default().with_layer("own", choosing(&profile.variants())),
)
.unwrap();
assert_eq!(chosen.device(), profile.device(), "{target:?}");
assert_eq!(chosen.writer(), profile.writer(), "{target:?}");
assert_eq!(
chosen.reader_settings(),
profile.reader_settings(),
"{target:?}"
);
assert_eq!(chosen.quirks(), profile.quirks(), "{target:?}");
}
}
#[test]
fn a_quirk_of_another_variant_reaches_the_device_the_writer_and_the_reader() {
let profile = Profile::of("word-win".parse().unwrap()).unwrap();
let with = |name, variant| {
Profile::resolve(
&Configuration::of("word-win".parse().unwrap()),
&Overrides::default().with_layer("test", choosing(&[(name, variant)])),
)
.unwrap()
};
for (name, variant) in [
("GridAdvances", "RoundToPdfSteps"),
("SingleBaseline", "CutDescent"),
] {
assert_ne!(with(name, variant).device(), profile.device(), "{name}");
}
assert_ne!(
with("PageOffsetSizes", "OneFactor").writer(),
profile.writer()
);
assert_ne!(
with("Markup", "PrintsMarkupArea").reader_settings(),
profile.reader_settings()
);
assert_ne!(
with("PageOffsetProduct", "Exact").writer(),
profile.writer()
);
assert_eq!(
Profile::of("word-win".parse().unwrap()).unwrap().writer(),
profile.writer()
);
}
fn zone(minutes: i32) -> String {
format!(r#"{{"zone_minutes":{minutes}}}"#)
}
#[test]
fn takes_the_machines_time_zone_from_the_configuration() {
let word_win = Profile::of("word-win".parse().unwrap()).unwrap();
assert_eq!(word_win.zone_minutes(), Ok(480));
for target in Target::all() {
let profile = Profile::of(target).unwrap();
let zoned = |minutes| {
configured(&target.to_string(), &zone(minutes)).map(|chosen| chosen.zone_minutes())
};
assert_eq!(
(
profile.zone_minutes().is_ok(),
zoned(-300),
zoned(1440),
zoned(-1440)
),
(
true,
Ok(Ok(-300)),
Err(Error::Value("zone_minutes")),
Err(Error::Value("zone_minutes"))
),
"{target}"
);
}
}
#[test]
fn needs_a_time_zone_where_a_date_property_is_written_as_its_local_date() {
let local = Profile::base().with_variant(crate::quirks::PropertyDateZone::LocalDate);
assert_eq!(local.zone_minutes(), Err(Error::Missing("zone_minutes")));
let mut configuration = local.configuration().clone();
configuration.zone_minutes = Some(60);
let zoned = Profile::resolve(&configuration, local.overrides()).unwrap();
assert_eq!(zoned.zone_minutes(), Ok(60));
}
#[test]
fn needs_a_target_and_reads_the_choice_of_family() {
let none = Overrides::default();
assert_eq!(
Profile::resolve(&Configuration::default(), &none),
Err(Error::Missing("target"))
);
let profile = configured("word-win", r#"{"fonts":{"use":{"Calibri":"Carlito"}}}"#).unwrap();
assert_eq!(
profile.used_families().collect::<Vec<_>>(),
[("Calibri", "Carlito")]
);
}
#[test]
fn takes_the_targets_own_profile_for_its_defaults() {
for target in Target::all() {
let own = Profile::resolve(&Configuration::of(target), &Overrides::default()).unwrap();
assert_eq!(own, Profile::of(target).unwrap(), "{target}");
assert_eq!(own.configuration(), &Configuration::of(target), "{target}");
}
}