use f_office_units::Length;
use f_office_fonts::FamilyName;
use f_office_paint::{Join, Outline, Rgb};
use super::{
Edges, MathRoom, ScriptMove, ScriptScale, SpaceKind, SymbolFont, outline, size_and_rise,
symbol_stand_in,
};
use crate::character_class::CharacterClass;
use crate::props::{
Limit, MathScript, MathStep, OutlineColor, RunProps, TextOutline, VerticalAlign,
};
use crate::quirks::{
DisplayFractionRoom, LineHeight, MirroredBracketText, ScriptRoom, ShapedGlyphText, SymbolText,
};
fn per_inch(dots: i64) -> crate::grid::Dot {
crate::grid::Device::per_inch(dots).unwrap().dot_size()
}
fn math_size_and_rise(
props: &RunProps,
script: MathScript,
dot: crate::grid::Dot,
) -> (Length, Length, bool) {
super::math_size_and_rise(props, script, dot, &|_, _| None, &|_, _| None)
}
fn plain_face(metrics: crate::FaceMetrics, size: Length, line_height: LineHeight) -> super::Face {
super::Face {
font: f_office_fonts::FontId::from_index(0),
metrics,
size,
line_size: size,
single_line: super::SingleLine::of(line_height),
color: Rgb::BLACK,
lines: super::RunLines::default(),
background: None,
rise: Length::ZERO,
raised: Length::ZERO,
math: crate::text::MathFace::default(),
outline: None,
text_fill: super::DrawnTextFill::Solid,
effect: false,
shadow_room: super::ShadowRoom::default(),
shadow: None,
glow: None,
reflection: None,
relief: None,
kerned: false,
east_asian_script: None,
ligatures: false,
scale: None,
border: super::face::RunBorder::None,
standing: super::Standing::default(),
}
}
struct Joining;
impl crate::Fonts for Joining {
fn face(&self, _family: &FamilyName, bold: bool, _italic: bool) -> Option<crate::ChosenFace> {
Some(crate::ChosenFace {
font: f_office_fonts::FontId::from_index(0),
metrics: crate::FaceMetrics {
units_per_em: 1000,
hhea_ascender: 800,
hhea_descender: -200,
hhea_line_gap: 0,
descent: 200,
underline_position: -100,
underline_thickness: 50,
strikeout_position: 250,
strikeout_thickness: 50,
superscript_offset: 0,
subscript_offset: 0,
superscript_size: 0,
subscript_size: 0,
line_top: 800,
script_top: 800,
east_asian: false,
average_width: 500,
target_units_per_em: None,
},
synthetic_bold: bold,
synthetic_italic: false,
stands_in: false,
})
}
fn glyph(&self, _font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Some(u32::from(ch))
}
fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Some(if glyph == 500 { 150 } else { 100 })
}
fn kerning(
&self,
_font: f_office_fonts::FontId,
left: u32,
right: u32,
_table: crate::KerningTable,
) -> i32 {
match (left, char::from_u32(right)) {
(500, Some('x')) => -20,
(102, Some('i')) => -999,
_ => 0,
}
}
fn ligatures(
&self,
_font: f_office_fonts::FontId,
glyphs: &[u32],
) -> Vec<f_office_fonts::Ligature> {
glyphs
.windows(2)
.enumerate()
.filter(|(_, pair)| pair == &[102, 105])
.map(|(start, _)| f_office_fonts::Ligature {
start,
len: 2,
glyph: 500,
})
.collect()
}
}
struct Only(&'static [&'static str]);
impl crate::Fonts for Only {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
let index = self.0.iter().position(|name| family.is(name))?;
let font = f_office_fonts::FontId::from_index(u32::try_from(index).ok()?);
Joining
.face(family, bold, italic)
.map(|chosen| crate::ChosenFace { font, ..chosen })
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
let index = usize::try_from(font.index()).ok()?;
self.0.get(index).map(|name| (*name).to_owned())
}
}
fn chosen(fonts: &Only, theme: &crate::styles::Theme, name: Option<&str>) -> u32 {
use crate::props::FontRef;
let table = crate::styles::FontTable::default();
let props = RunProps {
font_ascii: name.map(|name| match name {
"+minor" => FontRef::MinorLatin,
name => FontRef::Name(name.into()),
}),
..RunProps::default()
};
let mut shaper = super::Shaper::new(fonts, theme, &table, &super::ShaperSettings::base());
let face = shaper.face(&props, true).unwrap();
shaper.faces[face.0].font.index()
}
#[test]
fn only_fonts_measure_like_joining_fonts() {
use crate::Fonts as _;
let fonts = Only(&["Cambria"]);
let font = f_office_fonts::FontId::from_index(0);
assert!(
fonts
.face(&FamilyName::from_static("Missing"), false, false)
.is_none()
);
assert_eq!(fonts.glyph(font, 'a'), Some(97));
assert_eq!(fonts.advance(font, 97), Some(100));
}
struct Shaping;
impl crate::Fonts for Shaping {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
match ch {
'\u{FEFB}' => Some(900),
'\u{06CC}' => Some(u32::from('\u{064A}')),
_ => Joining.glyph(font, ch),
}
}
fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Some(if glyph == 900 { 300 } else { 100 })
}
fn kerning(
&self,
_font: f_office_fonts::FontId,
_left: u32,
_right: u32,
_table: crate::KerningTable,
) -> i32 {
-30
}
fn shape(
&self,
_font: f_office_fonts::FontId,
request: &f_office_fonts::ShapeRequest<'_>,
) -> Result<Vec<f_office_fonts::ShapedGlyph>, f_office_fonts::ShapeFailure> {
let shaped = |glyph, advance, offset, cluster| f_office_fonts::ShapedGlyph {
glyph,
advance,
offset,
cluster,
};
let mut glyphs = Vec::new();
let mut chars = request.text.char_indices().peekable();
while let Some((at, ch)) = chars.next() {
match ch {
'ل' if chars.next_if(|&(_, next)| next == 'ا').is_some() => {
glyphs.push(shaped(900, 300, (0, 0), at));
}
'ل' if chars.next_if(|&(_, next)| next == 'م').is_some() => {
glyphs.push(shaped(902, 90, (0, 0), at));
}
'\u{064E}' => {
let base = glyphs.last().map_or(at, |g| g.cluster);
glyphs.push(shaped(901, 0, (40, 120), base));
}
'\u{06CC}' => glyphs.push(shaped(u32::from('\u{064A}'), 90, (0, 0), at)),
' ' => glyphs.push(shaped(u32::from(' '), 100, (0, 0), at)),
_ => glyphs.push(shaped(u32::from(ch), 90, (0, 0), at)),
}
}
Ok(glyphs)
}
}
#[test]
fn mirrors_brackets_in_right_to_left_runs() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let text = |rtl, complex| {
let props = RunProps {
complex,
rtl,
..RunProps::default()
};
let mut shaper =
super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "(a) [\u{AB}]", &mut glyphs);
glyphs.iter().map(|g| g.ch).collect::<String>()
};
assert_eq!(text(Some(true), None), ")a( ]\u{BB}[");
assert_eq!(text(None, None), "(a) [\u{AB}]");
assert_eq!(text(None, Some(true)), "(a) [\u{AB}]");
}
#[test]
fn writes_the_character_of_the_file_for_a_mirrored_bracket_when_the_quirk_says_so() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let glyphs = |rtl, written| {
let props = RunProps {
rtl,
..RunProps::default()
};
let mut shaper = super::Shaper::new(
&Joining,
&theme,
&table,
&super::ShaperSettings::base_with(|p| p.with_variant(written)),
);
let mut glyphs = Vec::new();
shaper.measure(&props, "(a] {7\u{BB}", &mut glyphs);
glyphs
};
let text = |glyphs: &[super::Glyph]| glyphs.iter().map(|g| g.ch).collect::<String>();
let as_in_file = glyphs(Some(true), MirroredBracketText::AsInFile);
let mirrored = glyphs(Some(true), MirroredBracketText::Mirrored);
assert_eq!(text(&as_in_file), "(a] {7\u{BB}");
assert_eq!(text(&mirrored), ")a[ }7\u{AB}");
let drawn = |glyphs: &[super::Glyph]| glyphs.iter().map(|g| g.id).collect::<Vec<_>>();
assert_eq!(drawn(&as_in_file), drawn(&mirrored));
let plain = glyphs(None, MirroredBracketText::AsInFile);
assert_eq!(text(&plain), "(a] {7\u{BB}");
assert_ne!(drawn(&plain), drawn(&as_in_file));
}
#[test]
fn gives_unit_brackets_a_mirrored_glyph_by_the_east_asian_font() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mirrors = |east_asian: Option<&str>, rtl, text: &str| {
let props = RunProps {
rtl,
font_east_asia: east_asian
.map(|name| Box::new(crate::props::FontRef::Name(name.into()))),
..RunProps::default()
};
let mut shaper = super::Shaper::new(
&Joining,
&theme,
&table,
&super::ShaperSettings::base_with(|p| p.with_variant(MirroredBracketText::AsInFile)),
);
let mut glyphs = Vec::new();
shaper.measure(&props, text, &mut glyphs);
let id_of = |ch| glyphs.iter().find(|g| g.ch == ch).map(|g| g.id);
glyphs
.iter()
.filter(|g| matches!(g.ch, '(' | ')'))
.map(|g| {
g.unit_mirror.map(|m| {
let other = if g.ch == '(' { ')' } else { '(' };
(m.ch, Some(m.id) == id_of(other))
})
})
.collect::<Vec<_>>()
};
let mirrored = [Some(('(', true)), Some((')', true))];
let none = [None, None];
assert_eq!(mirrors(None, None, "\u{0628} (7)"), mirrored);
assert_eq!(
mirrors(Some("Times New Roman"), None, "\u{0628} (7)"),
mirrored
);
assert_eq!(
mirrors(Some("times new roman"), None, "(7) \u{05D0}"),
mirrored
);
assert_eq!(mirrors(Some("Arial"), None, "\u{0628} (7)"), none);
assert_eq!(mirrors(Some("Missing Face"), None, "\u{0628} (7)"), none);
assert_eq!(mirrors(None, None, "a (7)"), none);
assert_eq!(mirrors(None, Some(true), "\u{0628} (7)"), none);
}
#[test]
fn takes_the_direction_of_a_computed_page_number_from_the_reader_of_fields() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let direction = |rtl, field_rtl| {
let props = RunProps {
rtl,
field_rtl,
..RunProps::default()
};
let mut shaper =
super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "7", &mut glyphs);
glyphs.first().map(|g| g.direction)
};
let left = Some(super::RunDirection::LeftToRight);
let unicode = crate::props::BidiLanguageClass::Unicode;
let computed = Some(super::RunDirection::of(true, Some(unicode)));
assert_eq!(direction(None, Some(true)), computed);
assert_eq!(direction(Some(true), Some(false)), left);
let right = Some(super::RunDirection::of(true, None));
assert_eq!(direction(Some(true), None), right);
assert_eq!(direction(None, None), left);
}
type ShapedRow = (char, u32, i64, bool, (i64, i64));
fn shaped_run(fonts: &dyn crate::Fonts, text: &str) -> Vec<ShapedRow> {
shaped_run_with(fonts, text, &super::ShaperSettings::base())
}
fn shaped_run_with(
fonts: &dyn crate::Fonts,
text: &str,
settings: &super::ShaperSettings,
) -> Vec<ShapedRow> {
let props = RunProps {
size: Some(20),
size_cs: Some(20),
kern: Some(2),
..RunProps::default()
};
shaped_run_of(fonts, &props, text, settings)
}
fn shaped_run_of(
fonts: &dyn crate::Fonts,
props: &RunProps,
text: &str,
settings: &super::ShaperSettings,
) -> Vec<ShapedRow> {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let twentieths = |length: Length| length.units() / Length::UNITS_PER_TWIP;
let mut shaper = super::Shaper::new(fonts, &theme, &table, settings);
let mut glyphs = Vec::new();
shaper.measure(props, text, &mut glyphs);
glyphs
.iter()
.map(|g| {
let offset = (twentieths(g.offset.0), twentieths(g.offset.1));
(g.ch, g.id, twentieths(g.advance), g.part, offset)
})
.collect()
}
#[test]
fn a_stretch_of_a_shaped_script_takes_the_glyphs_of_the_layout_tables() {
let glyphs = shaped_run(&Shaping, "بلا ب\u{064E}");
assert_eq!(
glyphs,
[
('ب', u32::from('ب'), 18, false, (0, 0)),
('\u{FEFB}', 900, 60, false, (0, 0)),
(' ', u32::from(' '), 20, false, (0, 0)),
('ب', u32::from('ب'), 18, false, (0, 0)),
('\u{064E}', 901, 0, false, (8, 24)),
]
);
}
#[test]
fn arabic_space_and_punctuation_stay_in_the_arabic_stretch_when_sharing_its_face() {
struct ArabicSpaceKern;
impl crate::Fonts for ArabicSpaceKern {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, _font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Some(if ch == '\u{061C}' {
u32::from(' ')
} else {
u32::from(ch)
})
}
fn advance(&self, _font: f_office_fonts::FontId, _glyph: u32) -> Option<u16> {
Some(100)
}
fn shape(
&self,
_font: f_office_fonts::FontId,
request: &f_office_fonts::ShapeRequest<'_>,
) -> Result<Vec<f_office_fonts::ShapedGlyph>, f_office_fonts::ShapeFailure> {
let chars: Vec<(usize, char)> = request.text.char_indices().collect();
let mut out = Vec::with_capacity(chars.len());
for (i, &(at, ch)) in chars.iter().enumerate() {
let next = chars.get(i + 1).map(|&(_, c)| c);
let (adv, xoff) = match (ch, next) {
('و', Some(' ' | '.')) => (80, -20),
(' ', Some('ك')) => (70, -30),
_ => (100, 0),
};
out.push(f_office_fonts::ShapedGlyph {
glyph: u32::from(ch),
advance: adv,
offset: (xoff, 0),
cluster: at,
});
}
Ok(out)
}
}
let glyphs = shaped_run(&ArabicSpaceKern, "أو كتب");
assert_eq!(
glyphs,
[
('أ', u32::from('أ'), 20, false, (0, 0)),
('و', u32::from('و'), 16, false, (-4, 0)),
(' ', u32::from(' '), 14, false, (-6, 0)),
('ك', u32::from('ك'), 20, false, (0, 0)),
('ت', u32::from('ت'), 20, false, (0, 0)),
('ب', u32::from('ب'), 20, false, (0, 0)),
]
);
let punct = shaped_run(&ArabicSpaceKern, "أو.الم");
assert_eq!(punct[1], ('و', u32::from('و'), 16, false, (-4, 0)));
assert_eq!(punct[2], ('.', u32::from('.'), 20, false, (0, 0)));
let diff_fonts = Only(&["Latin", "Complex"]);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Latin".into())),
font_hansi: Some(crate::props::FontRef::Name("Latin".into())),
font_cs: Some(Box::new(crate::props::FontRef::Name("Complex".into()))),
..RunProps::default()
};
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper =
super::Shaper::new(&diff_fonts, &theme, &table, &super::ShaperSettings::base());
let mut mixed = Vec::new();
shaper.measure(&props, "أو الم", &mut mixed);
assert_eq!(
mixed
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>(),
[0, 0, 0, 0, 0, 0]
);
let rtl_props = RunProps {
rtl: Some(true),
..props
};
let mut rtl_mixed = Vec::new();
shaper.measure(&rtl_props, "أو الم", &mut rtl_mixed);
assert_eq!(
rtl_mixed
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>(),
[1, 1, 1, 1, 1, 1]
);
}
#[test]
fn a_shaped_glyph_writes_the_lowest_character_that_the_font_maps_to_it() {
let glyphs = shaped_run(&Shaping, "\u{06CC}لم");
assert_eq!(
glyphs,
[
('\u{064A}', u32::from('\u{064A}'), 18, false, (0, 0)),
('ل', 902, 18, false, (0, 0)),
('م', u32::from('م'), 0, true, (0, 0)),
]
);
}
#[test]
fn a_shaped_glyph_writes_the_letters_of_the_document_when_the_quirk_says_so() {
let text = "\u{0644}\u{0627}\u{06CC}";
let letters = shaped_run_with(
&Shaping,
text,
&super::ShaperSettings::base_with(|p| p.with_variant(ShapedGlyphText::ClusterLetters)),
);
let lowest = shaped_run_with(
&Shaping,
text,
&super::ShaperSettings::base_with(|p| {
p.with_variant(ShapedGlyphText::LowestMappedCharacter)
}),
);
assert_eq!(
letters,
[
('\u{0644}', 900, 60, false, (0, 0)),
('\u{0627}', u32::from('\u{0627}'), 0, true, (0, 0)),
('\u{06CC}', u32::from('\u{064A}'), 18, false, (0, 0)),
]
);
assert_eq!(
lowest,
[
('\u{FEFB}', 900, 60, false, (0, 0)),
('\u{064A}', u32::from('\u{064A}'), 18, false, (0, 0)),
]
);
}
#[test]
fn a_part_of_a_ligature_takes_no_character_spacing() {
let props = RunProps {
size: Some(20),
size_cs: Some(20),
spacing: Some(Length::from_units(-4 * Length::UNITS_PER_TWIP)),
..RunProps::default()
};
let settings =
super::ShaperSettings::base_with(|p| p.with_variant(ShapedGlyphText::ClusterLetters));
assert_eq!(
shaped_run_of(&Shaping, &props, "\u{0644}\u{0627}\u{064A}", &settings),
[
('\u{0644}', 900, 56, false, (0, 0)),
('\u{0627}', u32::from('\u{0627}'), 0, true, (0, 0)),
('\u{064A}', u32::from('\u{064A}'), 14, false, (0, 0)),
]
);
}
#[test]
fn measures_a_text_of_many_shaped_words_with_one_look_at_a_stretch_for_each_character() {
const WORDS: usize = 20_000;
let text = "بب ".repeat(WORDS);
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Shaping, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
super::STRETCH_LOOKS.with(|looks| looks.set(0));
shaper.measure(&RunProps::default(), &text, &mut glyphs);
let looks = super::STRETCH_LOOKS.with(std::cell::Cell::get);
assert!(looks <= 3 * WORDS, "{looks} looks");
let ids: Vec<u32> = glyphs.iter().map(|g| g.id).collect();
let word = [u32::from('ب'), u32::from('ب'), u32::from(' ')];
assert_eq!(ids, word.repeat(WORDS));
let advances: std::collections::BTreeSet<Length> = glyphs
.iter()
.filter(|g| g.id == u32::from('ب'))
.map(|g| g.advance)
.collect();
assert_eq!(advances.len(), 1);
}
#[test]
fn a_caller_without_a_shaper_draws_the_characters_and_the_shaper_keeps_the_cause() {
let glyphs = shaped_run(&Joining, "بلا");
let ids: Vec<u32> = glyphs.iter().map(|g| g.1).collect();
assert_eq!(ids, "بلا".chars().map(u32::from).collect::<Vec<_>>());
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
shaper.measure(&RunProps::default(), "ب", &mut Vec::new());
let notes = shaper.take_notes();
let causes: Vec<_> = notes.unshaped.iter().map(|&(_, c)| c).collect();
assert_eq!(causes, [f_office_fonts::ShapeFailure::NoShaper]);
assert_eq!(shaper.take_notes(), super::FontNotes::default());
}
#[test]
fn a_fork_starts_with_no_notes_and_gives_its_own_back() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
shaper.measure(&RunProps::default(), "ب", &mut Vec::new());
let mut fork = shaper.fork();
assert_eq!(fork.take_notes(), super::FontNotes::default());
fork.measure(&RunProps::default(), "ب", &mut Vec::new());
let own = shaper.take_notes();
shaper.add_notes(own.clone());
shaper.add_notes(fork.take_notes());
assert_eq!(shaper.take_notes(), own);
}
#[test]
fn draws_complex_script_characters_with_the_complex_script_font() {
use crate::props::FontRef;
let fonts = Only(&["Latin", "Complex"]);
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let props = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_hansi: Some(FontRef::Name("Latin".into())),
font_cs: Some(Box::new(FontRef::Name("Complex".into()))),
..RunProps::default()
};
let fonts_of = |props: &RunProps, text: &str| {
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(props, text, &mut glyphs);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>()
};
assert_eq!(fonts_of(&props, "a \u{05D0}\u{0628}"), [0, 0, 0, 0]);
let east_asian = RunProps {
font_east_asia: Some(Box::new(FontRef::Name("Complex".into()))),
..props.clone()
};
assert_eq!(
fonts_of(&east_asian, "a\u{4E2D}\u{3042}\u{AC00}"),
[0, 1, 1, 1]
);
assert_eq!(fonts_of(&props, "a\u{4E2D}"), [0, 0]);
let cs = RunProps {
complex: Some(true),
..props.clone()
};
assert_eq!(fonts_of(&cs, "a \u{05D0}"), [1, 1, 1]);
let rtl = RunProps {
rtl: Some(true),
..props
};
assert_eq!(fonts_of(&rtl, "a \u{05D0}\u{0628}"), [1, 1, 1, 1]);
}
struct LatinFirst(&'static [&'static str]);
impl crate::Fonts for LatinFirst {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Only(self.0).face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
if font.index() == 0 && CharacterClass::EastAsianFont.contains(ch) {
return None;
}
Only(self.0).glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Only(self.0).advance(font, glyph)
}
}
#[test]
fn draws_east_asian_glyphs_that_the_font_lacks_with_the_fallback_fonts() {
use crate::props::FontRef;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let latin = Some(FontRef::Name("Latin".into()));
let props = RunProps {
font_ascii: latin.clone(),
font_east_asia: latin.map(Box::new),
..RunProps::default()
};
let drawn = |fonts: &LatinFirst| {
let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "a\u{4E2D}", &mut glyphs);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>()
};
let all = LatinFirst(&["Latin", "Microsoft JhengHei", "MS Mincho"]);
assert_eq!(drawn(&all), [0, 2]);
assert_eq!(drawn(&LatinFirst(&["Latin", "Microsoft JhengHei"])), [0, 1]);
}
#[test]
fn draws_east_asian_text_of_a_missing_font_with_microsoft_yahei() {
use crate::props::FontRef;
let fonts = Only(&["Latin", "Microsoft YaHei"]);
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let props = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_east_asia: Some(Box::new(FontRef::Name("Missing".into()))),
..RunProps::default()
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "a\u{4E2D}", &mut glyphs);
let drawn: Vec<u32> = glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect();
assert_eq!(drawn, [0, 1]);
}
#[test]
fn draws_a_missing_font_with_the_font_of_its_east_asian_character_set() {
use crate::props::FontRef;
let fonts = Only(&[
"Latin",
"Microsoft YaHei",
"Microsoft JhengHei",
"Yu Gothic",
"Malgun Gothic",
]);
let xml = format!(
r#"<w:fonts xmlns:w="{}"><w:font w:name="Big5"><w:charset w:val="88"/></w:font><w:font w:name="標楷體"><w:charset w:val="88"/></w:font><w:font w:name="GB"><w:charset w:val="86"/></w:font><w:font w:name="JIS"><w:charset w:val="80"/></w:font><w:font w:name="Hangul"><w:charset w:val="81"/></w:font><w:font w:name="Ansi"><w:charset w:val="00"/></w:font></w:fonts>"#,
crate::ns::W
);
let doc =
f_office_xml::Document::parse(xml.as_bytes(), &f_office_xml::Limits::default()).unwrap();
let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
let theme = crate::styles::Theme::default();
let drawn = |name: &str| {
let props = RunProps {
font_ascii: Some(FontRef::Name(name.into())),
font_east_asia: Some(Box::new(FontRef::Name(name.into()))),
..RunProps::default()
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "a\u{4E2D}", &mut glyphs);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<u32>>()
};
assert_eq!(drawn("Big5"), [2, 2]);
assert_eq!(drawn("標楷體"), [1, 1]);
assert_eq!(drawn("GB"), [1, 1]);
assert_eq!(drawn("JIS"), [3, 3]);
assert_eq!(drawn("Hangul"), [4, 4]);
assert_eq!(drawn("Ansi").last(), Some(&1));
}
#[test]
fn draws_shared_punctuation_with_the_east_asian_font_only_with_the_east_asian_hint() {
use crate::props::FontRef;
let fonts = Only(&["Latin", "East"]);
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let drawn = |hint: Option<bool>| {
let props = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_hansi: Some(FontRef::Name("Latin".into())),
font_east_asia: Some(Box::new(FontRef::Name("East".into()))),
east_asian_hint: hint,
..RunProps::default()
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(
&props,
"A \u{2018}B\u{2019}\u{203B}\u{2026}\u{2014}\u{00B7}",
&mut glyphs,
);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<u32>>()
};
assert_eq!(drawn(Some(true)), [0, 0, 1, 0, 1, 1, 1, 1, 1]);
assert_eq!(drawn(Some(false)), [0; 9]);
assert_eq!(drawn(None), [0; 9]);
}
#[test]
fn draws_hinted_symbols_with_the_east_asian_font_unless_it_is_times_new_roman() {
use crate::props::FontRef;
use crate::quirks::HintedSlot;
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let drawn = |families: &'static [&'static str], variant| {
let fonts = Only(families);
let props = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_hansi: Some(FontRef::Name("Latin".into())),
font_east_asia: Some(Box::new(FontRef::Name(families[1].into()))),
east_asian_hint: Some(true),
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(
&props,
"A\u{03C9}\u{0416}\u{2191}\u{2502} \u{2014}",
&mut glyphs,
);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<u32>>()
};
assert_eq!(
drawn(&["Latin", "East"], HintedSlot::Symbols),
[0, 1, 1, 1, 1, 0, 1]
);
assert_eq!(
drawn(&["Latin", "East"], HintedSlot::Punctuation),
[0, 0, 0, 0, 0, 0, 1]
);
assert_eq!(
drawn(&["Latin", "Times New Roman"], HintedSlot::Symbols),
[0; 7]
);
}
#[test]
fn draws_complex_script_text_of_a_missing_font_with_the_font_of_the_quirk() {
use crate::ns::W;
use crate::props::FontRef;
use crate::quirks::MissingComplexFont::{self, Arial, ByFontTable};
use f_office_xml::{Document, Limits};
let fonts = Only(&[
"Latin",
"Arial",
"Calibri",
"Times New Roman",
"Sakkal Majalla",
]);
let theme = crate::styles::Theme {
latin: crate::styles::MinorMajor {
minor: Some("Calibri".into()),
major: None,
},
..crate::styles::Theme::default()
};
let long = "A Missing Font Name Of 32 Chars.";
assert_eq!(long.len(), 32);
let entries = [
(
"Hebrew Swiss",
r#"<w:charset w:val="B1"/><w:family w:val="swiss"/>"#,
),
(
"Arabic Roman",
r#"<w:charset w:val="B2"/><w:family w:val="roman"/>"#,
),
(
"Paged Roman",
r#"<w:charset w:val="00"/><w:family w:val="roman"/><w:sig w:usb0="00002001" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000041" w:csb1="00000000"/>"#,
),
(
"Paged Auto",
r#"<w:charset w:val="00"/><w:family w:val="auto"/><w:sig w:usb0="00002001" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000041" w:csb1="00000000"/>"#,
),
(
"Ranged Auto",
r#"<w:charset w:val="00"/><w:family w:val="auto"/><w:sig w:usb0="00002001" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000"/>"#,
),
(
"Plain Roman",
r#"<w:charset w:val="00"/><w:family w:val="roman"/>"#,
),
(long, r#"<w:charset w:val="B2"/><w:family w:val="swiss"/>"#),
];
let table = entries
.iter()
.fold(String::new(), |mut table, (name, parts)| {
table.push_str(r#"<w:font w:name=""#);
table.push_str(name);
table.push_str(r#"">"#);
table.push_str(parts);
table.push_str("</w:font>");
table
});
let xml = format!(r#"<w:fonts xmlns:w="{W}">{table}</w:fonts>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
let drawn = |quirk: MissingComplexFont, complex: &str| {
let latin = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_cs: Some(Box::new(FontRef::Name(complex.into()))),
..RunProps::default()
};
let rtl = RunProps {
rtl: Some(true),
..latin.clone()
};
let settings = super::ShaperSettings::base_with(|p| p.with_variant(quirk));
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&latin, "a", &mut glyphs);
shaper.measure(&rtl, "\u{05D0}", &mut glyphs);
let faces: Vec<u32> = glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect();
(faces.first().copied(), faces.last().copied())
};
let cases = [
("Missing", 3),
("Hebrew Swiss", 1),
("Arabic Roman", 4),
("Paged Roman", 4),
("Paged Auto", 1),
("Ranged Auto", 2),
("Plain Roman", 3),
(long, 3),
];
for (missing, face) in cases {
assert_eq!(drawn(Arial, missing), (Some(0), Some(1)), "{missing}");
assert_eq!(
drawn(ByFontTable, missing),
(Some(0), Some(face)),
"{missing}"
);
}
}
struct Substituting;
impl crate::Fonts for Substituting {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Only(&["Named", "Arial", "Calibri", "Times New Roman"]).face(family, bold, italic)
}
fn substitute(
&self,
_family: &FamilyName,
_bold: bool,
_italic: bool,
) -> Option<crate::ChosenFace> {
None
}
fn family_substitute(
&self,
family: &FamilyName,
bold: bool,
italic: bool,
) -> Option<crate::ChosenFace> {
if !family.is("Other") {
return None;
}
let chosen = self.face(&FamilyName::from_static("Named"), bold, italic)?;
Some(crate::ChosenFace {
font: f_office_fonts::FontId::from_index(9),
..chosen
})
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
}
#[test]
fn draws_complex_script_text_of_a_missing_family_with_its_substitute_first() {
use crate::props::FontRef;
use crate::quirks::MissingComplexFont::{Arial, ByFontTable};
let table = crate::styles::FontTable::default();
let theme = crate::styles::Theme::default();
let drawn = |quirk, text: &str| {
let props = RunProps {
font_ascii: Some(FontRef::Name("Other".into())),
font_cs: Some(Box::new(FontRef::Name("Other".into()))),
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| p.with_variant(quirk));
let mut shaper = super::Shaper::new(&Substituting, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&props, text, &mut glyphs);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<u32>>()
};
for quirk in [Arial, ByFontTable] {
assert_eq!(drawn(quirk, "\u{05D0}"), [9], "{quirk:?}");
assert_eq!(drawn(quirk, "a"), [9], "{quirk:?}");
}
}
#[test]
fn draws_the_digits_of_a_right_to_left_run_with_its_ascii_font() {
use crate::props::FontRef;
let fonts = Only(&["Latin", "Arial", "Calibri"]);
let theme = crate::styles::Theme {
latin: crate::styles::MinorMajor {
minor: Some("Calibri".into()),
major: None,
},
..crate::styles::Theme::default()
};
let table = crate::styles::FontTable::default();
let drawn = |ascii: &str, (rtl, complex): (bool, bool), text: &str| {
let props = RunProps {
font_ascii: Some(FontRef::Name(ascii.into())),
font_cs: Some(Box::new(FontRef::Name("Missing".into()))),
rtl: rtl.then_some(true),
complex: complex.then_some(true),
..RunProps::default()
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, text, &mut glyphs);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>()
};
assert_eq!(drawn("Latin", (true, false), "\u{05D0}1-2"), [1, 0, 1, 0]);
assert_eq!(drawn("Latin", (true, true), "\u{05D0}1-2"), [1, 0, 1, 0]);
assert_eq!(
drawn("Latin", (true, false), "5.0,6:1."),
[0, 0, 0, 0, 0, 0, 0, 1]
);
assert_eq!(drawn("Latin", (true, false), ".5 :"), [1, 0, 1, 1]);
assert_eq!(drawn("Latin", (false, true), "\u{05D0}1.2"), [1, 1, 1, 1]);
assert_eq!(drawn("Gone", (true, false), "\u{05D0}1-2"), [1, 1, 1, 1]);
}
#[test]
fn draws_the_digits_of_a_hebrew_right_to_left_run_with_its_complex_script_font() {
use crate::props::{BidiScript, FontRef};
let fonts = Only(&["Latin", "Arial"]);
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let drawn = |language: &str| {
let props = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_cs: Some(Box::new(FontRef::Name("Arial".into()))),
rtl: Some(true),
bidi_script: Some(BidiScript::of(language)),
..RunProps::default()
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "\u{05D0}1.2", &mut glyphs);
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>()
};
assert_eq!(drawn("fa-IR"), [1, 0, 0, 0]);
assert_eq!(drawn("ar-SA"), [1, 0, 0, 0]);
assert_eq!(drawn("he-IL"), [1, 1, 1, 1]);
assert_eq!(drawn("HE"), [1, 1, 1, 1]);
}
#[test]
fn draws_the_digits_of_a_right_to_left_run_at_the_complex_script_size_and_bold() {
use crate::props::FontRef;
let fonts = Only(&["Latin", "Arial"]);
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let props = RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_cs: Some(Box::new(FontRef::Name("Arial".into()))),
size: Some(28),
size_cs: Some(18),
bold: Some(true),
rtl: Some(true),
..RunProps::default()
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "5", &mut glyphs);
let face = &shaper.faces[glyphs[0].face.0];
assert_eq!(face.font.index(), 0);
assert_eq!(Some(face.size), Length::from_points(9));
let plain = glyphs[0].face;
glyphs.clear();
let bold = RunProps {
bold: None,
bold_cs: Some(true),
..props
};
shaper.measure(&bold, "5", &mut glyphs);
assert_ne!(glyphs[0].face, plain);
}
#[test]
fn draws_a_missing_font_with_cambria_only_in_a_document_without_a_theme() {
use crate::styles::Theme;
let fonts = Only(&["Times New Roman", "Cambria", "Carlito"]);
let font = |theme: &Theme, name: Option<&str>| chosen(&fonts, theme, name);
let none = Theme::default();
assert_eq!(font(&none, Some("Missing")), 1);
assert_eq!(font(&none, Some("\"Calibri\", Arial, sans-serif")), 1);
assert_eq!(font(&none, Some("Times New Roman")), 0);
assert_eq!(font(&none, None), 0);
assert_eq!(font(&none, Some("+minor")), 0);
}
struct Standing;
impl crate::Fonts for Standing {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Only(&["Named", "Yu Gothic"]).face(family, bold, italic)
}
fn substitute(
&self,
family: &FamilyName,
bold: bool,
italic: bool,
) -> Option<crate::ChosenFace> {
let chosen = self.face(family, bold, italic)?;
let font = f_office_fonts::FontId::from_index(1);
Some(crate::ChosenFace { font, ..chosen })
}
fn family_substitute(
&self,
family: &FamilyName,
bold: bool,
italic: bool,
) -> Option<crate::ChosenFace> {
if !["Other", "Missing", "CharsetMissing"]
.iter()
.any(|name| family.is(name))
{
return None;
}
let chosen = self.face(&FamilyName::from_static("Named"), bold, italic)?;
Some(crate::ChosenFace {
font: f_office_fonts::FontId::from_index(2),
..chosen
})
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
}
#[test]
fn takes_a_substitute_for_the_first_font_of_a_list_and_for_an_alternate_name() {
use crate::ns::W;
use crate::props::FontRef;
use f_office_xml::{Document, Limits};
let xml = format!(
r#"<w:fonts xmlns:w="{W}"><w:font w:name="Other"><w:altName w:val="Named"/></w:font><w:font w:name="CharsetMissing"><w:charset w:val="80"/></w:font></w:fonts>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
let theme = crate::styles::Theme::default();
let font = |name: &str| {
let props = RunProps {
font_ascii: Some(FontRef::Name(name.into())),
..RunProps::default()
};
let mut shaper =
super::Shaper::new(&Standing, &theme, &table, &super::ShaperSettings::base());
let face = shaper.face(&props, true).unwrap();
shaper.faces[face.0].font.index()
};
assert_eq!(font("Named"), 0);
assert_eq!(font("Named, Arial, sans-serif"), 1);
assert_eq!(font("Other"), 1);
assert_eq!(font("Missing"), 2);
assert_eq!(font("CharsetMissing"), 1);
}
#[test]
fn keeps_times_new_roman_for_text_without_a_font_also_with_a_theme() {
let fonts = Only(&["Times New Roman", "Cambria", "Carlito", "Calibri"]);
let themed = crate::styles::Theme {
latin: crate::styles::MinorMajor {
minor: Some("Carlito".into()),
major: None,
},
..crate::styles::Theme::default()
};
let font = |name: Option<&str>| chosen(&fonts, &themed, name);
assert_eq!(font(None), 0);
assert_eq!(font(Some("+minor")), 2);
}
#[test]
fn draws_a_missing_font_with_calibri_in_a_document_with_a_theme() {
let fonts = Only(&["Times New Roman", "Cambria", "Carlito", "Calibri"]);
let theme = |minor: &str| crate::styles::Theme {
latin: crate::styles::MinorMajor {
minor: Some(minor.into()),
major: None,
},
..crate::styles::Theme::default()
};
assert_eq!(chosen(&fonts, &theme("Cambria"), Some("Missing")), 3);
assert_eq!(chosen(&fonts, &theme("Missing"), Some("Missing")), 3);
let without = Only(&["Times New Roman", "Cambria"]);
assert_eq!(chosen(&without, &theme("Cambria"), Some("Missing")), 0);
}
fn fallback_face(fallback: crate::quirks::MissingFontFallback, themed: bool, name: &str) -> u32 {
use crate::ns::W;
use crate::props::FontRef;
use f_office_xml::{Document, Limits};
let fonts = Only(&["Times New Roman", "Cambria", "Carlito", "Calibri"]);
let xml = format!(
r#"<w:fonts xmlns:w="{W}"><w:font w:name="Roman"><w:family w:val="roman"/></w:font><w:font w:name="Swiss"><w:family w:val="swiss"/></w:font><w:font w:name="NoClass"><w:charset w:val="00"/></w:font></w:fonts>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
let theme = crate::styles::Theme {
latin: crate::styles::MinorMajor {
minor: themed.then(|| "Carlito".into()),
major: None,
},
..crate::styles::Theme::default()
};
let props = RunProps {
font_ascii: Some(FontRef::Name(name.into())),
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| p.with_variant(fallback));
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let face = shaper.face(&props, true).unwrap();
shaper.faces[face.0].font.index()
}
#[test]
fn draws_a_missing_font_by_its_font_table_entry_where_the_target_does() {
use crate::quirks::MissingFontFallback::ByFontTable;
for themed in [true, false] {
let faces = ["Absent", "Roman", "Swiss", "NoClass"]
.map(|name| fallback_face(ByFontTable, themed, name));
assert_eq!(faces, [1, 1, 3, 3]);
}
}
#[test]
fn draws_a_missing_font_by_the_theme_where_the_target_does() {
use crate::quirks::MissingFontFallback::ByTheme;
for name in ["Absent", "Roman", "Swiss"] {
assert_eq!(
[true, false].map(|themed| fallback_face(ByTheme, themed, name)),
[3, 1]
);
}
}
fn suffixed_faces(names: crate::quirks::SuffixedFontNames, name: &str, text: &str) -> Vec<u32> {
use crate::ns::W;
use crate::props::FontRef;
use f_office_xml::{Document, Limits};
let fonts = Only(&[
"Times New Roman",
"Cambria",
"Calibri",
"Arial",
"Cambria Math",
]);
let entry = |name: &str, charset: &str, alternate: &str| {
format!(
r#"<w:font w:name="{name}">{alternate}<w:charset w:val="{charset}"/><w:family w:val="roman"/></w:font>"#
)
};
let xml = format!(
r#"<w:fonts xmlns:w="{W}">{}{}{}{}</w:fonts>"#,
entry("Times New Roman CYR", "CC", ""),
entry("Missing CYR", "CC", ""),
entry("Times New Roman CE", "00", ""),
entry(
"Times New Roman Greek",
"CC",
r#"<w:altName w:val="Arial"/>"#
),
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
let theme = crate::styles::Theme::default();
let font = Some(FontRef::Name(name.into()));
let props = RunProps {
font_ascii: font.clone(),
font_hansi: font,
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::MissingFontFallback::ByFontTable)
.with_variant(names)
});
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&props, text, &mut glyphs);
glyphs
.iter()
.map(|glyph| shaper.faces[glyph.face.0].font.index())
.collect()
}
const SPLIT_TEXT: &str = "A\u{E9}\u{10D}\u{410}\u{2015}\u{2116}";
#[test]
fn splits_a_run_of_a_suffixed_font_name_whose_entry_gives_its_character_set() {
use crate::quirks::SuffixedFontNames::DrawBase;
assert_eq!(
suffixed_faces(DrawBase, "Times New Roman CYR", SPLIT_TEXT),
[0, 0, 2, 2, 3, 4]
);
assert_eq!(
suffixed_faces(DrawBase, "Times New Roman cyr", "A\u{410}"),
[0, 2]
);
}
#[test]
fn draws_a_suffixed_font_name_whole_with_its_family_without_that_entry() {
use crate::quirks::SuffixedFontNames::DrawBase;
assert_eq!(
suffixed_faces(DrawBase, "Times New Roman CE", SPLIT_TEXT),
[0; 6]
);
assert_eq!(
suffixed_faces(DrawBase, "Times New Roman TUR", SPLIT_TEXT),
[0; 6]
);
assert_eq!(suffixed_faces(DrawBase, "Missing CYR", SPLIT_TEXT), [1; 6]);
assert_eq!(
suffixed_faces(DrawBase, "Times New Roman Greek", SPLIT_TEXT),
[3; 6]
);
}
#[test]
fn draws_a_suffixed_font_name_as_a_missing_font_where_the_target_does_not() {
use crate::quirks::SuffixedFontNames::Missing;
for name in ["Times New Roman CYR", "Times New Roman TUR"] {
assert_eq!(suffixed_faces(Missing, name, SPLIT_TEXT), [1; 6], "{name}");
}
}
#[test]
fn a_ligature_takes_its_own_advance_and_kerns_with_the_glyph_after_it() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let settings = super::ShaperSettings {
ligatures: true,
..super::ShaperSettings::base()
};
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
let props = |ligatures| RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
ligatures,
kern: Some(2),
..RunProps::default()
};
let measured = |shaper: &mut super::Shaper<'_>, ligatures| {
let mut glyphs = Vec::new();
shaper.measure(&props(ligatures), "fix", &mut glyphs);
glyphs
.iter()
.map(|g| (g.id, g.advance.units(), g.part))
.collect::<Vec<_>>()
};
assert_eq!(
measured(&mut shaper, Some(true)),
[
(500, 150 * 254 - 20 * 254, false),
(105, 0, true),
(120, 25_400, false)
]
);
assert_eq!(
measured(&mut shaper, None),
[
(102, 25_400 - 999 * 254, false),
(105, 25_400, false),
(120, 25_400, false)
]
);
let mut glyphs = Vec::new();
shaper.measure(&props(None), "fix", &mut glyphs);
let written: Vec<Option<u16>> = glyphs.iter().map(|g| g.written).collect();
assert_eq!(written, [Some(100), None, None]);
let mut glyphs = Vec::new();
shaper.measure(&props(Some(true)), "fix", &mut glyphs);
assert_eq!(glyphs.first().map(|g| g.written), Some(Some(150)));
let spaced = RunProps {
spacing: Some(Length::from_units(-12_700)),
..props(Some(true))
};
let mut glyphs = Vec::new();
shaper.measure(&spaced, "fix", &mut glyphs);
let ids: Vec<u32> = glyphs.iter().map(|g| g.id).collect();
assert_eq!(ids, [102, 105, 120]);
}
#[test]
fn an_older_compatibility_mode_keeps_the_letters_apart() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let shaper = super::Shaper::new(
&Joining,
&theme,
&table,
&super::ShaperSettings {
ligatures: false,
..super::ShaperSettings::base()
},
);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
ligatures: Some(true),
..RunProps::default()
};
for mut shaper in [shaper.fork(), shaper] {
let mut glyphs = Vec::new();
shaper.measure(&props, "fix", &mut glyphs);
let ids: Vec<u32> = glyphs.iter().map(|g| g.id).collect();
assert_eq!(ids, [102, 105, 120]);
}
}
#[test]
fn scales_the_characters_before_their_spacing() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
scale: Some(150),
spacing: Some(Length::from_units(1_000)),
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(&props, "ab", &mut glyphs);
let advances: Vec<i64> = glyphs.iter().map(|g| g.advance.units()).collect();
assert_eq!(advances, [39_100, 39_100]);
}
#[test]
fn a_space_typed_in_a_math_run_holds_the_line_together_and_keeps_its_glyph() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let text = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
..RunProps::default()
};
let math = RunProps {
math: Some(true),
..text.clone()
};
let normal_math = RunProps {
math: Some(false),
..text.clone()
};
let (mut prose, mut equation, mut normal) = (Vec::new(), Vec::new(), Vec::new());
shaper.measure(&text, "a b", &mut prose);
shaper.measure(&math, "a b", &mut equation);
shaper.measure(&normal_math, "a b", &mut normal);
let kinds: Vec<SpaceKind> = equation.iter().map(|g| g.space).collect();
assert_eq!(
kinds,
[SpaceKind::Free, SpaceKind::Equation, SpaceKind::Free]
);
assert_eq!(
normal.iter().map(|g| g.space).collect::<Vec<_>>(),
[SpaceKind::Free, SpaceKind::Equation, SpaceKind::Free]
);
assert!(crate::lines::is_space(&crate::lines::Piece::Glyph(
prose[1]
)));
assert!(!crate::lines::is_space(&crate::lines::Piece::Glyph(
equation[1]
)));
assert_eq!(equation[1].ch, ' ');
assert_eq!(equation[1].id, prose[1].id);
assert_eq!(equation[1].advance, prose[1].advance);
}
#[test]
fn an_operator_break_space_shapes_as_the_no_break_space_of_an_operator() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let math = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
math: Some(true),
..RunProps::default()
};
let (mut no_break, mut operator) = (Vec::new(), Vec::new());
shaper.measure(&math, "+\u{a0}", &mut no_break);
shaper.measure(
&math,
&format!("+{}", super::OPERATOR_BREAK_SPACE),
&mut operator,
);
assert_eq!(operator[1].ch, '\u{a0}');
assert_eq!(operator[1].space, SpaceKind::Operator);
assert_eq!(operator[1].id, no_break[1].id);
assert_eq!(operator[1].advance, no_break[1].advance);
}
#[test]
fn a_spaced_glyph_keeps_its_own_written_width_and_carries_its_spacing() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
spacing: Some(Length::from_units(-12_700)),
..RunProps::default()
};
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&props, "ab", &mut glyphs);
assert!(
glyphs
.iter()
.all(|g| g.written.is_none() && g.spacing == Length::ZERO)
);
let settings = super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::DeviceAdvance::ExtrasOnTheirOwn)
});
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings).fork();
let mut glyphs = Vec::new();
shaper.measure(&props, "ab", &mut glyphs);
let measured: Vec<(i64, Option<u16>, i64)> = glyphs
.iter()
.map(|g| (g.advance.units(), g.written, g.spacing.units()))
.collect();
assert_eq!(
measured,
[(12_700, Some(100), -12_700), (12_700, Some(100), -12_700)]
);
let mut glyphs = Vec::new();
let plain = RunProps {
spacing: None,
..props
};
shaper.measure(&plain, "ab", &mut glyphs);
assert!(
glyphs
.iter()
.all(|g| g.written.is_none() && g.spacing == Length::ZERO)
);
}
#[test]
fn clamps_condensed_character_spacing_at_zero_advance() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
spacing: Length::from_twips(-40),
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::DeviceAdvance::ExtrasOnTheirOwn)
});
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&props, "a ", &mut glyphs);
let measured: Vec<(i64, i64)> = glyphs
.iter()
.map(|g| (g.advance.units(), g.spacing.units()))
.collect();
assert_eq!(measured, [(0, -25_400), (0, -25_400)]);
}
#[test]
fn gives_full_width_characters_the_spacing_twice_when_byte_widths_balance() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
font_east_asia: Some(Box::new(crate::props::FontRef::Name("Any".into()))),
spacing: Some(Length::from_units(1_000)),
..RunProps::default()
};
let advances = |spacing: crate::styles::FullWidthSpacing| {
let mut shaper = super::Shaper::new(
&Joining,
&theme,
&table,
&super::ShaperSettings {
full_width_spacing: spacing,
..super::ShaperSettings::base()
},
);
let mut glyphs = Vec::new();
shaper.measure(&props, "测、Aa", &mut glyphs);
glyphs
.iter()
.map(|g| g.advance.units())
.collect::<Vec<i64>>()
};
assert_eq!(
advances(crate::styles::FullWidthSpacing::Twice),
[27_400, 27_400, 27_400, 26_400]
);
assert_eq!(
advances(crate::styles::FullWidthSpacing::Once),
[26_400, 26_400, 26_400, 26_400]
);
}
#[test]
fn widens_synthetic_bold_glyphs_but_not_spaces_by_a_fiftieth_of_the_size() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let advances = |shaper: &mut super::Shaper<'_>, bold| {
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
bold: Some(bold),
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(&props, "a b", &mut glyphs);
glyphs.iter().map(|g| g.advance.units()).collect::<Vec<_>>()
};
assert_eq!(advances(&mut shaper, false), [25_400, 25_400, 25_400]);
assert_eq!(advances(&mut shaper, true), [30_480, 25_400, 30_480]);
let settings = super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::SyntheticBoldWidth::KeepsWidths)
});
let keeps = super::Shaper::new(&Joining, &theme, &table, &settings);
assert_eq!(advances(&mut keeps.fork(), true), [25_400, 25_400, 25_400]);
}
#[test]
fn draws_small_capitals_at_four_fifths_of_the_size_to_the_nearest_half_point() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let advances = |shaper: &mut super::Shaper<'_>, half_points| {
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
size: Some(half_points),
small_caps: Some(true),
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(&props, "Ab 1+", &mut glyphs);
glyphs.iter().map(|g| g.advance.units()).collect::<Vec<_>>()
};
assert_eq!(
advances(&mut shaper, 32),
[40_640, 33_020, 33_020, 40_640, 40_640]
);
assert_eq!(
advances(&mut shaper, 24),
[30_480, 24_130, 24_130, 30_480, 30_480]
);
}
#[test]
fn leaves_out_the_format_characters_that_word_does_not_draw() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(
&props,
"\u{FEFF}a\u{200B}b\u{200D}\u{2060}c\u{FE0F}\u{202C}",
&mut glyphs,
);
let text: String = glyphs.iter().map(|g| g.ch).collect();
assert_eq!(text, "abc");
}
#[test]
fn marks_the_glyph_after_each_format_character() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let settings = super::ShaperSettings::base();
let mut shaper = super::Shaper::new(&Shaping, &theme, &table, &settings);
let props = RunProps {
size: Some(20),
size_cs: Some(20),
..RunProps::default()
};
let mut marked = |text: &str| {
let mut glyphs = Vec::new();
shaper.measure(&props, text, &mut glyphs);
glyphs
.iter()
.map(|g| {
(
g.ch,
g.left_out_before == super::LeftOutBefore::FormatCharacter,
)
})
.collect::<Vec<_>>()
};
assert_eq!(
marked("\u{0628}\u{0646}\u{200C}\u{0645}\u{0647}"),
[
('\u{0628}', false),
('\u{0646}', false),
('\u{0645}', true),
('\u{0647}', false),
]
);
assert_eq!(
marked("ab\u{200C}c \u{200C}d"),
[
('a', false),
('b', false),
('c', true),
(' ', false),
('d', true),
]
);
let format = ('\u{200B}'..='\u{200F}')
.chain('\u{202A}'..='\u{202E}')
.chain(['\u{FEFF}']);
for ch in format {
assert_eq!(
marked(&format!("ab{ch}c")),
[('a', false), ('b', false), ('c', true)],
"U+{:04X}",
u32::from(ch)
);
assert_eq!(
marked(&format!("\u{0628}{ch}\u{0646}")),
[('\u{0628}', false), ('\u{0646}', true)],
"U+{:04X}",
u32::from(ch)
);
}
assert!(
marked("\u{0628}\u{0646} ab\u{2060}c")
.iter()
.all(|&(_, after)| !after)
);
}
#[test]
fn draws_the_operators_and_joins_the_selectors_where_the_target_does() {
use crate::quirks::InvisibleCharacters;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let settings = super::ShaperSettings::base_with(|p| {
p.with_variant(InvisibleCharacters::OperatorsDrawnSelectorsJoined)
});
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
..RunProps::default()
};
let math = RunProps {
math: Some(true),
..props.clone()
};
let mut measured_in = |props: &RunProps, text: &str| {
let mut glyphs = Vec::new();
shaper.measure(props, text, &mut glyphs);
glyphs
};
let in_math = measured_in(&math, "\u{FE00}f\u{2061}x\u{2060}\u{FE0F}");
let mut measured = |text: &str| measured_in(&props, text);
let shown = |glyphs: &[super::Glyph]| glyphs.iter().map(|g| g.ch).collect::<String>();
assert_eq!(shown(&in_math), "fx");
assert_eq!(
shown(&measured(
"\u{FEFF}a\u{200B}b\u{200D}\u{2060}c\u{FE0F}\u{202C}"
)),
"ab\u{2060}c"
);
let opening = measured("\u{200B}\u{FE00}d\u{2061}");
assert_eq!(shown(&opening), "\u{FE00}d\u{2061}");
let selectors: Vec<bool> = opening.iter().map(super::is_selector).collect();
assert_eq!(selectors, [true, false, false]);
}
#[test]
fn decides_what_each_kind_of_invisible_character_does() {
use super::decisions::Invisible;
use crate::quirks::InvisibleCharacters;
let chars = [
'x', '\u{200C}', '\u{202E}', '\u{FEFF}', '\u{2060}', '\u{2064}', '\u{FE0F}',
];
let decided = |variant, math| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
chars.map(|ch| settings.invisible(ch, math))
};
let (drawn, left, joined) = (Invisible::Drawn, Invisible::Left, Invisible::Joined);
let none_drawn = [drawn, left, left, left, left, left, left];
for math in [false, true] {
assert_eq!(decided(InvisibleCharacters::TakeNoRoom, math), none_drawn);
}
assert_eq!(
decided(InvisibleCharacters::OperatorsDrawnSelectorsJoined, false),
[drawn, left, left, left, drawn, drawn, joined]
);
assert_eq!(
decided(InvisibleCharacters::OperatorsDrawnSelectorsJoined, true),
none_drawn
);
}
#[test]
fn draws_outlines_with_a_theme_color_in_yellow() {
let width = Length::from_emus(9_525).unwrap();
let run = |outline| RunProps {
outline,
..RunProps::default()
};
let solid = |color| Some(TextOutline::Solid { width, color });
assert_eq!(
outline(&run(solid(OutlineColor::Scheme))),
Some(Outline {
width,
color: Rgb {
r: 255,
g: 255,
b: 0
},
join: Join::Round,
})
);
assert_eq!(
outline(&run(solid(OutlineColor::Rgb([1, 2, 3])))),
Some(Outline {
width,
color: Rgb { r: 1, g: 2, b: 3 },
join: Join::Round,
})
);
assert_eq!(outline(&run(Some(TextOutline::None))), None);
assert_eq!(outline(&run(None)), None);
}
#[test]
fn scripts_of_equations_take_the_math_font_sizes_and_shifts() {
use crate::props::MathScript;
let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
let run = RunProps {
size: Some(24),
..RunProps::default()
};
let (quarter, mac) = (per_inch(288), per_inch(300));
let sup = MathScript::default().inside(MathStep::Superscript, None);
let sub = MathScript::default().inside(MathStep::Subscript, None);
let script = |size, rise| (pt(size), pt(rise), false);
assert_eq!(math_size_and_rise(&run, sup, quarter), script(850, 450));
assert_eq!(math_size_and_rise(&run, sub, quarter), script(850, -250));
assert_eq!(math_size_and_rise(&run, sup, mac), script(850, 432));
assert_eq!(math_size_and_rise(&run, sub, mac), script(850, -240));
let inner = sup.inside(MathStep::Subscript, None);
assert_eq!(math_size_and_rise(&run, inner, quarter), script(700, 275));
let raised = RunProps {
position: Some(pt(100)),
..run.clone()
};
assert_eq!(math_size_and_rise(&raised, sup, quarter).1, pt(550));
let display = MathScript::display();
assert_eq!(
math_size_and_rise(&run, display.inside(MathStep::Superscript, None), quarter),
script(850, 450)
);
}
#[test]
fn parts_of_fractions_take_the_math_font_sizes_and_shifts() {
use crate::props::MathScript;
let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
let quarter = per_inch(288);
let run = |half_points| RunProps {
size: Some(half_points),
..RunProps::default()
};
let part = |size, rise| (pt(size), pt(rise), true);
let inline = MathScript::default();
assert_eq!(
math_size_and_rise(&run(22), inline.inside(MathStep::Numerator, None), quarter),
part(800, 650)
);
assert_eq!(
math_size_and_rise(
&run(22),
inline.inside(MathStep::Denominator, None),
quarter
),
part(800, -550)
);
let display = MathScript::display();
let numerator = display.inside(MathStep::Numerator, None);
assert_eq!(
math_size_and_rise(&run(24), numerator, quarter),
part(1200, 900)
);
assert_eq!(
math_size_and_rise(
&run(24),
display.inside(MathStep::Denominator, None),
quarter
),
part(1200, -800)
);
assert_eq!(
math_size_and_rise(
&run(24),
numerator.inside(MathStep::Numerator, None),
quarter
),
part(1200, 1600)
);
assert_eq!(
math_size_and_rise(
&run(24),
display
.with_small_frac(crate::props::SmallFractions::On)
.inside(MathStep::Numerator, None)
.inside(MathStep::Numerator, None),
quarter
),
part(850, 1600)
);
let inner = inline
.inside(MathStep::Numerator, None)
.inside(MathStep::Superscript, None);
assert!(math_size_and_rise(&run(22), inner, quarter).2);
}
#[test]
fn structures_shift_their_parts_at_the_size_of_their_control_properties() {
use crate::props::MathScript;
let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
let quarter = per_inch(288);
let run = RunProps {
size: Some(20),
..RunProps::default()
};
let display = MathScript::display();
let numerator = display.inside(MathStep::Numerator, Some(28));
let denominator = display.inside(MathStep::Denominator, Some(28));
assert_eq!(
math_size_and_rise(&run, numerator, quarter),
(pt(1000), pt(1050), true)
);
assert_eq!(
math_size_and_rise(&run, denominator, quarter),
(pt(1000), pt(-925), true)
);
let sized = numerator.inside(MathStep::Superscript, Some(16));
assert_eq!(math_size_and_rise(&run, sized, quarter).1, pt(1350));
let plain = numerator.inside(MathStep::Superscript, None);
assert_eq!(math_size_and_rise(&run, plain, quarter).1, pt(1425));
}
#[test]
fn superscripts_in_a_denominator_take_the_cramped_shift() {
use crate::props::MathScript;
let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
let quarter = per_inch(288);
let run = RunProps {
size: Some(24),
..RunProps::default()
};
let rise = |script| math_size_and_rise(&run, script, quarter).1;
let display = MathScript::display();
let numerator = display.inside(MathStep::Numerator, None);
let denominator = display.inside(MathStep::Denominator, None);
assert_eq!(rise(denominator), pt(-800));
assert_eq!(
rise(denominator.inside(MathStep::Superscript, None)),
pt(-450)
);
assert_eq!(
rise(numerator.inside(MathStep::Superscript, None)),
pt(1350)
);
let inner = denominator.inside(MathStep::Numerator, None);
let small_inner = display
.with_small_frac(crate::props::SmallFractions::On)
.inside(MathStep::Denominator, None)
.inside(MathStep::Numerator, None);
assert_eq!(
(
rise(inner.inside(MathStep::Superscript, None)),
rise(small_inner.inside(MathStep::Superscript, None)),
),
(pt(250), pt(150))
);
let beside = denominator.inside(MathStep::SuperscriptBesideSubscript, None);
assert_eq!(rise(beside), pt(-375));
let element = display.cramped();
assert_eq!(rise(element.inside(MathStep::Superscript, None)), pt(350));
assert_eq!(rise(display.inside(MathStep::Superscript, None)), pt(450));
}
#[test]
fn superscripts_take_two_thirds_in_whole_half_points() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let run = |size, vertical| RunProps {
size: Some(size),
vertical,
..RunProps::default()
};
let sup = Some(VerticalAlign::Superscript);
let lost = ScriptMove::LostSize(None);
assert_eq!(
size_and_rise(&run(22, sup), lost, ScriptScale::TwoThirds).0,
points(14)
);
assert_eq!(
size_and_rise(&run(24, sup), lost, ScriptScale::TwoThirds).0,
points(16)
);
let sub = size_and_rise(
&run(24, Some(VerticalAlign::Subscript)),
lost,
ScriptScale::TwoThirds,
);
assert_eq!(sub, (points(16), Length::from_units(-points(2).units())));
assert_eq!(
size_and_rise(&run(22, None), lost, ScriptScale::TwoThirds),
(points(22), Length::ZERO)
);
assert_eq!(
size_and_rise(&run(20, sup), lost, ScriptScale::TwoThirds),
(points(13), points(7))
);
let sub = size_and_rise(
&run(20, Some(VerticalAlign::Subscript)),
lost,
ScriptScale::TwoThirds,
)
.1;
assert_eq!(sub, Length::from_units(-points(7).units() / 4));
}
fn script_size_in(
half_points: i64,
vertical: VerticalAlign,
metrics: &crate::FaceMetrics,
) -> Length {
let run = RunProps {
size: Some(half_points),
vertical: Some(vertical),
..RunProps::default()
};
let scale = ScriptScale::of_face(metrics, Some(vertical));
size_and_rise(&run, ScriptMove::LostSize(None), scale).0
}
fn script_face(
em: u16,
superscript_size: i16,
subscript_size: i16,
superscript_offset: i16,
) -> crate::FaceMetrics {
crate::FaceMetrics {
units_per_em: em,
superscript_size,
subscript_size,
superscript_offset,
..crate::FaceMetrics::default()
}
}
#[test]
fn scripts_take_the_sizes_of_their_font_within_the_values_seen_to_keep_them() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let (sup, sub) = (VerticalAlign::Superscript, VerticalAlign::Subscript);
let six_tenths = script_face(2048, 1229, 1229, 717);
assert_eq!(script_size_in(22, sup, &six_tenths), points(13));
assert_eq!(
script_size_in(24, sup, &script_face(2048, 1331, 1331, 928)),
points(16)
);
let apart = script_face(2048, 1250, 1180, 760);
assert_eq!(script_size_in(24, sup, &apart), points(15));
assert_eq!(script_size_in(24, sub, &apart), points(14));
assert_eq!(
script_size_in(24, sup, &script_face(256, 128, 128, 128)),
points(12)
);
}
#[test]
fn scripts_in_a_font_of_odd_values_take_three_fifths_of_the_size() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
for odd in [
script_face(2048, 650, 650, 500),
script_face(2048, 1579, 1579, 0),
script_face(256, 128, 128, 220),
script_face(2048, 1331, 1331, 0),
script_face(1000, 0, 0, 0),
] {
assert_eq!(
script_size_in(24, VerticalAlign::Superscript, &odd),
points(14)
);
assert_eq!(
script_size_in(24, VerticalAlign::Subscript, &odd),
points(14)
);
}
}
#[test]
fn scripts_of_at_most_a_third_of_their_line_take_three_fifths_line_by_line() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let (sup, sub) = (VerticalAlign::Superscript, VerticalAlign::Subscript);
let third = script_face(2048, 683, 683, 976);
assert_eq!(script_size_in(20, sup, &third), points(7));
assert_eq!(script_size_in(21, sup, &third), points(13));
assert_eq!(script_size_in(24, sub, &third), points(14));
assert_eq!(script_size_in(200, sup, &third), points(67));
assert_eq!(script_size_in(201, sup, &third), points(121));
}
#[test]
fn scripts_whose_superscript_offset_lies_below_a_quarter_of_their_line_fall_back_line_by_line() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let (sup, sub) = (VerticalAlign::Superscript, VerticalAlign::Subscript);
let garamond = crate::FaceMetrics {
line_top: 1765,
script_top: 1765,
descent: 539,
..script_face(2048, 1331, 1331, 469)
};
let perpetua = script_face(2048, 1331, 1331, 385);
for (face, hp, kind, expected) in [
(&garamond, 20, sup, 13),
(&garamond, 23, sup, 15),
(&garamond, 24, sup, 14),
(&garamond, 24, sub, 14),
(&garamond, 25, sup, 16),
(&garamond, 28, sup, 17),
(&perpetua, 18, sup, 11),
(&perpetua, 19, sup, 12),
(&perpetua, 20, sup, 12),
] {
assert_eq!(script_size_in(hp, kind, face), points(expected));
}
for (hp, expected_rise) in [(20, 5), (24, 9)] {
let run = RunProps {
size: Some(hp),
vertical: Some(sup),
..RunProps::default()
};
let edges = Edges {
metrics: &garamond,
dot: per_inch(600),
heights: &|_| None,
room: 0,
};
let scale = ScriptScale::of_face(&garamond, Some(sup));
assert_eq!(
size_and_rise(&run, ScriptMove::LineEdges(edges), scale).1,
points(expected_rise)
);
}
}
#[test]
fn scripts_keep_sizes_of_the_font_up_to_its_em() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
for (size, half_points) in [(1843, 22), (2048, 24)] {
assert_eq!(
script_size_in(
24,
VerticalAlign::Superscript,
&script_face(2048, size, size, 976)
),
points(half_points)
);
}
}
#[test]
fn scripts_meet_the_edges_of_their_line_on_dots_and_half_points() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let run = |size, vertical| RunProps {
size: Some(size),
vertical: Some(vertical),
..RunProps::default()
};
let dot = per_inch(288);
let calibri = crate::FaceMetrics {
units_per_em: 2048,
line_top: 1950,
script_top: 1950,
descent: 550,
..crate::FaceMetrics::default()
};
let moved = |size, vertical, metrics| {
let edges = Edges {
metrics,
dot,
heights: &|_| None,
room: 0,
};
size_and_rise(
&run(size, vertical),
ScriptMove::LineEdges(edges),
ScriptScale::TwoThirds,
)
.1
};
for (size, rise) in [(20, 6), (22, 7), (24, 8)] {
assert_eq!(
moved(size, VerticalAlign::Superscript, &calibri),
points(rise)
);
let drop = moved(size, VerticalAlign::Subscript, &calibri);
assert_eq!(drop, Length::from_units(-points(2).units()));
}
let low = crate::FaceMetrics {
units_per_em: 1000,
line_top: 1000,
script_top: 1000,
descent: 500,
superscript_offset: 250,
subscript_offset: 100,
..crate::FaceMetrics::default()
};
assert_eq!(moved(28, VerticalAlign::Superscript, &low), points(7));
let drop = moved(28, VerticalAlign::Subscript, &low);
assert_eq!(drop, Length::from_units(-points(3).units()));
}
#[test]
fn superscripts_whose_font_values_are_not_used_meet_the_line_top_within_the_em_without_a_cap() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let rise = |half_points: i64, metrics: &crate::FaceMetrics| {
let run = RunProps {
size: Some(half_points),
vertical: Some(VerticalAlign::Superscript),
..RunProps::default()
};
let edges = Edges {
metrics,
dot: per_inch(600),
heights: &|_| None,
room: 0,
};
let scale = ScriptScale::of_face(metrics, Some(VerticalAlign::Superscript));
size_and_rise(&run, ScriptMove::LineEdges(edges), scale).1
};
let with_top = |top: u16, offset: i16, size: i16, east_asian: bool| crate::FaceMetrics {
line_top: top,
script_top: top,
descent: 500,
east_asian,
..script_face(2048, size, size, offset)
};
assert_eq!(rise(24, &with_top(1900, 500, 650, false)), points(9));
assert_eq!(rise(24, &with_top(2300, 500, 650, false)), points(10));
assert_eq!(rise(16, &with_top(2300, 0, 1331, false)), points(6));
assert_eq!(rise(24, &with_top(1900, 0, 1331, true)), points(10));
assert_eq!(rise(20, &with_top(1900, 976, 683, false)), points(10));
}
#[test]
fn subscripts_meet_the_line_bottom_by_their_font_values_and_the_east_asian_room() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let drop = |half_points: i64, metrics: &crate::FaceMetrics, room: i64| {
let run = RunProps {
size: Some(half_points),
vertical: Some(VerticalAlign::Subscript),
..RunProps::default()
};
let edges = Edges {
metrics,
dot: per_inch(600),
heights: &|_| None,
room,
};
let scale = ScriptScale::of_face(metrics, Some(VerticalAlign::Subscript));
Length::ZERO - size_and_rise(&run, ScriptMove::LineEdges(edges), scale).1
};
let face = |superscript_offset: i16, subscript_offset: i16| crate::FaceMetrics {
line_top: 1638,
script_top: 1638,
descent: 600,
subscript_offset,
..script_face(2048, 1331, 1331, superscript_offset)
};
assert_eq!(drop(24, &face(600, 100), 0), points(1));
assert_eq!(drop(24, &face(600, 0), 0), Length::ZERO);
assert_eq!(drop(24, &face(0, 100), 0), points(3));
assert_eq!(drop(24, &face(0, 100), 150), points(4));
assert_eq!(drop(24, &face(0, 100), 600), points(5));
}
#[test]
fn scripts_take_the_heights_of_the_vdmx_table_when_the_font_gives_them() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let run = |vertical| RunProps {
size: Some(24),
vertical: Some(vertical),
..RunProps::default()
};
let dot = per_inch(288);
let times = crate::FaceMetrics {
units_per_em: 2048,
line_top: 1912,
script_top: 1825,
descent: 443,
..crate::FaceMetrics::default()
};
let vdmx = |pels: u16| match pels {
32 => Some((28, -8)),
48 => Some((43, -12)),
_ => None,
};
let moved = |vertical, heights: &dyn Fn(u16) -> Option<(i16, i16)>| {
let edges = Edges {
metrics: ×,
dot,
heights,
room: 0,
};
size_and_rise(
&run(vertical),
ScriptMove::LineEdges(edges),
ScriptScale::TwoThirds,
)
.1
};
let down = |half_points| Length::from_units(-points(half_points).units());
assert_eq!(moved(VerticalAlign::Superscript, &vdmx), points(9));
assert_eq!(moved(VerticalAlign::Subscript, &vdmx), down(2));
assert_eq!(moved(VerticalAlign::Superscript, &|_| None), points(8));
assert_eq!(moved(VerticalAlign::Subscript, &|_| None), down(1));
}
#[test]
fn superscripts_rise_no_higher_than_their_font_raises_them() {
let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
let sup = RunProps {
size: Some(28),
vertical: Some(VerticalAlign::Superscript),
..RunProps::default()
};
let metrics = |offset| crate::FaceMetrics {
units_per_em: 1000,
superscript_offset: offset,
..crate::FaceMetrics::default()
};
let rise = |offset| {
let cap = super::superscript_cap(&sup, &metrics(offset));
size_and_rise(&sup, ScriptMove::LostSize(cap), ScriptScale::TwoThirds).1
};
assert_eq!(rise(250), points(7));
assert_eq!(rise(500), points(10));
assert_eq!(rise(0), points(10));
let sub = RunProps {
vertical: Some(VerticalAlign::Subscript),
..sup
};
let cap = super::superscript_cap(&sub, &metrics(250));
assert_eq!(
size_and_rise(&sub, ScriptMove::LostSize(cap), ScriptScale::TwoThirds).1,
Length::from_units(-points(10).units() / 4)
);
}
#[test]
fn symbol_characters_read_as_word_writes_them() {
let symbol = Some(SymbolFont::Symbol);
let cases = [
('\u{F0B7}', symbol, 1, '\u{2022}'),
('\u{F0B7}', None, 1, '\u{B7}'),
('\u{F0A7}', Some(SymbolFont::Wingdings), 1, '\u{A7}'),
('\u{F071}', symbol, 1, 'q'),
('a', symbol, 1, 'a'),
('\u{A7}', Some(SymbolFont::Wingdings), 1, '\u{A7}'),
('\u{F100}', None, 1, '\u{F100}'),
('\u{F07F}', symbol, 0, '\u{FFFD}'),
('a', None, 0, 'a'),
('\u{B7}', symbol, 1, '\u{2022}'),
('\u{B7}', None, 1, '\u{B7}'),
];
for (ch, font, id, text) in cases {
assert_eq!(
super::ShaperSettings::base_with(|p| p.with_variant(SymbolText::LowByte))
.symbol_text(ch, font, id),
text,
"{ch:?}"
);
}
}
#[test]
fn knows_the_symbol_fonts_by_name_and_stands_in_for_their_bullets() {
let with_codes =
|family| SymbolFont::of(family).filter(|&font| super::symbol_table::has_codes(font));
assert_eq!(
(with_codes("wingdings"), with_codes("Wingdings 2")),
(Some(SymbolFont::Wingdings), None)
);
assert_eq!(
(symbol_stand_in('\u{F0B7}'), symbol_stand_in('a')),
(Some('\u{2022}'), None)
);
}
#[test]
fn symbol_characters_read_as_the_table_gives_them_where_the_target_says_so() {
let (symbol, wingdings) = (Some(SymbolFont::Symbol), Some(SymbolFont::Wingdings));
let cases = [
('\u{F0A7}', wingdings, 1, '\u{25AA}'),
('\u{F0FC}', wingdings, 1, '\u{2713}'),
('\u{F0B7}', symbol, 1, '\u{2022}'),
('\u{F02D}', symbol, 1, '\u{2212}'),
('\u{F0A8}', wingdings, 1, '\u{F0A8}'),
('\u{F0AF}', symbol, 1, '\u{F0AF}'),
('\u{F061}', symbol, 1, '\u{F061}'),
('\u{F051}', None, 1, '\u{F051}'),
('a', None, 1, 'a'),
('\u{F07F}', symbol, 0, '\u{F07F}'),
('\u{B7}', symbol, 1, '\u{2022}'),
('\u{E8}', wingdings, 1, '\u{2794}'),
('\u{A7}', wingdings, 1, '\u{25AA}'),
('a', symbol, 1, 'a'),
('\u{A8}', wingdings, 1, '\u{A8}'),
('\u{E8}', None, 1, '\u{E8}'),
];
for (ch, font, id, text) in cases {
let written =
super::ShaperSettings::base_with(|p| p.with_variant(SymbolText::TableOrSymbol))
.symbol_text(ch, font, id);
assert_eq!(written, text, "{ch:?}");
}
}
#[test]
fn starts_a_piece_at_each_256th_character_of_a_run_or_of_a_page() {
let at = |in_run, in_paragraph| super::TextPlace {
in_run,
in_paragraph,
starts_buffer: false,
run: None,
};
assert!(at(256, 300).starts_piece(0, 256));
assert!(at(512, 512).starts_piece(0, 256));
assert!(!at(0, 256).starts_piece(0, 256));
assert!(!at(255, 255).starts_piece(0, 256));
assert!(!at(512, 512).starts_piece(100, 256));
assert!(at(356, 356).starts_piece(100, 256));
assert!(at(256, 900).starts_piece(100, 256));
}
#[test]
fn takes_the_hhea_line_or_the_taller_line_as_the_profile_says() {
let metrics = crate::FaceMetrics {
units_per_em: 2048,
hhea_ascender: 1523,
hhea_descender: -525,
hhea_line_gap: 425,
descent: 550,
line_top: 1950,
script_top: 1950,
..crate::FaceMetrics::default()
};
let size = Length::from_units(2048 * 100);
let face = |line_height| plain_face(metrics, size, line_height);
let hhea = face(LineHeight::TakesHheaLine);
let taller = face(LineHeight::TakesTallerLine);
assert_eq!(hhea.line_height().units(), 247_300);
assert_eq!(taller.line_height().units(), 250_000);
assert_eq!(hhea.descent().units(), 55_000);
assert_eq!(taller.descent().units(), 55_000);
assert_eq!(taller.ascent().units(), 195_000);
}
#[test]
fn leaves_out_the_line_gap_of_a_font_made_for_east_asian_text() {
let metrics = crate::FaceMetrics {
units_per_em: 256,
hhea_ascender: 220,
hhea_descender: -36,
hhea_line_gap: 36,
descent: 36,
line_top: 256,
script_top: 220,
east_asian: true,
..crate::FaceMetrics::default()
};
let size = Length::from_units(256 * 100);
let face = |metrics, line_height| plain_face(metrics, size, line_height);
for line_height in [
LineHeight::TakesHheaLine,
LineHeight::TakesTallerLine,
LineHeight::TakesTallerLineEastAsianWin,
] {
let face = face(metrics, line_height);
assert_eq!(face.line_height().units(), 33_200);
assert_eq!(face.descent().units(), 7_400);
assert_eq!(face.ascent().units(), 25_800);
}
let win = crate::FaceMetrics {
hhea_ascender: 200,
hhea_descender: -56,
descent: 50,
line_top: 242,
script_top: 230,
..metrics
};
assert_eq!(
face(win, LineHeight::TakesTallerLine).line_height().units(),
36_400
);
assert_eq!(
face(win, LineHeight::TakesHheaLine).line_height().units(),
33_200
);
let latin = crate::FaceMetrics {
east_asian: false,
..metrics
};
assert_eq!(
face(latin, LineHeight::TakesHheaLine).line_height().units(),
29_200
);
}
#[test]
fn takes_the_win_line_of_an_east_asian_font_whose_hhea_line_is_taller_where_the_target_does() {
let metrics = crate::FaceMetrics {
units_per_em: 1000,
hhea_ascender: 986,
hhea_descender: -315,
hhea_line_gap: 0,
descent: 260,
line_top: 1041,
script_top: 860,
east_asian: true,
..crate::FaceMetrics::default()
};
let size = Length::from_units(1000 * 100);
let taller = plain_face(metrics, size, LineHeight::TakesTallerLine);
let win = plain_face(metrics, size, LineHeight::TakesTallerLineEastAsianWin);
assert_eq!(taller.line_height().units(), 169_100);
assert_eq!(taller.descent().units(), 45_500);
assert_eq!(win.line_height().units(), 145_600);
assert_eq!(win.descent().units(), 42_800);
assert_eq!(win.ascent().units(), 102_800);
let latin = crate::FaceMetrics {
east_asian: false,
..metrics
};
assert_eq!(
plain_face(latin, size, LineHeight::TakesTallerLineEastAsianWin)
.line_height()
.units(),
130_100
);
}
#[test]
fn cuts_pieces_of_256_characters_from_mode_15_and_of_512_before() {
let at = |in_run| super::TextPlace {
in_run,
in_paragraph: in_run,
starts_buffer: false,
run: None,
};
assert!(!at(256).starts_piece(0, 512));
assert!(at(1024).starts_piece(0, 512));
}
struct Hinted;
impl crate::Fonts for Hinted {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn bi_level_advance(
&self,
_font: f_office_fonts::FontId,
glyph: u32,
ppem: u16,
) -> Option<i32> {
(ppem == 1000).then_some(if glyph == u32::from('a') { 101 } else { 100 })
}
fn target_face(&self, _font: f_office_fonts::FontId) -> Option<(String, String)> {
Some(("Face-One".to_owned(), "Version 2.5".to_owned()))
}
}
struct HyphenPairs;
impl crate::Fonts for HyphenPairs {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn kerning(
&self,
_font: f_office_fonts::FontId,
left: u32,
right: u32,
_table: crate::KerningTable,
) -> i32 {
if (left, right) == (u32::from('r'), u32::from('-')) {
-76
} else {
0
}
}
}
#[test]
fn kerns_a_non_breaking_hyphen_with_the_pairs_of_its_own_glyph() {
use crate::quirks::NonBreakingHyphen;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let props = RunProps {
size: Some(20),
kern: Some(2),
..RunProps::default()
};
let kerning = |variant, text: &str| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
let mut shaper = super::Shaper::new(&HyphenPairs, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&props, text, &mut glyphs);
glyphs.first().map(|g| g.kerning.units())
};
let element = format!("r{}G", super::NON_BREAKING_HYPHEN);
for variant in [
NonBreakingHyphen::OwnGlyph,
NonBreakingHyphen::AsHyphenMinus,
] {
assert_eq!(kerning(variant, &element), Some(0));
assert_ne!(kerning(variant, "r-G"), Some(0));
}
}
#[test]
fn draws_a_non_breaking_hyphen_with_the_glyph_that_the_quirk_names() {
use crate::quirks::NonBreakingHyphen;
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let id = |variant| {
let mut shaper = super::Shaper::new(
&Joining,
&theme,
&table,
&super::ShaperSettings::base_with(|p| p.with_variant(variant)),
);
let face = shaper.face(&RunProps::default(), true).unwrap();
shaper.glyph(face, super::NON_BREAKING_HYPHEN).unwrap().id
};
assert_eq!(id(NonBreakingHyphen::OwnGlyph), 0x2011);
assert_eq!(id(NonBreakingHyphen::AsHyphenMinus), u32::from('-'));
}
#[test]
fn writes_the_bi_level_width_where_it_differs_from_the_rounded_advance() {
use crate::quirks::WrittenWidths;
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let written = |widths, ch| {
let mut shaper = super::Shaper::new(
&Hinted,
&theme,
&table,
&super::ShaperSettings::base_with(|p| p.with_variant(widths)),
);
let face = shaper.face(&RunProps::default(), true).unwrap();
shaper.glyph(face, ch).unwrap().written
};
assert_eq!(written(WrittenWidths::HintedAdvanceAt1000, 'a'), Some(101));
assert_eq!(written(WrittenWidths::HintedAdvanceAt1000, 'b'), None);
assert_eq!(written(WrittenWidths::RoundsAdvance, 'a'), None);
}
struct HalfWidths;
impl crate::Fonts for HalfWidths {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
let mut face = Joining.face(family, bold, italic)?;
face.metrics.units_per_em = 2000;
Some(face)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Some(if glyph == 500 { 1500 } else { 1181 })
}
fn ligatures(
&self,
font: f_office_fonts::FontId,
glyphs: &[u32],
) -> Vec<f_office_fonts::Ligature> {
Joining.ligatures(font, glyphs)
}
}
#[test]
fn writes_a_width_of_a_half_thousandth_from_font_units() {
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let settings = super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::WrittenWidths::HintedAdvanceAt1000)
});
let mut shaper = super::Shaper::new(&HalfWidths, &theme, &table, &settings);
let props = RunProps {
size: Some(24),
..RunProps::default()
};
let face = shaper.face(&props, true).unwrap();
let glyph = shaper.glyph(face, 'T').unwrap();
let size = 24 * 12_700;
assert_eq!(glyph.advance.units(), 179_984);
assert_eq!(f_office_units::div_round(179_984 * 1000, size), 590);
assert_eq!(glyph.written, Some(591));
let props = RunProps {
size: Some(25),
..RunProps::default()
};
let face = shaper.face(&props, true).unwrap();
assert_eq!(shaper.glyph(face, 'T').unwrap().written, None);
}
#[test]
fn a_ligature_writes_its_own_width_and_not_its_first_letters() {
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let settings = super::ShaperSettings {
ligatures: true,
..super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::WrittenWidths::HintedAdvanceAt1000)
})
};
let mut shaper = super::Shaper::new(&HalfWidths, &theme, &table, &settings);
let props = RunProps {
font_ascii: Some(crate::props::FontRef::Name("Any".into())),
size: Some(24),
ligatures: Some(true),
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(&props, "fix", &mut glyphs);
let first = glyphs.first().unwrap();
assert_eq!((first.id, first.written), (500, None));
let mut glyphs = Vec::new();
shaper.measure(
&RunProps {
ligatures: None,
..props
},
"fix",
&mut glyphs,
);
assert_eq!(
glyphs.first().map(|g| (g.id, g.written)),
Some((102, Some(591)))
);
}
struct Instructed {
own: bool,
source: f_office_fonts::KerningSource,
}
impl Instructed {
const fn legacy(own: bool) -> Self {
Self {
own,
source: f_office_fonts::KerningSource::KernTable,
}
}
}
impl crate::Fonts for Instructed {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Hinted.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Hinted.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Hinted.advance(font, glyph)
}
fn kerning_source(&self, _font: f_office_fonts::FontId) -> f_office_fonts::KerningSource {
self.source
}
fn target_face(&self, font: f_office_fonts::FontId) -> Option<(String, String)> {
self.own.then(|| Hinted.target_face(font)).flatten()
}
fn device_width(&self, _font: f_office_fonts::FontId, _glyph: u32, _ppem: u16) -> Option<i32> {
Some(17)
}
fn kerning(
&self,
_font: f_office_fonts::FontId,
left: u32,
right: u32,
_table: crate::KerningTable,
) -> i32 {
if (left, right) == (u32::from('A'), u32::from('V')) {
-50
} else {
0
}
}
}
#[test]
fn takes_the_device_width_of_the_targets_own_face_from_its_instructions() {
use crate::quirks::GridAdvances::{RightEdgeSteps, RoundToPdfSteps};
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let size = 11 * f_office_units::Length::UNITS_PER_POINT;
let width = |own, advances| {
let fonts = Instructed::legacy(own);
let settings = on_steps(|p| p.with_variant(advances));
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let fork = shaper.fork().face(&RunProps::default(), true).unwrap();
let face = shaper.face(&RunProps::default(), true).unwrap();
let face = super::FaceIndex(face.0.max(fork.0));
shaper.device_width(face, u32::from('I'), (size, 44))
};
assert_eq!(width(true, RightEdgeSteps), Some((17, size / 10)));
assert_eq!(width(false, RightEdgeSteps), None);
assert_eq!(width(true, RoundToPdfSteps), None);
}
#[test]
fn keeps_or_drops_the_device_width_of_a_kerned_run_by_the_targets_variant() {
use crate::quirks::KernedDeviceWidths;
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let size = 11 * f_office_units::Length::UNITS_PER_POINT;
let fonts = Instructed {
own: true,
source: f_office_fonts::KerningSource::Gpos,
};
let mode_15 = crate::mode::ModeRules::of(crate::mode::CompatibilityMode::Mode15);
let width = |kerned, kern: Option<i64>| {
let settings = super::ShaperSettings {
mode_rules: mode_15,
..device_steps(kerned)
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let props = RunProps {
kern,
..RunProps::default()
};
let face = shaper.face(&props, true).unwrap();
shaper
.device_width(face, u32::from('I'), (size, 44))
.map(|(width, _)| width)
};
let own = KernedDeviceWidths::Own;
let on_its_own = KernedDeviceWidths::OwnWithKerningOnItsOwn;
let nearest = KernedDeviceWidths::Nearest;
assert_eq!(width(nearest, Some(2)), None);
assert_eq!(width(nearest, None), Some(17));
assert_eq!(width(nearest, Some(400)), Some(17));
assert_eq!(width(own, Some(2)), width(own, None));
assert_eq!(width(on_its_own, Some(2)), Some(17));
}
fn device_steps(kerned: crate::quirks::KernedDeviceWidths) -> super::ShaperSettings {
on_steps(|p| p.with_variant(kerned))
}
fn on_steps(
change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
) -> super::ShaperSettings {
let steps = crate::Target::all()
.map(|target| crate::profile::Profile::of(target).unwrap())
.find(|profile| {
profile.quirks().grid_advances == crate::quirks::GridAdvances::RightEdgeSteps
})
.expect("a target steps glyphs by whole dots");
let profile = change(
&steps
.with_variant(crate::quirks::KerningTableRead::FaceSource)
.with_variant(crate::quirks::DeviceAdvance::ExactAdvances),
);
super::ShaperSettings::of(
&crate::styles::Settings::default(),
&profile.quirks(),
profile.device().dot_size(),
)
}
fn kerned_steps(
kerned: crate::quirks::KernedDeviceWidths,
(mode, source): (
crate::mode::CompatibilityMode,
f_office_fonts::KerningSource,
),
kern: Option<i64>,
) -> (bool, Option<i64>) {
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let size = 11 * f_office_units::Length::UNITS_PER_POINT;
let fonts = Instructed { own: true, source };
let settings = super::ShaperSettings {
mode_rules: crate::mode::ModeRules::of(mode),
..device_steps(kerned)
};
let shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let props = RunProps {
kern,
..RunProps::default()
};
let mut shaper = shaper.fork();
let face = shaper.face(&props, true).unwrap();
let width = shaper.device_width(face, u32::from('I'), (size, 44));
(
shaper.steps_without_bias(face),
width.map(|(width, _)| width),
)
}
fn ligature_steps_without_bias(ligatures: crate::quirks::LigatureSteps, kern: Option<i64>) -> bool {
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let fonts = Instructed {
own: true,
source: f_office_fonts::KerningSource::Gpos,
};
let settings = super::ShaperSettings {
mode_rules: crate::mode::ModeRules::of(crate::mode::CompatibilityMode::Mode15),
ligatures: true,
..on_steps(|p| {
p.with_variant(crate::quirks::KernedDeviceWidths::Nearest)
.with_variant(ligatures)
})
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let props = RunProps {
kern,
ligatures: Some(true),
..RunProps::default()
};
let face = shaper.face(&props, true).unwrap();
shaper.steps_without_bias(face)
}
#[test]
fn steps_a_run_with_ligatures_as_a_kerned_run_where_the_target_does() {
use crate::quirks::LigatureSteps;
assert!(ligature_steps_without_bias(
LigatureSteps::AsKernedRun,
None
));
assert!(ligature_steps_without_bias(
LigatureSteps::AsKernedRun,
Some(2)
));
assert!(!ligature_steps_without_bias(
LigatureSteps::AsTheirRun,
None
));
assert!(ligature_steps_without_bias(
LigatureSteps::AsTheirRun,
Some(2)
));
}
#[test]
fn steps_a_kerned_run_without_the_bias_where_the_target_does() {
use crate::quirks::KernedDeviceWidths;
let nearest = KernedDeviceWidths::Nearest;
let gpos_15 = (
crate::mode::CompatibilityMode::Mode15,
f_office_fonts::KerningSource::Gpos,
);
assert_eq!(kerned_steps(nearest, gpos_15, Some(2)), (true, None));
assert_eq!(kerned_steps(nearest, gpos_15, None), (false, Some(17)));
assert_eq!(kerned_steps(nearest, gpos_15, Some(400)), (false, Some(17)));
let on_its_own = KernedDeviceWidths::OwnWithKerningOnItsOwn;
assert_eq!(
kerned_steps(on_its_own, gpos_15, Some(2)),
(false, Some(17))
);
let own = KernedDeviceWidths::Own;
assert_eq!(kerned_steps(own, gpos_15, Some(2)), (false, Some(17)));
let rounded = KernedDeviceWidths::Rounded;
assert_eq!(kerned_steps(rounded, gpos_15, Some(2)), (false, None));
}
#[test]
fn steps_a_kerned_run_by_its_device_widths_before_mode_15_and_rounded_in_a_legacy_kern_face_from_it()
{
use crate::mode::CompatibilityMode;
use f_office_fonts::KerningSource;
let nearest = crate::quirks::KernedDeviceWidths::Nearest;
let own = (false, Some(17));
for mode in [CompatibilityMode::Mode14, CompatibilityMode::Below14] {
for source in [KerningSource::Gpos, KerningSource::KernTable] {
assert_eq!(kerned_steps(nearest, (mode, source), Some(2)), own);
}
}
let legacy_15 = (CompatibilityMode::Mode15, KerningSource::KernTable);
assert_eq!(kerned_steps(nearest, legacy_15, Some(2)), (false, None));
}
#[test]
fn keeps_a_pairs_kerning_apart_for_the_steps_where_the_kerned_run_steps_so() {
use crate::mode::{CompatibilityMode, ModeRules};
use crate::quirks::KernedDeviceWidths::{Nearest, Own};
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let fonts = Instructed {
own: true,
source: f_office_fonts::KerningSource::Gpos,
};
let kerning = |kerned, mode| {
let settings = super::ShaperSettings {
mode_rules: ModeRules::of(mode),
..device_steps(kerned)
};
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let props = RunProps {
kern: Some(2),
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(&props, "AV", &mut glyphs);
let steps: Vec<Length> = glyphs
.iter()
.map(|g| shaper.kerning_on_its_own(g))
.collect();
(glyphs.first().map(|g| g.kerning), steps)
};
let (kept, steps) = kerning(Nearest, CompatibilityMode::Mode14);
let kept = kept.unwrap();
assert!(kept < Length::ZERO);
assert_eq!(steps, [kept, Length::ZERO]);
let zero = vec![Length::ZERO, Length::ZERO];
assert_eq!(kerning(Nearest, CompatibilityMode::Mode15).1, zero);
assert_eq!(kerning(Own, CompatibilityMode::Mode14).1, zero);
}
#[test]
fn steps_a_kerned_run_as_own_where_nearest_or_own_does_not_step_at_the_nearest_dot() {
use crate::mode::CompatibilityMode;
use f_office_fonts::KerningSource;
let either = crate::quirks::KernedDeviceWidths::NearestOrOwn;
let gpos_15 = (CompatibilityMode::Mode15, KerningSource::Gpos);
assert_eq!(kerned_steps(either, gpos_15, Some(2)), (true, None));
let own = (false, Some(17));
for mode in [CompatibilityMode::Mode14, CompatibilityMode::Below14] {
assert_eq!(
kerned_steps(either, (mode, KerningSource::Gpos), Some(2)),
own
);
}
let legacy_15 = (CompatibilityMode::Mode15, KerningSource::KernTable);
assert_eq!(kerned_steps(either, legacy_15, Some(2)), own);
}
struct Operators;
impl crate::Fonts for Operators {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Some(match glyph {
9000 => 1500,
8000 => 200,
8001 => 300,
_ => 100,
})
}
fn ink(
&self,
_font: f_office_fonts::FontId,
glyph: u32,
) -> Result<Option<(i32, i32)>, f_office_fonts::OutlineError> {
Ok(match glyph {
9000 => Some((-700, 1250)),
0x28 => Some((-250, 750)),
8000 => Some((-500, 1100)),
8001 => Some((-900, 1500)),
_ => None,
})
}
fn math_limits(&self, _font: f_office_fonts::FontId) -> Option<f_office_fonts::MathLimits> {
Some(f_office_fonts::MathLimits {
math_leading: 125,
display_operator_min_height: 1300,
upper_limit_baseline_rise_min: 250,
lower_limit_baseline_drop_min: 500,
superscript_baseline_drop_max: 290,
subscript_baseline_drop_min: 200,
delimited_sub_formula_min_height: 1465,
})
}
fn display_variant(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u32> {
(glyph == 0x2211).then_some(9000)
}
fn vertical_variant(
&self,
_font: f_office_fonts::FontId,
glyph: u32,
least: i32,
) -> Option<(u32, bool)> {
let variants = [(0x28, 1000), (8000, 1600), (8001, 2400)];
if glyph != 0x28 {
return None;
}
variants
.iter()
.find(|&&(_, height)| height >= least)
.map(|&(variant, _)| (variant, true))
.or(Some((8001, false)))
}
fn italic_correction(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<i32> {
(glyph == 9000).then_some(400)
}
fn script_glyph(
&self,
_font: f_office_fonts::FontId,
glyph: u32,
level: f_office_fonts::ScriptLevel,
) -> Option<u32> {
let script = match level {
f_office_fonts::ScriptLevel::Script => 7001,
f_office_fonts::ScriptLevel::ScriptOfScript => 7002,
};
(glyph == u32::from('x')).then_some(script)
}
}
fn hundredths(n: i64) -> Length {
Length::from_units(n * Length::UNITS_PER_POINT / 100)
}
fn math_run(script: MathScript) -> RunProps {
RunProps {
size: Some(24),
math_script: Some(script),
..RunProps::default()
}
}
#[test]
fn draws_a_display_operator_large_with_the_room_of_its_ink() {
use crate::Fonts as _;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let sum = |fonts: &dyn crate::Fonts| {
let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
let run = math_run(MathScript::display().large());
shaper.measure(&run, "\u{2211}", &mut glyphs);
let face = shaper.faces[glyphs[0].face.0].math;
(glyphs[0].id, glyphs[0].advance, face.large, face.room)
};
let leading = hundredths(150);
assert_eq!(
sum(&Operators),
(9000, hundredths(1800), true, MathRoom::Ink { leading })
);
assert_eq!(
sum(&Joining),
(0x2211, hundredths(120), true, MathRoom::Lines)
);
let font = f_office_fonts::FontId::from_index(0);
assert_eq!(Operators.display_variant(font, 97), None);
}
#[test]
fn draws_the_script_glyphs_of_the_level_that_the_style_gives() {
use crate::Fonts as _;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let glyph = |fonts: &dyn crate::Fonts, script: MathScript| {
let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
let mut glyphs = Vec::new();
shaper.measure(&math_run(script), "xy", &mut glyphs);
(glyphs[0].id, glyphs[1].id)
};
let (x, y) = (u32::from('x'), u32::from('y'));
let sup = MathStep::Superscript;
let display = MathScript::display();
assert_eq!(glyph(&Operators, display), (x, y));
assert_eq!(glyph(&Operators, display.inside(sup, None)), (7001, y));
let twice = display.inside(sup, None).inside(MathStep::Subscript, None);
assert_eq!(glyph(&Operators, twice), (7002, y));
let numerator = MathStep::Numerator;
assert_eq!(glyph(&Operators, display.inside(numerator, None)), (x, y));
let inline = MathScript::default().inside(numerator, None);
assert_eq!(glyph(&Operators, inline), (7001, y));
assert_eq!(glyph(&Joining, display.inside(sup, None)), (x, y));
assert_eq!(
Joining.script_glyph(
f_office_fonts::FontId::from_index(0),
x,
f_office_fonts::ScriptLevel::Script
),
None
);
}
#[test]
fn gives_a_part_of_a_fraction_the_room_of_its_ink_in_a_math_font() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let room_on = |fonts: &dyn crate::Fonts, script: MathScript, display: DisplayFractionRoom| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(display));
let mut shaper = super::Shaper::new(fonts, &theme, &table, &settings);
let face = shaper.face(&math_run(script), true).unwrap();
let face = &shaper.faces[face.0];
(face.size, face.math.room)
};
let room = |fonts: &dyn crate::Fonts, script: MathScript| {
room_on(fonts, script, DisplayFractionRoom::FontLines)
};
let inline = MathScript::default().inside(MathStep::Numerator, None);
let leading = hundredths(150);
assert_eq!(
room(&Operators, inline),
(hundredths(850), MathRoom::Ink { leading })
);
assert_eq!(room(&Joining, inline).1, MathRoom::InkBelow);
let ink = DisplayFractionRoom::Ink;
let display = MathScript::display().inside(MathStep::Numerator, None);
assert_eq!(
room_on(&Operators, display, ink).1,
MathRoom::Ink { leading }
);
let script = MathScript::display()
.inside(MathStep::Denominator, None)
.inside(MathStep::Subscript, None);
assert_eq!(
room_on(&Operators, script, ink).1,
MathRoom::Ink { leading }
);
assert_eq!(room_on(&Joining, display, ink).1, MathRoom::Lines);
assert_eq!(room(&Operators, display).1, MathRoom::Lines);
}
#[test]
fn gives_a_script_of_an_inline_equation_the_room_of_its_lines_and_its_ink_on_a_target_that_asks() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let room = |fonts: &dyn crate::Fonts, script: MathScript, variant: ScriptRoom| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
let mut shaper = super::Shaper::new(fonts, &theme, &table, &settings);
let face = shaper.face(&math_run(script), true).unwrap();
shaper.faces[face.0].math.room
};
let both = MathRoom::LinesAndInk {
leading: hundredths(150),
};
let inline = MathScript::default();
let superscript = inline.inside(MathStep::Superscript, None);
for script in [
superscript,
inline.inside(MathStep::Subscript, None),
inline.inside(MathStep::SuperscriptBesideSubscript, None),
superscript.inside(MathStep::Subscript, None),
MathScript::display().inside(MathStep::Subscript, None),
] {
assert_eq!(
room(&Operators, script, ScriptRoom::Ink),
both,
"{script:?}"
);
assert_eq!(
room(&Operators, script, ScriptRoom::FontLines),
MathRoom::Lines
);
}
let ink = ScriptRoom::Ink;
assert_eq!(room(&Joining, superscript, ink), MathRoom::Lines);
assert_eq!(room(&Operators, inline, ink), MathRoom::Lines);
let in_fraction = inline
.inside(MathStep::Numerator, None)
.inside(MathStep::Superscript, None);
assert_eq!(
room(&Operators, in_fraction, ink),
MathRoom::Ink {
leading: hundredths(150)
}
);
}
#[test]
fn places_the_limits_of_a_display_operator_by_its_ink() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Operators, &theme, &table, &super::ShaperSettings::base());
let mut limit = |step| {
let face = shaper
.face(&math_run(MathScript::display().inside(step, None)), true)
.unwrap();
let face = &shaper.faces[face.0];
(face.size, face.rise, face.math.room)
};
let room = MathRoom::Ink {
leading: hundredths(150),
};
let stacked = Limit {
operator: '\u{2211}',
beside: false,
};
assert_eq!(
limit(MathStep::UpperLimit(stacked)),
(hundredths(850), hundredths(1800), room)
);
assert_eq!(
limit(MathStep::LowerLimit(stacked)),
(hundredths(850), hundredths(-1440), room)
);
let beside = Limit {
beside: true,
..stacked
};
assert_eq!(
limit(MathStep::UpperLimit(beside)),
(hundredths(850), hundredths(1152), room)
);
assert_eq!(
limit(MathStep::LowerLimit(beside)),
(hundredths(850), hundredths(-1080), room)
);
assert_eq!(limit(MathStep::Superscript).2, MathRoom::Lines);
}
#[test]
fn stands_a_delimiter_with_the_middle_of_its_ink_on_the_math_axis() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Operators, &theme, &table, &super::ShaperSettings::base());
let mut rise = |script: MathScript| {
let face = shaper.face(&math_run(script), true).unwrap();
shaper.faces[face.0].rise
};
let inline = MathScript::default();
assert_eq!(rise(inline.on_axis('(')), hundredths(48));
assert_eq!(rise(MathScript::display().on_axis('(')), hundredths(48));
let numerator = MathScript::display().inside(MathStep::Numerator, None);
assert_eq!(rise(numerator), hundredths(912));
assert_eq!(rise(numerator.on_axis('(')), hundredths(960));
assert_eq!(rise(inline.on_axis('x')), Length::ZERO);
assert_eq!(rise(inline), Length::ZERO);
}
#[test]
fn grows_a_delimiter_into_the_first_variant_that_reaches_a_share_of_its_need_or_its_need_less_the_shortfall()
{
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Operators, &theme, &table, &super::ShaperSettings::base());
let face = shaper.face(&math_run(MathScript::display()), true).unwrap();
let leading = hundredths(150);
let mut grow = |need: Length| {
let mut glyph = shaper.glyph(face, '(').unwrap();
let sub_formula = shaper.grow(&mut glyph, (need, Length::ZERO), leading);
let grown = shaper.faces[glyph.face.0];
(
glyph.id,
glyph.advance,
grown.rise,
grown.raised,
grown.math.room,
sub_formula,
)
};
let room = MathRoom::Ink { leading };
assert_eq!(
grow(hundredths(2160)),
(
8000,
hundredths(240),
hundredths(-24),
hundredths(-24),
room,
true
)
);
assert_eq!(grow(hundredths(2340)).0, 8001);
assert_eq!(grow(hundredths(6000)).0, 8001);
assert_eq!(
grow(hundredths(1200)),
(
0x28,
hundredths(120),
hundredths(48),
hundredths(48),
room,
false
)
);
let mut x = shaper.glyph(face, 'x').unwrap();
let before = x;
shaper.grow(&mut x, (hundredths(2400), Length::ZERO), leading);
assert_eq!(x, before);
}
#[test]
fn moves_the_lower_limit_beside_a_display_operator_by_its_italic_correction() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let correction = |fonts: &dyn crate::Fonts, operator| {
let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
let face = shaper.face(&math_run(MathScript::display()), true).unwrap();
shaper.italic_correction(face, operator)
};
assert_eq!(correction(&Operators, '\u{2211}'), hundredths(480));
assert_eq!(correction(&Operators, 'x'), Length::ZERO);
assert_eq!(correction(&Joining, '\u{2211}'), Length::ZERO);
}
struct Slanted;
impl crate::Fonts for Slanted {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
let mut face = Joining.face(family, bold, italic)?;
if family.is("Plain") {
face.font = f_office_fonts::FontId::from_index(1);
}
Some(face)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn italic_correction(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<i32> {
(font.index() == 0 && matches!(char::from_u32(glyph), Some('x' | 'y'))).then_some(300)
}
}
#[test]
fn adds_the_italic_correction_before_another_font_but_not_before_a_script() {
use crate::props::FontRef;
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let mut shaper = super::Shaper::new(&Slanted, &theme, &table, &super::ShaperSettings::base());
let props = RunProps::default();
let mut slanted = Vec::new();
shaper.measure(&props, "x", &mut slanted);
let plain = slanted[0].advance.units();
let text = RunProps {
font_ascii: Some(FontRef::Name("Plain".into())),
font_hansi: Some(FontRef::Name("Plain".into())),
..RunProps::default()
};
let mut after = Vec::new();
shaper.measure(&text, " ", &mut after);
let mut last = slanted[0];
shaper.correct_italic(&mut last, &after[0]);
assert_eq!(last.advance.units(), plain * 4);
let script = RunProps {
size: Some(16),
..RunProps::default()
};
let mut small = Vec::new();
shaper.measure(&script, "=", &mut small);
let mut base = slanted[0];
shaper.correct_italic(&mut base, &small[0]);
assert_eq!(base.advance.units(), plain);
}
#[test]
fn adds_the_italic_correction_of_a_slanted_glyph_before_an_upright_one() {
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let mut shaper = super::Shaper::new(&Slanted, &theme, &table, &super::ShaperSettings::base());
let props = RunProps::default();
let mut glyphs = Vec::new();
shaper.measure(&props, "xy=x", &mut glyphs);
let advances: Vec<i64> = glyphs.iter().map(|g| g.advance.units()).collect();
let plain = advances[0];
assert_eq!(advances, [plain, plain * 4, plain, plain]);
let mut next = Vec::new();
shaper.measure(&props, "=", &mut next);
let mut last = glyphs[3];
shaper.correct_italic(&mut last, &next[0]);
assert_eq!(last.advance.units(), plain * 4);
let mut digit = Vec::new();
shaper.measure(&props, "x2", &mut digit);
assert_eq!(digit[0].advance.units(), plain);
let mut last = glyphs[3];
shaper.correct_italic(&mut last, &digit[1]);
assert_eq!(last.advance.units(), plain * 4);
let mut joined = Vec::new();
super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base()).measure(
&props,
"y=",
&mut joined,
);
assert_eq!(joined[0].advance.units(), plain);
}
#[test]
fn gives_each_character_the_face_slot_of_its_script_and_size() {
use super::{FaceSlot, HintedSet, face_slot};
let plain = (false, None);
let punctuation = (false, Some(HintedSet::Punctuation));
let symbols = (false, Some(HintedSet::Symbols));
let cases = [
('a', false, plain, FaceSlot::Ascii),
('\u{00E9}', false, plain, FaceSlot::Other),
('a', true, plain, FaceSlot::SmallAscii),
('\u{00E9}', true, plain, FaceSlot::SmallOther),
('\u{0628}', false, plain, FaceSlot::Ascii),
('\u{0628}', true, plain, FaceSlot::SmallAscii),
('\u{0628}', false, (true, None), FaceSlot::Complex),
('a', true, (true, None), FaceSlot::Complex),
('\u{4E2D}', true, plain, FaceSlot::EastAsian),
('\u{2019}', false, plain, FaceSlot::Other),
('\u{2019}', false, punctuation, FaceSlot::EastAsian),
('\u{03C9}', false, punctuation, FaceSlot::Other),
('\u{03C9}', false, symbols, FaceSlot::EastAsian),
('\u{0416}', false, symbols, FaceSlot::EastAsian),
('\u{02C7}', false, symbols, FaceSlot::EastAsian),
('\u{2502}', false, symbols, FaceSlot::EastAsian),
('\u{2713}', false, symbols, FaceSlot::EastAsian),
('\u{2019}', false, symbols, FaceSlot::EastAsian),
('\u{2002}', false, symbols, FaceSlot::Other),
('\u{0301}', false, symbols, FaceSlot::Other),
('\u{00E9}', false, symbols, FaceSlot::Other),
];
for (ch, small, context, slot) in cases {
assert_eq!(face_slot(ch, small, context), slot, "{ch:?} small {small}");
}
}
#[test]
fn gives_each_character_its_font_side() {
use super::FontSide::{EastAsian, Open, Other};
use super::font_side;
use super::script::HintedLatin;
let (plain, hint, complex) = (
(false, None),
(false, Some(HintedLatin::Open)),
(true, None),
);
let cases = [
('\u{4E00}', plain, EastAsian),
('\u{FF17}', plain, EastAsian),
('\u{3002}', hint, EastAsian),
('7', plain, Other),
('7', hint, Other),
('k', hint, Other),
('\u{00E9}', plain, Other),
('\u{0101}', plain, Other),
('\u{201C}', plain, Other),
('\u{03B1}', plain, Other),
('\u{00B7}', hint, EastAsian),
('\u{00A7}', hint, EastAsian),
('\u{201C}', hint, EastAsian),
('\u{2026}', hint, EastAsian),
('\u{203B}', hint, EastAsian),
('\u{2192}', hint, EastAsian),
('\u{2460}', hint, EastAsian),
('\u{03B1}', hint, EastAsian),
('\u{0434}', hint, EastAsian),
('\u{00E9}', hint, Open),
('\u{0101}', hint, Open),
('\u{1F00}', hint, Open),
('\u{1F00}', plain, Other),
(' ', plain, Open),
('\u{0628}', plain, Open),
('a', complex, Open),
];
for (ch, (all_complex, hint), side) in cases {
let found = font_side(ch, all_complex, hint, false, |_| true);
assert_eq!(found, side, "{ch:?} {all_complex} {hint:?}");
}
}
#[test]
fn separates_ascii_and_high_ansi_sides_when_latin_slots_differ() {
use super::FontSide::{EastAsian, HighAnsi, Open, Other};
use super::script::{HintLanguage, HintedLatin};
use super::{ascii_hansi_differ, font_side};
use crate::props::{FontRef, RunProps};
let slot_cases = [
(None, None, false),
(Some(FontRef::Name("Times New Roman".into())), None, false),
(Some(FontRef::Name("Calibri".into())), None, true),
(
Some(FontRef::Name("Calibri".into())),
Some(FontRef::Name("calibri".into())),
false,
),
(
Some(FontRef::Name("Calibri".into())),
Some(FontRef::MinorLatin),
true,
),
(Some(FontRef::MinorLatin), Some(FontRef::MinorLatin), false),
(Some(FontRef::MinorLatin), Some(FontRef::MajorLatin), true),
];
for (font_ascii, font_hansi, expected) in slot_cases {
let props = RunProps {
font_ascii,
font_hansi,
..RunProps::default()
};
assert_eq!(ascii_hansi_differ(&props), expected);
}
let hint_other = Some(HintedLatin::ByLanguage(HintLanguage::Other));
let hint_zh = Some(HintedLatin::ByLanguage(HintLanguage::Chinese));
let char_cases = [
('a', false, None, Other),
(' ', false, None, Other),
('\u{2019}', false, None, HighAnsi),
('\u{00E9}', false, None, HighAnsi),
('\u{4E00}', false, None, EastAsian),
('\u{0628}', false, None, Open),
(' ', true, None, Open),
('\u{00E9}', false, hint_other, HighAnsi),
('\u{00E9}', false, hint_zh, EastAsian),
('\u{2019}', false, hint_other, EastAsian),
];
for (ch, all_complex, hint, expected) in char_cases {
assert_eq!(font_side(ch, all_complex, hint, true, |_| true), expected);
}
}
#[test]
fn gives_hinted_latin_characters_the_side_of_their_language() {
use super::FontSide::{EastAsian, Open, Other};
use super::font_side;
use super::script::{HintLanguage, HintedLatin};
let [chinese, set, other] = [
HintLanguage::Chinese,
HintLanguage::ChineseSet,
HintLanguage::Other,
];
let cases = [
('\u{00B0}', [EastAsian, EastAsian, EastAsian]),
('\u{00D7}', [EastAsian, EastAsian, EastAsian]),
('\u{00E9}', [EastAsian, Other, Other]),
('\u{00FC}', [EastAsian, Other, Other]),
('\u{1EA1}', [EastAsian, Other, Other]),
('\u{0101}', [EastAsian, EastAsian, Other]),
('\u{01CE}', [EastAsian, EastAsian, Other]),
('\u{0251}', [EastAsian, EastAsian, Other]),
('\u{00A9}', [Other, Other, Other]),
('\u{00F1}', [Other, Other, Other]),
('\u{00E4}', [Other, Other, Other]),
('\u{1F00}', [Other, Other, Other]),
('\u{00A7}', [EastAsian, EastAsian, EastAsian]),
('\u{03B1}', [EastAsian, EastAsian, EastAsian]),
('\u{4E00}', [EastAsian, EastAsian, EastAsian]),
('k', [Other, Other, Other]),
(' ', [Open, Open, Open]),
];
for (ch, sides) in cases {
for (language, side) in [chinese, set, other].into_iter().zip(sides) {
let hint = Some(HintedLatin::ByLanguage(language));
assert_eq!(
font_side(ch, false, hint, false, |_| true),
side,
"{ch:?} {language:?}"
);
}
}
let hint = Some(HintedLatin::ByLanguage(chinese));
let mut asked = None;
let side = font_side('\u{00E9}', false, hint, false, |side| {
asked = Some(side);
false
});
assert_eq!((side, asked), (Open, Some(EastAsian)));
let side = font_side('\u{00A7}', false, hint, false, |_| false);
assert_eq!(side, EastAsian);
}
#[test]
fn reads_the_hint_language_of_a_run() {
use super::script::HintLanguage;
use crate::props::EastAsianScript;
use crate::styles::EastAsianCharset;
let cases = [
(
Some(EastAsianScript::Simplified),
None,
HintLanguage::Chinese,
),
(
Some(EastAsianScript::Traditional),
Some(EastAsianCharset::ShiftJis),
HintLanguage::Chinese,
),
(
Some(EastAsianScript::Japanese),
Some(EastAsianCharset::Gb2312),
HintLanguage::ChineseSet,
),
(None, Some(EastAsianCharset::Big5), HintLanguage::ChineseSet),
(None, Some(EastAsianCharset::ShiftJis), HintLanguage::Other),
(Some(EastAsianScript::Korean), None, HintLanguage::Other),
(None, None, HintLanguage::Other),
];
for (script, charset, language) in cases {
assert_eq!(
HintLanguage::of(script, charset),
language,
"{script:?} {charset:?}"
);
}
}
struct Lacking(&'static [&'static str], &'static [char]);
impl crate::Fonts for Lacking {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Only(self.0).face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
if font.index() == 0 && self.1.contains(&ch) {
return None;
}
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
}
#[test]
fn asks_the_face_of_the_side_for_a_hinted_letter() {
use super::FontSide::{EastAsian, Open, Other};
use crate::props::{EastAsianScript, FontRef};
use crate::quirks::HintedFontSide;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let run = |script| RunProps {
font_ascii: Some(FontRef::Name("Latin".into())),
font_hansi: Some(FontRef::Name("Latin".into())),
font_east_asia: Some(Box::new(FontRef::Name("East".into()))),
east_asian_hint: Some(true),
east_asian_language: Some(crate::props::EastAsianLanguage::Script(script)),
..RunProps::default()
};
let sides = |fonts: &Lacking, script, variant| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
let mut shaper = super::Shaper::new(fonts, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&run(script), "\u{4E00}\u{00E9}\u{4E8C}", &mut glyphs);
glyphs.iter().map(|g| g.side).collect::<Vec<_>>()
};
let (chinese, japanese) = (EastAsianScript::Simplified, EastAsianScript::Japanese);
let by_language = HintedFontSide::ByLanguage;
let full = Lacking(&["East", "Latin"], &[]);
assert_eq!(
sides(&full, chinese, by_language),
[EastAsian, EastAsian, EastAsian]
);
assert_eq!(
sides(&full, japanese, by_language),
[EastAsian, Other, EastAsian]
);
let lacking = Lacking(&["East", "Latin"], &['\u{00E9}']);
assert_eq!(
sides(&lacking, chinese, by_language),
[EastAsian, Open, EastAsian]
);
assert_eq!(
sides(&lacking, japanese, by_language),
[EastAsian, Other, EastAsian]
);
let latin_lacking = Lacking(&["Latin", "East"], &['\u{00E9}']);
assert_eq!(
sides(&latin_lacking, japanese, by_language),
[EastAsian, Open, EastAsian]
);
assert_eq!(
sides(&full, chinese, HintedFontSide::Open),
[EastAsian, Open, EastAsian]
);
}
struct TwoTables;
impl crate::Fonts for TwoTables {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn kerning(
&self,
_font: f_office_fonts::FontId,
_left: u32,
_right: u32,
table: crate::KerningTable,
) -> i32 {
match table {
crate::KerningTable::FaceSource => -20,
crate::KerningTable::KernTable => -50,
}
}
}
#[test]
fn kerns_by_the_kern_table_before_mode_15_where_the_target_does() {
use crate::mode::{CompatibilityMode, ModeRules};
use crate::quirks::KerningTableRead::{FaceSource, KernTableBeforeMode};
let units = |read, value, open_type| {
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let rules = ModeRules::of(CompatibilityMode::read(value));
let settings = super::ShaperSettings {
mode_rules: rules.with_open_type_features(open_type),
..super::ShaperSettings::base_with(|p| p.with_variant(read))
};
let shaper = super::Shaper::new(&TwoTables, &theme, &table, &settings);
let metrics = crate::FaceMetrics::default();
let face = plain_face(metrics, Length::from_units(1000), LineHeight::TakesHheaLine);
shaper.kerning_units(&face, 1, 2)
};
let cases = [
(None, false, -50),
(Some(12), false, -50),
(Some(14), false, -50),
(Some(14), true, -20),
(None, true, -20),
(Some(15), false, -20),
(Some(16), true, -20),
];
for (value, open_type, kerning) in cases {
assert_eq!(units(KernTableBeforeMode, value, open_type), kerning);
assert_eq!(units(FaceSource, value, open_type), -20);
}
}
struct Styled;
impl Styled {
const FAMILIES: [&'static str; 2] = ["Serif", "Sans"];
}
impl crate::Fonts for Styled {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
let index = Self::FAMILIES.iter().position(|name| family.is(name))?;
let index = u32::try_from(4 * index).ok()? + 2 * u32::from(italic) + u32::from(bold);
let font = f_office_fonts::FontId::from_index(index);
Joining
.face(family, false, false)
.map(|chosen| crate::ChosenFace { font, ..chosen })
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
let (sans, italic) = (font.index() >= 4, font.index() % 4 >= 2);
let missing = match ch {
'\u{590}'..='\u{5FF}' => italic && sans,
'\u{600}'..='\u{6FF}' => italic,
_ => false,
};
(!missing).then(|| u32::from(ch))
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
let index = usize::try_from(font.index() / 4).ok()?;
Self::FAMILIES.get(index).map(|name| (*name).to_owned())
}
}
#[test]
fn an_italic_complex_run_takes_the_upright_face_where_its_italic_face_lacks_the_language_script() {
use crate::props::{BidiScript, FontRef};
use crate::quirks::ComplexItalicFace::{Italic, UprightForLanguage};
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let font = |family: &str, bold: bool, language: Option<BidiScript>, quirk| {
let props = RunProps {
font_cs: Some(Box::new(FontRef::Name(family.into()))),
bold_cs: Some(bold),
italic_cs: Some(true),
bidi_script: language,
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| p.with_variant(quirk));
let mut shaper = super::Shaper::new(&Styled, &theme, &table, &settings);
let face = shaper.complex_face(&props).unwrap();
let face = shaper.faces[face.0];
let upright = face.font.index() % 4 < 2;
assert_eq!(face.standing.synthetic_italic, upright, "{family} {bold}");
face.font.index()
};
assert_eq!(font("Serif", false, None, UprightForLanguage), 0);
assert_eq!(font("Serif", true, None, UprightForLanguage), 1);
assert_eq!(
font("Serif", false, Some(BidiScript::Other), UprightForLanguage),
0
);
assert_eq!(
font("Serif", false, Some(BidiScript::Hebrew), UprightForLanguage),
2
);
assert_eq!(font("Sans", false, None, UprightForLanguage), 6);
assert_eq!(font("Serif", true, None, Italic), 3);
}
struct UprightOnly;
impl crate::Fonts for UprightOnly {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining
.face(family, bold, italic)
.map(|chosen| crate::ChosenFace {
synthetic_italic: italic,
..chosen
})
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
}
#[test]
fn text_of_an_equation_asks_for_the_upright_face() {
use crate::props::FontRef;
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let synthetic = |math: Option<bool>| {
let props = RunProps {
font_ascii: Some(FontRef::Name("Cambria Math".into())),
italic: Some(true),
math,
..RunProps::default()
};
let mut shaper =
super::Shaper::new(&UprightOnly, &theme, &table, &super::ShaperSettings::base());
let face = shaper.face(&props, true).unwrap();
shaper.faces[face.0].standing.synthetic_italic
};
assert!(synthetic(None));
assert!(!synthetic(Some(true)));
}
#[test]
fn math_run_uses_own_non_cambria_font_for_supported_alphanumerics_only() {
use crate::props::FontRef;
struct MathAndCalibri;
impl crate::Fonts for MathAndCalibri {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
let index = match (family.as_str(), bold, italic) {
("Cambria Math", false, false) => 1,
("Calibri", false, true) => 2,
("Calibri", false, false) => 3,
_ => return None,
};
let id = f_office_fonts::FontId::from_index(index);
let metrics = if index == 1 {
crate::FaceMetrics {
units_per_em: 2048,
hhea_ascender: 1950,
hhea_descender: -450,
descent: 450,
line_top: 1950,
script_top: 1950,
..crate::FaceMetrics::default()
}
} else {
crate::FaceMetrics {
units_per_em: 2048,
hhea_ascender: 2100,
hhea_descender: -600,
descent: 600,
line_top: 2100,
script_top: 2100,
..crate::FaceMetrics::default()
}
};
Some(crate::ChosenFace {
font: id,
metrics,
synthetic_bold: false,
synthetic_italic: false,
stands_in: false,
})
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
if font.index() == 1 {
return Some(u32::from(ch));
}
(ch.is_ascii_digit() || ch == '+').then_some(u32::from(ch))
}
fn advance(&self, _font: f_office_fonts::FontId, _glyph: u32) -> Option<u16> {
Some(1000)
}
}
let theme = crate::styles::Theme::default();
let table = crate::styles::FontTable::default();
let props = RunProps {
font_ascii: Some(FontRef::Name("Calibri".into())),
font_hansi: Some(FontRef::Name("Calibri".into())),
italic: Some(true),
math: Some(true),
size: Some(32),
..RunProps::default()
};
let mut shaper = super::Shaper::new(
&MathAndCalibri,
&theme,
&table,
&super::ShaperSettings::base(),
);
let mut glyphs = Vec::new();
shaper.measure(&props, "\u{1D465}1+", &mut glyphs);
assert_eq!(glyphs.len(), 3);
assert_eq!(shaper.faces[glyphs[0].face.0].font.index(), 1);
assert_eq!(shaper.faces[glyphs[1].face.0].font.index(), 2);
assert_eq!(shaper.faces[glyphs[2].face.0].font.index(), 1);
assert_eq!(shaper.faces[glyphs[1].face.0].metrics.line_top, 1950);
assert_eq!(shaper.faces[glyphs[1].face.0].metrics.descent, 450);
}
struct NamedWithoutDevanagari(&'static [&'static str]);
impl crate::Fonts for NamedWithoutDevanagari {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Only(self.0).face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
if font.index() == 0 && ('\u{0900}'..='\u{097F}').contains(&ch) {
return None;
}
Only(self.0).glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Only(self.0).advance(font, glyph)
}
fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
let index = usize::try_from(font.index()).ok()?;
self.0.get(index).map(|name| (*name).to_owned())
}
}
#[test]
fn draws_a_devanagari_digit_of_a_label_that_its_font_lacks_with_mangal() {
use crate::props::FontRef;
use crate::quirks::SubstituteFaces;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let fonts = NamedWithoutDevanagari(&["Tahoma", "Nirmala UI", "Mangal"]);
let tahoma = Some(FontRef::Name("Tahoma".into()));
let props = RunProps {
font_ascii: tahoma.clone(),
font_hansi: tahoma.clone(),
font_cs: tahoma.map(Box::new),
..RunProps::default()
};
let settings = super::ShaperSettings::base_with(|p| p.with_variant(SubstituteFaces::ByBlock));
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let mut drawn = |label: bool| {
let mut glyphs = Vec::new();
if label {
shaper.measure_label(&props, "\u{0967}.", &mut glyphs);
} else {
shaper.measure(&props, "\u{0967}.", &mut glyphs);
}
glyphs
.iter()
.map(|g| shaper.faces[g.face.0].font.index())
.collect::<Vec<_>>()
};
assert_eq!(drawn(false), [1, 0]);
assert_eq!(drawn(true), [2, 0]);
}
struct NamedWithoutFixedSpaces(&'static [&'static str]);
impl crate::Fonts for NamedWithoutFixedSpaces {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Only(self.0).face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
if font.index() == 0 && matches!(ch, '\u{2002}' | '\u{2003}') {
return None;
}
Only(self.0).glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Only(self.0).advance(font, glyph)
}
fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
let index = usize::try_from(font.index()).ok()?;
self.0.get(index).map(|name| (*name).to_owned())
}
}
#[test]
fn keeps_an_en_space_in_its_own_face_in_a_text_form_field() {
use super::LineSizing;
use crate::props::FontRef;
use crate::quirks::SubstituteFaces;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let fonts = NamedWithoutFixedSpaces(&[
"Arial Narrow",
"Arial",
"Times New Roman",
"Courier New",
"Cambria Math",
]);
let narrow = Some(FontRef::Name("Arial Narrow".into()));
let settings = super::ShaperSettings::base_with(|p| p.with_variant(SubstituteFaces::ByBlock));
let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
let mut drawn = |form_text: Option<bool>| {
let props = RunProps {
font_ascii: narrow.clone(),
font_hansi: narrow.clone(),
form_text,
..RunProps::default()
};
let mut glyphs = Vec::new();
shaper.measure(&props, "\u{2002}", &mut glyphs);
let glyph = glyphs.first().unwrap();
(shaper.faces[glyph.face.0].font.index(), glyph.sizing)
};
let (font, sizing) = drawn(None);
assert_ne!(font, 0);
assert_eq!(sizing, LineSizing::Nothing);
assert_eq!(drawn(Some(true)), (0, LineSizing::ByFace));
}
struct Vdmx13;
impl crate::Fonts for Vdmx13 {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Joining.glyph(font, ch)
}
fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Joining.advance(font, glyph)
}
fn device_heights(&self, _font: f_office_fonts::FontId, pels: u16) -> Option<(i16, i16)> {
(pels == 13).then_some((12, -4))
}
}
#[test]
fn gives_whole_pixel_heights_from_the_vdmx_table_or_else_rounded_from_the_win_heights() {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let mut shaper = super::Shaper::new(&Vdmx13, &theme, &table, &super::ShaperSettings::base());
let face = shaper.face(&RunProps::default(), true).unwrap();
assert_eq!(shaper.whole_pixel_heights(face, 13), Some((12, 4)));
assert_eq!(shaper.whole_pixel_heights(face, 14), Some((11, 3)));
}
#[test]
fn the_exact_edge_check_cuts_each_advance_to_whole_parts_of_a_point() {
let size = Length::from_points(11).unwrap().units();
let point = Length::UNITS_PER_POINT;
let exact =
super::ShaperSettings::base_with(|p| p.with_variant(crate::quirks::GlyphEdgeCheck::Exact));
assert_eq!(
exact.counted_advance((556 * size, 1_000)),
(25_051 * point, 4_096)
);
let whole = exact.counted_advance((1_139 * size, 2_048));
assert_eq!(whole, (25_058 * point, 4_096));
assert_eq!(whole.0 * 2_048, 1_139 * size * whole.1);
let tied = super::ShaperSettings::base_with(|p| {
p.with_variant(crate::quirks::GlyphEdgeCheck::RoundedWithTie)
});
assert_eq!(
tied.counted_advance((556 * size, 1_000)),
(556 * size, 1_000)
);
}
struct Dashes;
impl crate::Fonts for Dashes {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
Joining.face(family, bold, italic)
}
fn glyph(&self, _font: f_office_fonts::FontId, ch: char) -> Option<u32> {
Some(u32::from(ch))
}
fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
Some(match char::from_u32(glyph) {
Some(' ') => 440,
Some('\u{00A0}') => 480,
Some('\u{2002}') => 500,
Some('\u{2013}') => 498,
Some('\u{2003}') => 1_000,
Some('\u{2014}') => 900,
_ => 100,
})
}
}
#[test]
fn lays_out_en_and_em_spaces_with_their_dashes_widths_where_the_target_does() {
use crate::quirks::FixedSpaceWidths;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let measured = |widths: FixedSpaceWidths| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(widths));
let mut shaper = super::Shaper::new(&Dashes, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(
&RunProps::default(),
"\u{2002}\u{2013}\u{2003}\u{2014}",
&mut glyphs,
);
glyphs
.iter()
.map(|g| (g.advance, g.kerning))
.collect::<Vec<_>>()
};
let own = measured(FixedSpaceWidths::OwnGlyphs);
let dashes = measured(FixedSpaceWidths::DashWidths);
assert_ne!(own[0].0, own[1].0);
assert_ne!(own[2].0, own[3].0);
assert_eq!(dashes[0], dashes[1]);
assert_eq!(dashes[2], dashes[3]);
assert_eq!(dashes[0].1, Length::ZERO);
assert_eq!(&dashes[1..2], &own[1..2]);
}
#[test]
fn lays_out_no_break_space_with_plain_space_width_where_the_target_does() {
use crate::quirks::FixedSpaceWidths;
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let measured = |widths: FixedSpaceWidths| {
let settings = super::ShaperSettings::base_with(|p| p.with_variant(widths));
let mut shaper = super::Shaper::new(&Dashes, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(&RunProps::default(), "\u{00A0} ", &mut glyphs);
glyphs
.iter()
.map(|g| (g.ch, g.advance, g.kerning))
.collect::<Vec<_>>()
};
let own = measured(FixedSpaceWidths::OwnGlyphs);
let dashes = measured(FixedSpaceWidths::DashWidths);
assert_ne!(own[0].1, own[1].1);
assert_eq!(dashes[0].0, '\u{00A0}');
assert_eq!(dashes[0].1, dashes[1].1);
assert_eq!(dashes[0].2, Length::ZERO);
}
#[test]
fn resolves_an_east_asian_theme_font_without_typeface_by_the_language_of_the_variant() {
use crate::props::{EastAsianScript, FontRef};
use crate::quirks::ThemeEastAsian;
let theme = crate::styles::Theme {
scripts: crate::styles::MinorMajor {
minor: vec![
("Jpan".into(), "Jpan Face".into()),
("Hans".into(), "Hans Face".into()),
],
major: Vec::new(),
},
..crate::styles::Theme::default()
};
let table = crate::styles::FontTable::default();
let fonts = Only(&["Latin"]);
let family = |variant, settings_script| {
let settings = super::ShaperSettings {
east_asian_script: settings_script,
..super::ShaperSettings::base_with(|p| p.with_variant(variant))
};
let shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
shaper
.theme_family(&FontRef::MinorEastAsia, Some(EastAsianScript::Japanese))
.map(str::to_owned)
};
let simplified = Some(EastAsianScript::Simplified);
assert_eq!(
family(ThemeEastAsian::RunLanguage, simplified).as_deref(),
Some("Jpan Face")
);
assert_eq!(
family(ThemeEastAsian::SettingsLanguage, simplified).as_deref(),
Some("Hans Face")
);
assert_eq!(
family(ThemeEastAsian::SettingsLanguage, None).as_deref(),
Some("MS Mincho")
);
}
#[test]
fn legacy_text_offset_rounds_to_shadow_box_steps() {
let pt = |n, d| Length::from_units(f_office_units::div_round(n * Length::UNITS_PER_POINT, d));
assert_eq!(
super::legacy_offset(Length::from_points(12).unwrap()),
pt(48, 100)
);
assert_eq!(
super::legacy_offset(Length::from_points(24).unwrap()),
pt(96, 100)
);
assert_eq!(
super::legacy_offset(Length::from_points(48).unwrap()),
pt(204, 100)
);
assert_eq!(super::legacy_offset(Length::ZERO), pt(12, 100));
}
fn measure_legacy_face(
variant: crate::quirks::TextShadows,
props: &RunProps,
) -> (super::Face, (bool, bool, bool, bool)) {
let (theme, table) = (
crate::styles::Theme::default(),
crate::styles::FontTable::default(),
);
let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
let mut glyphs = Vec::new();
shaper.measure(props, "A", &mut glyphs);
let face = *shaper.faces().get(glyphs[0].face).unwrap();
let drawn = shaper.draws_text_effects(props);
(face, drawn)
}
#[test]
fn draws_legacy_shadow_when_text_shadows_scale() {
use crate::props::Color;
use crate::quirks::TextShadows;
let base_props = RunProps {
size: Some(48),
color: Some(Color::Rgb([0xC0, 0x00, 0x00])),
..RunProps::default()
};
let (base_face, base_drawn) = measure_legacy_face(
TextShadows::Unknown,
&RunProps {
legacy_shadow: Some(true),
legacy_outline: Some(true),
..base_props.clone()
},
);
assert_eq!(
(
base_face.shadow,
base_face.outline,
base_face.text_fill,
base_drawn.3
),
(None, None, super::DrawnTextFill::Solid, false)
);
let (shadow_face, shadow_drawn) = measure_legacy_face(
TextShadows::Scaled,
&RunProps {
legacy_shadow: Some(true),
..base_props
},
);
let offset = super::legacy_offset(Length::from_points(24).unwrap());
assert_eq!(
shadow_face.shadow,
Some(super::DrawnShadow {
across: offset,
down: offset,
color: Rgb {
r: 192,
g: 192,
b: 192,
},
form: super::ShadowForm::Paths,
})
);
assert!(shadow_drawn.3);
}
#[test]
fn draws_legacy_outline_when_text_shadows_scale() {
use crate::props::Color;
use crate::quirks::TextShadows;
let base_props = RunProps {
size: Some(48),
color: Some(Color::Rgb([0xC0, 0x00, 0x00])),
..RunProps::default()
};
let (outline_face, _) = measure_legacy_face(
TextShadows::Scaled,
&RunProps {
legacy_outline: Some(true),
..base_props.clone()
},
);
assert_eq!(
(outline_face.outline, outline_face.text_fill),
(
Some(f_office_paint::Outline {
width: crate::params::LEGACY_TEXT_OUTLINE_WIDTH,
color: Rgb {
r: 0xC0,
g: 0x00,
b: 0x00,
},
join: f_office_paint::Join::Round,
}),
super::DrawnTextFill::None,
)
);
let (both_face, _) = measure_legacy_face(
TextShadows::Scaled,
&RunProps {
legacy_outline: Some(true),
legacy_shadow: Some(true),
..base_props
},
);
assert_eq!(both_face.text_fill, super::DrawnTextFill::White);
}
#[test]
fn draws_legacy_emboss_and_imprint_when_text_shadows_scale() {
use crate::quirks::TextShadows;
let base_props = RunProps {
size: Some(48),
..RunProps::default()
};
let (emboss_face, _) = measure_legacy_face(
TextShadows::Scaled,
&RunProps {
emboss: Some(true),
legacy_shadow: Some(true),
legacy_outline: Some(true),
..base_props.clone()
},
);
assert_eq!(emboss_face.relief, Some(super::TextRelief::Emboss));
assert_eq!(emboss_face.shadow, None);
assert_eq!(emboss_face.outline, None);
let (imprint_face, _) = measure_legacy_face(
TextShadows::Scaled,
&RunProps {
imprint: Some(true),
..base_props
},
);
assert_eq!(imprint_face.relief, Some(super::TextRelief::Imprint));
}
#[test]
fn draws_text_reflection_and_expands_descent_when_text_shadows_scale() {
use crate::props::TextReflection;
use crate::quirks::TextShadows;
let refl = TextReflection {
blur: Length::from_points(4).unwrap(),
distance: Length::from_points(4).unwrap(),
start_alpha: 50_000,
start_pos: 0,
end_alpha: 0,
end_pos: 50_000,
downward: true,
};
let props = RunProps {
size: Some(56),
reflection: Some(Box::new(refl)),
..RunProps::default()
};
let (base_face, base_drawn) = measure_legacy_face(TextShadows::Unknown, &props);
assert_eq!(
(base_face.reflection, base_face.shadow_room, base_drawn.2),
(None, super::ShadowRoom::default(), false)
);
let (scaled_face, scaled_drawn) = measure_legacy_face(TextShadows::Scaled, &props);
let drawn = scaled_face.reflection.expect("reflection drawn");
assert!(scaled_drawn.2);
assert!(drawn.pivot > Length::ZERO && drawn.blur > Length::ZERO);
assert_eq!(scaled_face.shadow_room.above, Length::ZERO);
assert!(scaled_face.shadow_room.below > Length::ZERO);
}
#[test]
fn east_asian_stand_in_rounds_line_room_whole_line_and_bold_unit_on_target_em_grid() {
use crate::quirks::{LineHeight, SyntheticBoldWidth};
use crate::text::decisions::{ShaperSettings, SingleLine};
let size = Length::from_points(11).unwrap();
let single = SingleLine::of(LineHeight::TakesHheaLine);
let make_face = |metrics: crate::FaceMetrics| super::Face {
font: f_office_fonts::FontId::from_index(0),
metrics,
size,
line_size: size,
single_line: single,
color: f_office_paint::Rgb::BLACK,
lines: super::RunLines::default(),
background: None,
rise: Length::ZERO,
raised: Length::ZERO,
math: super::MathFace::default(),
outline: None,
text_fill: super::DrawnTextFill::Solid,
effect: false,
shadow_room: super::ShadowRoom::default(),
shadow: None,
glow: None,
reflection: None,
relief: None,
kerned: false,
east_asian_script: None,
ligatures: false,
standing: super::Standing {
synthetic_bold: true,
synthetic_italic: false,
font: true,
},
scale: None,
border: super::RunBorder::default(),
};
for (target_em, ascent, descent, scale) in [
(256_u16, 224_u16, 32_u16, 8_u16),
(1024_u16, 896_u16, 128_u16, 2_u16),
] {
let asc_i = i16::try_from(ascent).unwrap();
let desc_i = i16::try_from(descent).unwrap();
let scale_i = i16::try_from(scale).unwrap();
let native = make_face(crate::FaceMetrics {
units_per_em: target_em,
hhea_ascender: asc_i,
hhea_descender: -desc_i,
descent,
line_top: ascent,
script_top: ascent,
east_asian: true,
..crate::FaceMetrics::default()
});
let stand_in = make_face(crate::FaceMetrics {
units_per_em: 2048,
hhea_ascender: asc_i * scale_i,
hhea_descender: -desc_i * scale_i,
descent: descent * scale,
line_top: ascent * scale,
script_top: ascent * scale,
east_asian: true,
target_units_per_em: Some(target_em),
..crate::FaceMetrics::default()
});
assert_eq!(
stand_in.line_height(),
native.line_height(),
"upem={target_em}"
);
assert_eq!(stand_in.descent(), native.descent(), "upem={target_em}");
assert_eq!(stand_in.whole_line(), None, "upem={target_em}");
assert_eq!(native.whole_line(), None, "upem={target_em}");
let settings = ShaperSettings::of(
&crate::Settings::default(),
&crate::profile::Profile::base()
.with_variant(SyntheticBoldWidth::CountsAFontUnit)
.quirks(),
crate::grid::Device::per_inch(600).unwrap().dot_size(),
);
assert_eq!(
settings.bold_counted_unit(
size.units(),
i64::from(stand_in.metrics.layout_units_per_em())
),
Some((size.units(), i64::from(target_em)))
);
}
}