use ttf_parser::{Face, Tag};
const BOLD_THRESHOLD: u16 = 600;
pub(crate) const OBLIQUE_SHEAR: f32 = 0.2;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct FaceSynthesis {
weight: u16,
axis_max: Option<f32>,
slanted: bool,
slant_axis: bool,
}
impl FaceSynthesis {
pub(crate) fn read(font_data: &[u8], face_index: u32) -> Self {
match Face::parse(font_data, face_index) {
Ok(face) => {
let axis = |tag: &[u8; 4]| {
face.variation_axes()
.into_iter()
.find(|axis| axis.tag == Tag::from_bytes(tag))
};
Self {
weight: face.weight().to_number(),
axis_max: axis(b"wght").map(|axis| axis.max_value),
slanted: face.is_italic()
|| face.is_oblique()
|| face.italic_angle().abs() > f32::EPSILON,
slant_axis: axis(b"slnt").is_some() || axis(b"ital").is_some(),
}
}
Err(_) => Self {
weight: 1000,
axis_max: None,
slanted: true,
slant_axis: false,
},
}
}
pub(crate) fn synthesizes_bold(self, requested_weight: u16) -> bool {
requested_weight >= BOLD_THRESHOLD
&& self.weight < BOLD_THRESHOLD
&& self
.axis_max
.is_none_or(|max| max < f32::from(BOLD_THRESHOLD))
}
pub(crate) fn synthesizes_oblique(self, italic_requested: bool) -> bool {
italic_requested && !self.slanted && !self.slant_axis
}
}
pub(crate) fn embolden_strength(size_px: f32) -> f32 {
size_px / 24.0
}
#[cfg(test)]
mod tests {
use super::*;
const REGULAR_CJK: &[u8] = include_bytes!("../../test-fonts/NotoSansCJKjp-NoNi-subset.otf");
const BOLD_CJK: &[u8] = include_bytes!("../../test-fonts/NotoSansCJKjp-Bold-NoNi-subset.otf");
const VARIABLE: &[u8] = include_bytes!("../../test-fonts/NotoSans-Variable.ttf");
const ITALIC: &[u8] = include_bytes!("../../test-fonts/NotoSans-Italic-subset.ttf");
fn of(font: &[u8]) -> FaceSynthesis {
FaceSynthesis::read(font, 0)
}
#[test]
fn a_regular_face_asked_for_bold_is_emboldened() {
assert!(of(REGULAR_CJK).synthesizes_bold(700));
assert!(of(REGULAR_CJK).synthesizes_bold(600));
assert!(!of(REGULAR_CJK).synthesizes_bold(400));
assert!(!of(REGULAR_CJK).synthesizes_bold(500));
}
#[test]
fn a_bold_face_or_a_weight_axis_draws_bold_for_real() {
assert!(!of(BOLD_CJK).synthesizes_bold(700));
assert!(!of(VARIABLE).synthesizes_bold(700));
}
#[test]
fn an_upright_face_asked_for_italic_is_slanted() {
assert!(of(REGULAR_CJK).synthesizes_oblique(true));
assert!(!of(REGULAR_CJK).synthesizes_oblique(false));
}
#[test]
fn an_italic_face_is_not_slanted_again() {
assert!(!of(ITALIC).synthesizes_oblique(true));
}
}