pub(crate) mod resident;
use crate::{
bitmap_font::{self, Settings},
output::raster::truetype::{rasterize, ScanMode},
truetype::{Environment, Font, Hinting, Size},
};
use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
pub use crate::bitmap_font::Glyph;
#[derive(Debug, Clone, Copy)]
pub struct BitmapMetrics {
pub width: u32,
pub height: u32,
pub baseline: f64,
}
pub trait BitmapFont: Send + Sync {
fn metrics(&self) -> BitmapMetrics;
fn glyph(&self, character: char) -> Result<Option<Cow<'_, Glyph>>, String>;
}
#[derive(Clone, Default)]
pub struct Fonts<'a> {
faces: BTreeMap<char, Arc<Face<'a>>>,
named: BTreeMap<String, Arc<Face<'a>>>,
resolver: Option<Arc<Resolver<'a>>>,
}
type Resolver<'a> = dyn Fn(&str) -> Result<Option<Face<'a>>, String> + Send + Sync + 'a;
enum Source<'a> {
Compact(&'static zpl_bitmap_fonts::Font),
Bitmap(Settings, Arc<Vec<Glyph>>),
Provider(BitmapMetrics, Arc<dyn BitmapFont + 'a>),
TrueType(Font<'a>, Hinting),
}
pub struct Face<'a> {
source: Source<'a>,
baseline: f64,
missing_advance: Option<u32>,
bitmap_printer_metrics: bool,
}
impl<'a> Fonts<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn insert_bitmap_font(
&mut self,
id: char,
font: Arc<dyn BitmapFont + 'a>,
) -> Result<(), String> {
validate_id(id)?;
self.faces.insert(id, Arc::new(Face::provider(font)?));
Ok(())
}
pub fn insert_named_bitmap_font(
&mut self,
name: &str,
font: Arc<dyn BitmapFont + 'a>,
) -> Result<(), String> {
let name = font_name(name)?;
self.named.insert(name, Arc::new(Face::provider(font)?));
Ok(())
}
pub fn insert_bitmap(
&mut self,
id: char,
settings: Settings,
glyphs: Vec<Glyph>,
baseline: f64,
) -> Result<(), String> {
validate_id(id)?;
self.faces
.insert(id, Arc::new(Face::bitmap(settings, glyphs, baseline)?));
Ok(())
}
pub fn insert_truetype(
&mut self,
id: char,
data: &'a [u8],
hinting: Hinting,
) -> Result<(), String> {
validate_id(id)?;
self.faces
.insert(id, Arc::new(Face::truetype(data, hinting)?));
Ok(())
}
pub fn insert_named_bitmap(
&mut self,
name: &str,
settings: Settings,
glyphs: Vec<Glyph>,
baseline: f64,
) -> Result<(), String> {
let name = font_name(name)?;
let face = Face::bitmap(settings, glyphs, baseline)?;
self.named.insert(name, Arc::new(face));
Ok(())
}
pub fn insert_named_truetype(
&mut self,
name: &str,
data: &'a [u8],
hinting: Hinting,
) -> Result<(), String> {
let name = font_name(name)?;
let face = Face::truetype(data, hinting)?;
self.named.insert(name, Arc::new(face));
Ok(())
}
pub fn set_resolver(
&mut self,
resolver: impl Fn(&str) -> Result<Option<Face<'a>>, String> + Send + Sync + 'a,
) {
self.resolver = Some(Arc::new(resolver));
}
}
pub(crate) struct RenderFonts<'r, 'a, 'd> {
resources: &'r Fonts<'a>,
aliases: BTreeMap<char, String>,
selected_name: Option<String>,
downloaded: BTreeMap<String, Face<'d>>,
resolved: BTreeMap<String, Face<'a>>,
registered_faces: BTreeMap<char, Face<'a>>,
registered_named: BTreeMap<String, Face<'a>>,
printer_metrics: bool,
pub(crate) truetype_printer_metrics: bool,
}
impl<'r, 'a, 'd> RenderFonts<'r, 'a, 'd> {
pub(crate) fn new(
resources: &'r Fonts<'a>,
printer_metrics: bool,
truetype_printer_metrics: bool,
) -> Self {
Self {
registered_faces: resources
.faces
.iter()
.filter_map(|(id, face)| {
face.with_printer_metrics(printer_metrics)
.map(|face| (*id, face))
})
.collect(),
registered_named: resources
.named
.iter()
.filter_map(|(name, face)| {
face.with_printer_metrics(printer_metrics)
.map(|face| (name.clone(), face))
})
.collect(),
printer_metrics,
truetype_printer_metrics,
resources,
aliases: BTreeMap::new(),
selected_name: None,
downloaded: BTreeMap::new(),
resolved: BTreeMap::new(),
}
}
fn checked_name(&mut self, name: &str) -> Result<String, String> {
let name = font_name(name)?;
if !self.downloaded.contains_key(&name)
&& !self.resources.named.contains_key(&name)
&& !self.resolved.contains_key(&name)
{
let face = match &self.resources.resolver {
Some(resolve) => resolve(&name)?,
None => resolve_rom_font(&name)?,
}
.ok_or_else(|| format!("unresolved named font {name:?}"))?;
let face = face
.with_printer_metrics(self.printer_metrics)
.unwrap_or(face);
self.resolved.insert(name.clone(), face);
}
Ok(name)
}
pub(crate) fn install(
&mut self,
download: &'d crate::render::font_downloads::Download,
) -> Result<(), String> {
use crate::render::font_downloads::Download;
let (name, face) = match download {
Download::TrueType { name, data } => (name, Face::truetype(data, Hinting::Native)?),
Download::Bitmap {
name,
settings,
glyphs,
baseline,
space,
} => {
let mut face = Face::bitmap_metrics(*settings, glyphs.clone(), *baseline)?;
face.missing_advance = Some(*space);
let face = face
.with_printer_metrics(self.printer_metrics)
.unwrap_or(face);
(name, face)
}
};
self.downloaded.insert(name.clone(), face);
Ok(())
}
pub(crate) fn alias(&mut self, id: char, name: &str) -> Result<(), String> {
let name = self.checked_name(name)?;
self.aliases.insert(id, name);
Ok(())
}
pub(crate) fn select_named(&mut self, name: &str) -> Result<(), String> {
self.selected_name = Some(self.checked_name(name)?);
Ok(())
}
pub(crate) fn has_named_selection(&self) -> bool {
self.selected_name.is_some()
}
pub(crate) fn scalable_layout(&self, id: char) -> bool {
self.get(id).map_or_else(
|| resident::is_scalable(id),
|face| face.compact().is_none() && !face.bitmap_printer_metrics,
)
}
pub(crate) fn get(&self, id: char) -> Option<&Face<'_>> {
let name = if id == NAMED_FONT {
self.selected_name.as_ref()
} else {
self.aliases.get(&id)
};
match name {
Some(name) => self
.downloaded
.get(name)
.or_else(|| self.registered_named.get(name))
.or_else(|| self.resources.named.get(name).map(Arc::as_ref))
.or_else(|| self.resolved.get(name)),
None => self
.registered_faces
.get(&id)
.or_else(|| self.resources.faces.get(&id).map(Arc::as_ref)),
}
}
}
pub(crate) fn font_name(name: &str) -> Result<String, String> {
let name = name.trim().to_ascii_uppercase();
let (device, file) = name.split_once(':').unwrap_or(("R", &name));
if !matches!(device, "R" | "E" | "B" | "A" | "Z") {
return Err("unsupported named font device".into());
}
let (base, extension) = file
.rsplit_once('.')
.ok_or("named font requires FNT, TTF, TTE, OTF or DAT extension")?;
if base.is_empty()
|| base.len() > 255
|| !base
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
|| !matches!(extension, "FNT" | "TTF" | "TTE" | "OTF" | "DAT")
{
return Err("invalid named font filename or extension".into());
}
Ok(format!("{device}:{file}"))
}
pub fn resolve_rom_font(name: &str) -> Result<Option<Face<'static>>, String> {
let name = font_name(name)?;
Ok(
zpl_bitmap_fonts::zd621::font_by_name(&name).map(|font| Face {
source: Source::Compact(font),
baseline: font.cell_metrics().map_or(0., |m| {
(f64::from(m.baseline) - 1.) / f64::from(m.cell_height)
}),
missing_advance: None,
bitmap_printer_metrics: false,
}),
)
}
pub(crate) const NAMED_FONT: char = '\0';
impl<'a> Face<'a> {
fn with_printer_metrics(&self, enabled: bool) -> Option<Self> {
if !enabled {
return None;
}
let (source, height) = match &self.source {
Source::Bitmap(settings, glyphs) => (
Source::Bitmap(*settings, Arc::clone(glyphs)),
settings.height,
),
Source::Provider(metrics, provider) => (
Source::Provider(*metrics, Arc::clone(provider)),
metrics.height,
),
_ => return None,
};
Some(Self {
source,
baseline: self.baseline - 1. / height as f64,
missing_advance: self.missing_advance,
bitmap_printer_metrics: true,
})
}
pub fn provider(font: Arc<dyn BitmapFont + 'a>) -> Result<Self, String> {
let metrics = font.metrics();
if !(1..=4096).contains(&metrics.width)
|| !(1..=4096).contains(&metrics.height)
|| !metrics.baseline.is_finite()
|| !(0. ..=metrics.height as f64).contains(&metrics.baseline)
{
return Err("invalid bitmap font metrics".into());
}
Ok(Self {
baseline: metrics.baseline / metrics.height as f64,
source: Source::Provider(metrics, font),
missing_advance: None,
bitmap_printer_metrics: false,
})
}
pub(crate) fn compact(&self) -> Option<&'static zpl_bitmap_fonts::Font> {
match self.source {
Source::Compact(face) => Some(face),
_ => None,
}
}
pub fn bitmap(settings: Settings, glyphs: Vec<Glyph>, baseline: f64) -> Result<Self, String> {
settings.validate()?;
Self::bitmap_metrics(settings, glyphs, baseline)
}
fn bitmap_metrics(
settings: Settings,
mut glyphs: Vec<Glyph>,
baseline: f64,
) -> Result<Self, String> {
bitmap_font::validate_glyphs(&glyphs)?;
if glyphs.is_empty()
|| !baseline.is_finite()
|| !(0. ..=settings.height as f64).contains(&baseline)
{
return Err("invalid bitmap font baseline or empty glyph set".into());
}
glyphs.sort_by_key(|g| g.codepoint);
if glyphs
.windows(2)
.any(|pair| pair[0].codepoint == pair[1].codepoint)
{
return Err("duplicate bitmap font codepoint".into());
}
Ok(Self {
baseline: baseline / settings.height as f64,
source: Source::Bitmap(settings, Arc::new(glyphs)),
missing_advance: None,
bitmap_printer_metrics: false,
})
}
pub fn truetype(data: &'a [u8], hinting: Hinting) -> Result<Self, String> {
let font = Font::parse(data).map_err(|e| e.to_string())?;
let baseline = 0.75;
Ok(Self {
source: Source::TrueType(font, hinting),
missing_advance: None,
bitmap_printer_metrics: false,
baseline,
})
}
}
fn validate_id(id: char) -> Result<(), String> {
if id.is_ascii_uppercase() || id.is_ascii_digit() || id == bitmap_font::GRAPHIC_SYMBOLS {
Ok(())
} else {
Err("font ID must be 0–9, A–Z, or @".into())
}
}
impl Face<'_> {
pub(crate) fn bitmap_ft_offset(&self, h: f64, rotation: u8) -> Option<(f64, f64)> {
if !self.bitmap_printer_metrics {
return None;
}
let height = match &self.source {
Source::Bitmap(settings, _) => settings.height,
Source::Provider(metrics, _) => metrics.height,
_ => return None,
};
let scale = h / height as f64;
Some(match rotation {
b'R' => (scale, 0.),
b'I' => (1., scale),
b'B' => (1. - scale, 1.),
_ => (0., 1. - scale),
})
}
pub(crate) fn is_truetype(&self) -> bool {
matches!(self.source, Source::TrueType(..))
}
pub(crate) fn baseline(&self, h: f64) -> f64 {
self.baseline
* match self.source {
Source::TrueType(..) => h.round(),
_ => h,
}
}
pub(crate) fn dimensions(&self, w: f64, h: f64) -> Result<(f64, f64), String> {
if let Source::Compact(face) = self.source {
if !w.is_finite() || !h.is_finite() || w < 0. || h < 0. {
return Err("font dimensions must be nonnegative and finite".into());
}
let Some(m) = face.cell_metrics() else {
return if w <= 1. && h <= 1. {
Ok((1., 1.))
} else {
Err(format!(
"ROM font {} has no calibrated sizing metrics; only size 1,1 is supported",
face.name
))
};
};
let (nw, nh) = (f64::from(m.cell_width), f64::from(m.cell_height));
let sx = (w / nw).round().max(1.);
let sy = (h / nh).round().max(1.);
return Ok((
nw * if w == 0. { sy } else { sx },
nh * if h == 0. { sx } else { sy },
));
}
let (nw, nh) = match &self.source {
Source::Compact(_) => unreachable!(),
Source::Bitmap(s, _) => (
if s.width == 0 { s.height } else { s.width } as f64,
s.height as f64,
),
Source::Provider(m, _) => (m.width as f64, m.height as f64),
Source::TrueType(..) => (1., 1.),
};
let (w, h) = match (w, h) {
(0., 0.) => (nw, nh),
(0., h) => (h * nw / nh, h),
(w, 0.) => (w, w * nh / nw),
pair => pair,
};
if !w.is_finite() || !h.is_finite() || w <= 0. || h <= 0. {
return Err("font dimensions must be positive".into());
}
if matches!(self.source, Source::TrueType(..))
&& (!(1. ..=4096.).contains(&w.round()) || !(1. ..=4096.).contains(&h.round()))
{
return Err("TrueType size must be in 1..=4096 dots per em".into());
}
if self.bitmap_printer_metrics {
return Ok((nw * (w / nw).round().max(1.), nh * (h / nh).round().max(1.)));
}
Ok((w, h))
}
pub(crate) fn glyph(
&self,
c: char,
w: f64,
h: f64,
environment: Environment,
) -> Result<(Cow<'_, Glyph>, f64, f64), String> {
self.dimensions(w, h)?;
match &self.source {
Source::Compact(_) => Err("ROM glyphs require measured encoding lookup".into()),
Source::Bitmap(s, glyphs) => {
let width = if s.width == 0 { s.height } else { s.width };
let index = match glyphs.binary_search_by_key(&(c as u32), |g| g.codepoint) {
Ok(index) => index,
Err(_) => {
let advance = self
.missing_advance
.ok_or_else(|| format!("unsupported custom font glyph {c:?}"))?;
return Ok((
Cow::Owned(Glyph {
codepoint: c as u32,
advance,
left: 0,
top: 0,
width: 0,
height: 0,
bitmap: vec![],
}),
w / width as f64,
h / s.height as f64,
));
}
};
Ok((
Cow::Borrowed(&glyphs[index]),
w / width as f64,
h / s.height as f64,
))
}
Source::Provider(metrics, font) => {
let glyph = font
.glyph(c)?
.ok_or_else(|| format!("unsupported custom font glyph {c:?}"))?;
bitmap_font::validate_glyphs(std::slice::from_ref(glyph.as_ref()))?;
if glyph.codepoint != c as u32 {
return Err("bitmap font returned a different codepoint".into());
}
Ok((glyph, w / metrics.width as f64, h / metrics.height as f64))
}
Source::TrueType(font, hinting) => {
let index = font
.glyph_index(c)
.ok_or_else(|| format!("unsupported custom font glyph {c:?}"))?;
let size =
Size::new(w.round() as u16, h.round() as u16).map_err(|e| e.to_string())?;
let instance = font
.instance(size, *hinting, environment)
.map_err(|e| e.to_string())?;
let outline = instance.outline(index).map_err(|e| e.to_string())?;
let advance = instance.layout_advance(index).map_err(|e| e.to_string())?;
let (mode, turns) = match environment {
Environment::Zd621V93 { quarter_turns } => (ScanMode::Zd621V93, quarter_turns),
_ => (ScanMode::Center, 0),
};
let glyph = rasterize(&outline, c as u32, advance, turns, mode)
.map_err(|e| e.to_string())?;
Ok((
Cow::Owned(crate::output::raster::truetype::unrotate_glyph(
glyph, turns,
)),
1.,
1.,
))
}
}
}
}
pub(crate) fn resolve_glyph<'a>(
selection: resident::Selection,
custom: Option<&'a Face<'a>>,
key: crate::fonts::resident::GlyphKey,
w: f64,
h: f64,
environment: Environment,
) -> Result<(resident::GlyphView<'a>, f64, f64), String> {
if let Some(custom) = custom {
if let Some(face) = custom.compact() {
let (nw, nh) = face.cell_metrics().map_or((1., 1.), |m| {
(f64::from(m.cell_width), f64::from(m.cell_height))
});
return Ok((
resident::glyph_from(selection.compact_set(face), key)?,
w / nw,
h / nh,
));
}
let crate::fonts::resident::GlyphKey::Unicode(c) = key else {
return Err("invalid custom font key".into());
};
let (g, sx, sy) = custom.glyph(c, w, h, environment)?;
return Ok((
resident::GlyphView {
advance: g.advance,
left: g.left,
top: g.top,
width: g.width,
height: g.height,
pixels: resident::Pixels::Custom(g),
},
sx,
sy,
));
}
let (glyphs, sx, sy) = resident::selected_for_char(selection, key, w, h);
Ok((resident::glyph_from(glyphs, key)?, sx, sy))
}