use crate::draw::FontDef;
#[derive(Debug, Clone, PartialEq)]
pub enum FontFace {
SkinFile {
font: FontDef,
fake_bold: bool,
},
StandIn {
family: &'static str,
bold: bool,
},
Default {
fake_bold: bool,
},
}
const STAND_INS: [(&str, &str); 2] = [
("tahoma", "DejaVuSansCondensed"),
("arial", "LiberationSans"),
];
impl FontFace {
pub fn of(font: Option<&FontDef>, bold: bool) -> FontFace {
let Some(font) = font else {
return FontFace::Default { fake_bold: bold };
};
if font.file.is_empty() {
if let Some((_, family)) = STAND_INS.iter().find(|(id, _)| *id == &*font.id) {
return FontFace::StandIn { family, bold };
}
}
FontFace::SkinFile {
font: font.clone(),
fake_bold: bold,
}
}
pub fn file(&self) -> Option<String> {
match self {
FontFace::StandIn { family, bold } => Some(format!(
"fonts/{family}{}.ttf",
if *bold { "-Bold" } else { "" }
)),
_ => None,
}
}
}
pub fn em_size(fontsize: i32) -> f32 {
(fontsize as f32 * 0.75).round()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GdiLineMetrics {
units_per_em: i32,
win_ascent: i32,
win_descent: i32,
sizes: Vec<(u16, i16, i16)>,
other_vdmx: bool,
}
impl GdiLineMetrics {
pub fn at(&self, px: f32) -> (i32, i32) {
let scale = |units: i32| units as f32 * px / self.units_per_em as f32;
(
scale(self.win_ascent).ceil() as i32,
scale(self.win_descent).ceil() as i32,
)
}
pub fn measured(&self, px: f32) -> Option<(i32, i32)> {
let ppem = px.round() as u16;
if let Some(&(_, high, low)) = self.sizes.iter().find(|s| s.0 == ppem) {
return Some((i32::from(high), -i32::from(low)));
}
self.other_vdmx.then(|| {
let scale = |units: i32| units as f32 * px / self.units_per_em as f32;
(
scale(self.win_ascent).round() as i32,
scale(self.win_descent).round() as i32,
)
})
}
pub fn read(bytes: &[u8]) -> Option<GdiLineMetrics> {
let u16_at = |o: usize| -> i32 {
if o + 2 <= bytes.len() {
((bytes[o] as i32) << 8) | bytes[o + 1] as i32
} else {
-1
}
};
let u32_at = |o: usize| -> i64 { ((u16_at(o) as i64) << 16) | u16_at(o + 2) as i64 };
let tables = u16_at(4);
if tables <= 0 {
return None;
}
let mut head: i64 = -1;
let mut os2: i64 = -1;
let mut vdmx: i64 = -1;
for i in 0..tables as usize {
let rec = 12 + i * 16;
if rec + 16 > bytes.len() {
break;
}
let tag = &bytes[rec..rec + 4];
let offset = u32_at(rec + 8);
match tag {
b"head" => head = offset,
b"OS/2" => os2 = offset,
b"VDMX" => vdmx = offset,
_ => {}
}
}
if head < 0 || os2 < 0 {
return None;
}
let upem = u16_at(head as usize + 18);
let ascent = u16_at(os2 as usize + 74);
let descent = u16_at(os2 as usize + 76);
if upem <= 0 || ascent < 0 || descent < 0 {
None
} else {
let (sizes, other_vdmx) = if vdmx < 0 {
(Vec::new(), false)
} else {
read_vdmx(bytes, vdmx as usize)
};
Some(GdiLineMetrics {
units_per_em: upem,
win_ascent: ascent,
win_descent: descent,
sizes,
other_vdmx,
})
}
}
}
fn read_vdmx(bytes: &[u8], at: usize) -> (Vec<(u16, i16, i16)>, bool) {
let u8_at = |o: usize| bytes.get(o).copied();
let u16_at = |o: usize| Some(u16::from_be_bytes([u8_at(o)?, u8_at(o + 1)?]));
let Some(ratios) = u16_at(at + 4) else {
return (Vec::new(), false);
};
for i in 0..ratios as usize {
let rec = at + 6 + 4 * i;
let (Some(charset), Some(x), Some(start), Some(end)) =
(u8_at(rec), u8_at(rec + 1), u8_at(rec + 2), u8_at(rec + 3))
else {
break;
};
let square = x == 0 || (start <= x && x <= end);
if charset != 1 || !square {
continue;
}
let Some(offset) = u16_at(at + 6 + 4 * ratios as usize + 2 * i) else {
break;
};
let group = at + offset as usize;
let count = u16_at(group).unwrap_or(0) as usize;
let sizes = (0..count)
.map_while(|k| {
let r = group + 4 + 6 * k;
Some((u16_at(r)?, u16_at(r + 2)? as i16, u16_at(r + 4)? as i16))
})
.collect();
return (sizes, false);
}
(Vec::new(), ratios > 0)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) type VdmxSize = (u16, i16, i16);
pub(crate) fn font_with(vdmx: Option<(u8, &[VdmxSize])>) -> Vec<u8> {
let mut head = vec![0u8; 54];
head[18..20].copy_from_slice(&2048u16.to_be_bytes());
let mut os2 = vec![0u8; 78];
os2[74..76].copy_from_slice(&1854u16.to_be_bytes());
os2[76..78].copy_from_slice(&434u16.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> = vec![(b"head", head), (b"OS/2", os2)];
if let Some((charset, sizes)) = vdmx {
let mut t = Vec::new();
t.extend_from_slice(&1u16.to_be_bytes()); t.extend_from_slice(&1u16.to_be_bytes()); t.extend_from_slice(&1u16.to_be_bytes()); t.extend_from_slice(&[charset, 1, 1, 1]);
t.extend_from_slice(&12u16.to_be_bytes()); t.extend_from_slice(&(sizes.len() as u16).to_be_bytes());
t.extend_from_slice(&[0, 255]);
for &(ppem, high, low) in sizes {
t.extend_from_slice(&ppem.to_be_bytes());
t.extend_from_slice(&high.to_be_bytes());
t.extend_from_slice(&low.to_be_bytes());
}
tables.push((b"VDMX", t));
}
let mut out = vec![0u8; 12 + 16 * tables.len()];
out[4..6].copy_from_slice(&(tables.len() as u16).to_be_bytes());
for (i, (tag, data)) in tables.iter().enumerate() {
let rec = 12 + 16 * i;
let offset = out.len() as u32;
out[rec..rec + 4].copy_from_slice(*tag);
out[rec + 8..rec + 12].copy_from_slice(&offset.to_be_bytes());
out[rec + 12..rec + 16].copy_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(data);
}
out
}
#[test]
fn the_line_rounds_up_without_a_vdmx_table() {
let m = GdiLineMetrics::read(&font_with(None)).expect("a line");
assert_eq!(m.at(18.0), (17, 4));
assert_eq!(m.at(24.0), (22, 6));
assert_eq!(m.measured(18.0), None);
}
#[test]
fn a_vdmx_group_for_windows_characters_gives_the_measured_line() {
let m = GdiLineMetrics::read(&font_with(Some((1, &[(18, 17, -4), (24, 21, -6)]))))
.expect("a line");
assert_eq!(m.measured(24.0), Some((21, 6)));
assert_eq!(m.measured(18.0), Some((17, 4)));
assert_eq!(m.measured(12.0), None, "a size the table leaves out");
assert_eq!(m.at(24.0), (22, 6), "the rounded-up line stays as it was");
}
#[test]
fn a_vdmx_table_only_for_all_characters_rounds_the_measured_line() {
let m = GdiLineMetrics::read(&font_with(Some((0, &[(16, 17, -4)])))).expect("a line");
assert_eq!(m.measured(16.0), Some((14, 3)));
}
}