use std::collections::BTreeMap;
use f_office_fonts::{
Decoration, FaceClassification, FamilyName, FontDb, FontId, FontMetrics, LineMetrics,
Os2Metrics, OutlineError, PathCommand, Point, ScriptMetrics, ShapeDirection, ShapeRequest,
ShapedGlyph, SymbolFont, plain_device_width,
};
use f_office_paint::{DisplayList, GlyphRun, Item, Turn};
use f_office_units::Length;
use f_office_units::scale::THOUSANDTHS;
use super::{FontChoice, apply_line, font_units, metrics_of};
use crate::profile::fonts::{SymbolFileMetrics, SymbolFontEntry};
use crate::{ChosenFace, OutlineCommand};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SymbolFonts(Vec<(SymbolFont, SymbolWidths)>);
impl SymbolFonts {
pub(crate) fn of(table: &BTreeMap<String, SymbolFontEntry>) -> Result<Self, &'static str> {
table
.iter()
.map(|(family, entry)| {
let font = SymbolFont::of(family).ok_or("symbol_font")?;
Ok((font, SymbolWidths::of(entry)?))
})
.collect::<Result<_, _>>()
.map(Self)
}
pub(crate) fn get(&self, font: SymbolFont) -> Option<(usize, &SymbolWidths)> {
(self.0.iter().enumerate())
.find(|(_, (of, _))| *of == font)
.map(|(at, (_, widths))| (at, widths))
}
pub(crate) fn named(&self, name: &str) -> Option<(usize, &SymbolWidths)> {
if let Some(font) = SymbolFont::of(name) {
return self.get(font);
}
let name = FamilyName::new(name);
(self.0.iter().enumerate())
.find(|(_, (_, widths))| name.is(&widths.postscript_name))
.map(|(at, (_, widths))| (at, widths))
}
pub(crate) fn at(&self, at: usize) -> Option<(SymbolFont, &SymbolWidths)> {
self.0.get(at).map(|(font, widths)| (*font, widths))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SymbolWidths {
pub(crate) postscript_name: String,
pub(crate) version: String,
pub(crate) metrics: FontMetrics,
pub(crate) classification: FaceClassification,
measured_sizes: u16,
codes: Vec<Option<CodeWidths>>,
heights: Vec<[i16; 3]>,
}
const MISSING_GLYPH: u32 = 0;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct CodeWidths {
advance: u16,
written: Option<u16>,
wider: Vec<u16>,
narrower: Vec<u16>,
}
impl SymbolWidths {
fn of(entry: &SymbolFontEntry) -> Result<Self, &'static str> {
let units_per_em = entry
.units_per_em
.filter(|&units| units > 0)
.ok_or("units_per_em")?;
let file = entry.metrics.as_ref().ok_or("metrics")?;
let mut codes = vec![None; usize::from(u8::MAX) + 1];
for (key, &advance) in &entry.advance {
let at = place(key).ok_or("advance")?;
let slot = codes.get_mut(at).ok_or("advance")?;
*slot = Some(CodeWidths {
advance,
..CodeWidths::default()
});
}
for (key, &width) in &entry.written {
code_mut(&mut codes, key).ok_or("written")?.written = Some(width);
}
for (key, sizes) in &entry.wider {
code_mut(&mut codes, key).ok_or("wider")?.wider = in_order(sizes).ok_or("wider")?;
}
for (key, sizes) in &entry.narrower {
code_mut(&mut codes, key).ok_or("narrower")?.narrower =
in_order(sizes).ok_or("narrower")?;
}
let sizes: Vec<u16> = (entry.heights.iter())
.map(|&[pels, ..]| u16::try_from(pels).ok())
.collect::<Option<_>>()
.ok_or("heights")?;
in_order(&sizes).ok_or("heights")?;
Ok(Self {
postscript_name: entry.postscript_name.clone().ok_or("postscript_name")?,
version: entry.version.clone().ok_or("version")?,
metrics: file_metrics(units_per_em, file),
classification: FaceClassification {
panose: file.panose,
east_asian: file.east_asian,
},
measured_sizes: entry.measured_sizes.ok_or("measured_sizes")?,
codes,
heights: entry.heights.clone(),
})
}
pub(crate) const fn units_per_em(&self) -> u16 {
self.metrics.units_per_em
}
pub(crate) fn code(&self, ch: char) -> Option<u32> {
let code = u32::from(SymbolFont::code(ch)?);
self.widths(code).map(|_| code)
}
pub(crate) fn advance(&self, code: u32) -> Option<u16> {
self.widths(code).map(|widths| widths.advance)
}
pub(crate) fn written(&self, code: u32) -> Option<u16> {
let widths = self.widths(code)?;
widths.written.or_else(|| {
let units = i64::from(widths.advance) * THOUSANDTHS;
let width = f_office_units::div_round(units, i64::from(self.units_per_em()));
u16::try_from(width).ok()
})
}
pub(crate) fn device_width(&self, code: u32, ppem: u16) -> Option<i32> {
let widths = self.widths(code)?;
let plain = plain_device_width(widths.advance, self.units_per_em(), ppem);
let moved =
|sizes: &[u16]| ppem <= self.measured_sizes && sizes.binary_search(&ppem).is_ok();
Some(if moved(&widths.wider) {
plain + 1
} else if moved(&widths.narrower) {
plain - 1
} else {
plain
})
}
pub(crate) fn heights(&self, pels: u16) -> Option<(i16, i16)> {
let pels = i16::try_from(pels).ok()?;
let at = (self.heights)
.binary_search_by_key(&pels, |&[size, ..]| size)
.ok()?;
self.heights.get(at).map(|&[_, top, bottom]| (top, bottom))
}
fn widths(&self, code: u32) -> Option<&CodeWidths> {
self.codes.get(usize::try_from(code).ok()?)?.as_ref()
}
}
pub(crate) fn character(font: SymbolFont, code: u32) -> Option<char> {
font.character(char::from(u8::try_from(code).ok()?))
}
fn place(key: &str) -> Option<usize> {
if key == SymbolFontEntry::MISSING_GLYPH {
return usize::try_from(MISSING_GLYPH).ok();
}
let value = u32::try_from(crate::numbers::hex(key)?).ok()?;
let code = SymbolFont::code(char::from_u32(value)?)?;
(u32::from(code) != value).then_some(usize::from(code))
}
fn code_mut<'a>(codes: &'a mut [Option<CodeWidths>], key: &str) -> Option<&'a mut CodeWidths> {
codes.get_mut(place(key)?)?.as_mut()
}
fn in_order(sizes: &[u16]) -> Option<Vec<u16>> {
sizes
.windows(2)
.all(|pair| matches!(pair, [before, after] if before < after))
.then(|| sizes.to_vec())
}
fn file_metrics(units_per_em: u16, file: &SymbolFileMetrics) -> FontMetrics {
let line = |[ascender, descender, line_gap]: [i16; 3]| LineMetrics {
ascender,
descender,
line_gap,
};
let script = |[x_size, y_size, x_offset, y_offset]: [i16; 4]| ScriptMetrics {
x_size,
y_size,
x_offset,
y_offset,
};
let decoration = |[position, thickness]: [i16; 2]| Decoration {
position,
thickness,
};
let [win_ascent, win_descent] = file.win;
FontMetrics {
units_per_em,
hhea: line(file.hhea),
os2: Some(Os2Metrics {
average_width: file.average_width,
typo: line(file.typo),
win_ascent,
win_descent,
use_typo_metrics: file.use_typo_metrics,
x_height: None,
cap_height: None,
strikeout: decoration(file.strikeout),
subscript: script(file.subscript),
superscript: script(file.superscript),
east_asian: file.east_asian,
}),
underline: Some(decoration(file.underline)),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct SymbolDrawing {
font: FontId,
units_per_em: u16,
space: u32,
}
impl SymbolDrawing {
pub(super) fn of(db: &FontDb) -> Option<Self> {
let family = FamilyName::from_static(SymbolFont::DRAWING_FAMILY);
let font = db
.query(&family, false, false)
.filter(|&id| db.info(id).is_some_and(|info| family.is(&info.family)))?;
db.load(font).ok()?;
Some(Self {
font,
units_per_em: db.metrics(font)?.units_per_em,
space: db.glyph_id(font, ' ').unwrap_or(0),
})
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct SymbolFace<'a> {
font: SymbolFont,
pub(super) widths: &'a SymbolWidths,
drawing: SymbolDrawing,
}
impl FontChoice<'_> {
pub(super) fn symbol_face(&self, font: FontId) -> Option<SymbolFace<'_>> {
let drawing = self.symbol_drawing?;
let at = font
.index()
.checked_sub(u32::try_from(self.db.len()).ok()?)?;
let (symbol, widths) = self.symbols.at(usize::try_from(at).ok()?)?;
Some(SymbolFace {
font: symbol,
widths,
drawing,
})
}
pub(super) fn symbol_stand_in(
&self,
family: &str,
(bold, italic): (bool, bool),
named: bool,
) -> Option<ChosenFace> {
self.symbol_drawing?;
let (at, widths) = self.symbols.named(family)?;
let first = u32::try_from(self.db.len()).ok()?;
let font = FontId::from_index(first.checked_add(u32::try_from(at).ok()?)?);
let own = metrics_of(&widths.metrics);
let line = (self.line(family)).filter(|line| named && line.over_own_file);
Some(ChosenFace {
font,
metrics: line.map_or(own, |line| apply_line(line, own)),
synthetic_bold: bold,
synthetic_italic: italic,
stands_in: true,
})
}
fn symbol_glyph(&self, face: &SymbolFace<'_>, code: u32) -> u32 {
if code == MISSING_GLYPH {
return MISSING_GLYPH;
}
character(face.font, code)
.and_then(|ch| self.db.glyph_id(face.drawing.font, ch))
.filter(|&glyph| glyph != 0)
.unwrap_or(face.drawing.space)
}
pub(super) fn symbol_outline(
&self,
face: &SymbolFace<'_>,
code: u32,
) -> Result<Vec<OutlineCommand>, OutlineError> {
let glyph = self.symbol_glyph(face, code);
let (own_em, drawn_em) = (
i64::from(face.widths.units_per_em()),
i64::from(face.drawing.units_per_em.max(1)),
);
let own = i64::from(face.widths.advance(code).unwrap_or(0));
let drawn = i64::from(self.db.advance(face.drawing.font, glyph).unwrap_or(0));
let shift = own * drawn_em - drawn * own_em;
let scaled = |value: f32, shift: i64| {
let value = i64::from(font_units(value.round()));
let place = f_office_units::div_round(2 * value * own_em + shift, 2 * drawn_em);
i32::try_from(place).unwrap_or(if place < 0 { i32::MIN } else { i32::MAX })
};
let at = |p: Point| [scaled(p.x, shift), scaled(p.y, 0)];
let outline = self.db.outline(face.drawing.font, glyph)?;
Ok(outline
.into_iter()
.map(|command| match command {
PathCommand::MoveTo(p) => OutlineCommand::MoveTo(at(p)),
PathCommand::LineTo(p) => OutlineCommand::LineTo(at(p)),
PathCommand::QuadTo(c, p) => OutlineCommand::QuadTo(at(c), at(p)),
PathCommand::CubicTo(c, d, p) => OutlineCommand::CubicTo(at(c), at(d), at(p)),
PathCommand::Close => OutlineCommand::Close,
})
.collect())
}
pub(super) fn symbol_ink(
&self,
face: &SymbolFace<'_>,
code: u32,
) -> Result<Option<(i32, i32)>, OutlineError> {
let outline = self.symbol_outline(face, code)?;
let heights = outline.iter().flat_map(|command| {
let heights = match *command {
OutlineCommand::MoveTo([_, y]) | OutlineCommand::LineTo([_, y]) => {
[Some(y), None, None]
}
OutlineCommand::QuadTo([_, c], [_, y]) => [Some(c), Some(y), None],
OutlineCommand::CubicTo([_, c], [_, d], [_, y]) => [Some(c), Some(d), Some(y)],
OutlineCommand::Close => [None, None, None],
};
heights.into_iter().flatten()
});
Ok(heights.fold(None, |range, y| {
Some(range.map_or((y, y), |(low, high): (i32, i32)| (low.min(y), high.max(y))))
}))
}
pub(super) fn symbol_shape(
face: &SymbolFace<'_>,
request: &ShapeRequest<'_>,
) -> Vec<ShapedGlyph> {
let mut glyphs: Vec<ShapedGlyph> = (request.text.char_indices())
.map(|(cluster, ch)| {
let glyph = face.widths.code(ch).unwrap_or(0);
ShapedGlyph {
glyph,
advance: face.widths.advance(glyph).map_or(0, i32::from),
offset: (0, 0),
cluster,
}
})
.collect();
if request.direction == ShapeDirection::RightToLeft {
glyphs.reverse();
}
glyphs
}
pub(super) fn symbol_bi_level_advance(
face: &SymbolFace<'_>,
glyph: u32,
ppem: u16,
) -> Option<i32> {
(i64::from(ppem) == THOUSANDTHS)
.then(|| face.widths.written(glyph))
.flatten()
.map(i32::from)
}
pub(super) fn symbol_drawing_names(
&self,
face: &SymbolFace<'_>,
) -> Option<(String, Option<String>)> {
let info = self.db.info(face.drawing.font)?;
let version = info
.version
.as_deref()
.map(|version| f_office_fonts::version_number(version).to_owned());
Some((info.family.clone(), version))
}
pub(super) fn symbol_target_face(&self, face: &SymbolFace<'_>) -> Option<(String, String)> {
let widths = face.widths;
self.environment
.is_target_file(face.font.family(), "Regular", &widths.version)
.then(|| (widths.postscript_name.clone(), widths.version.clone()))
}
pub(super) fn symbol_family(face: &SymbolFace<'_>) -> String {
face.font.family().to_owned()
}
pub(crate) fn draw_symbol_stand_ins(&self, list: DisplayList) -> DisplayList {
if self.symbol_drawing.is_none() {
return list;
}
let pages = (list.into_pages().into_iter())
.map(|page| page.map_items(|items| self.drawn_items(items)))
.collect();
DisplayList::new(pages)
}
fn drawn_items(&self, items: Vec<Item>) -> Vec<Item> {
items
.into_iter()
.map(|item| match item {
Item::Glyphs(run) => Item::Glyphs(self.drawn_run(run)),
Item::Group(mut group) => {
group.items = self.drawn_items(std::mem::take(&mut group.items));
Item::Group(group)
}
other => other,
})
.collect()
}
fn drawn_run(&self, mut run: GlyphRun) -> GlyphRun {
let Some(face) = self.symbol_face(run.font) else {
return run;
};
run.font = face.drawing.font;
let size = run.size.units();
let (own_em, drawn_em) = (
i64::from(face.widths.units_per_em()),
i64::from(face.drawing.units_per_em.max(1)),
);
let (along, down) = run.turn.map_or((i64::from(Turn::SCALE), 0), |turn| {
(i64::from(turn.xx), i64::from(turn.yx))
});
let scale = i64::from(Turn::SCALE);
for glyph in &mut run.glyphs {
let code = glyph.id;
glyph.id = self.symbol_glyph(&face, code);
let own = i64::from(face.widths.advance(code).unwrap_or(0));
let drawn = i64::from(self.db.advance(face.drawing.font, glyph.id).unwrap_or(0));
let shift = f_office_units::div_round(
(own * drawn_em - drawn * own_em) * size,
2 * own_em * drawn_em,
);
glyph.x += Length::from_units(f_office_units::div_round(shift * along, scale));
glyph.y += Length::from_units(f_office_units::div_round(shift * down, scale));
}
run
}
}
#[cfg(test)]
mod tests;