use std::collections::{BTreeMap, BTreeSet};
use std::num::NonZeroU16;
use std::sync::Arc;
use mln_style::bitmap::AlphaImage;
use mln_style::collections::VecMap;
use parking_lot::Mutex;
use crate::text::atlas::RectU16;
use crate::text::font_stack::FontStack;
use crate::text::tagged_string::FontStackHash;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, mln_wire::Wire)]
pub enum GlyphFont {
#[default]
FontPBF,
Face(NonZeroU16),
}
impl GlyphFont {
pub const SYSTEM: GlyphFont = GlyphFont::Face(NonZeroU16::MAX);
#[must_use]
pub const fn face(id: NonZeroU16) -> Self {
GlyphFont::Face(id)
}
#[must_use]
pub const fn id(self) -> u16 {
match self {
GlyphFont::FontPBF => 0,
GlyphFont::Face(id) => id.get(),
}
}
}
#[cfg(any(test, feature = "sqlite"))]
pub(crate) const GLYPHS_PER_GLYPH_RANGE: u32 = 256;
#[cfg(any(test, feature = "sqlite"))]
pub(crate) const GLYPH_RANGES_PER_FONT_STACK: u32 = 256;
#[cfg(any(test, feature = "sqlite"))]
pub(crate) const NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK: u32 = 97;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct GlyphRange {
pub first: u16,
pub second: u16,
pub font: GlyphFont,
}
impl GlyphRange {
#[must_use]
pub fn new(first: u16, second: u16, font: GlyphFont) -> Self {
GlyphRange { first, second, font }
}
}
impl PartialOrd for GlyphRange {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for GlyphRange {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(self.first, self.second, self.font).cmp(&(other.first, other.second, other.font))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, mln_wire::Wire)]
pub struct GlyphID {
pub code: u16,
pub(crate) font: GlyphFont,
}
impl GlyphID {
#[must_use]
pub const fn new(code: u16) -> Self {
GlyphID { code, font: GlyphFont::FontPBF }
}
#[must_use]
pub fn from_char(c: char) -> Option<Self> {
pbf_code(c).map(GlyphID::from)
}
#[must_use]
pub(crate) fn char(self) -> Option<char> {
char::from_u32(u32::from(self.code))
}
#[must_use]
pub fn with_type(index: u16, font: GlyphFont) -> Self {
GlyphID { code: index, font }
}
#[must_use]
pub(crate) fn hash(self) -> u32 {
(u32::from(self.font.id()) << 16) | u32::from(self.code)
}
}
impl PartialOrd for GlyphID {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for GlyphID {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.hash().cmp(&other.hash())
}
}
impl From<u16> for GlyphID {
fn from(code: u16) -> Self {
GlyphID::new(code)
}
}
#[must_use]
pub(crate) fn pbf_code(c: char) -> Option<u16> {
u16::try_from(u32::from(c)).ok()
}
pub(crate) type GlyphIDs = BTreeSet<GlyphID>;
#[must_use]
pub fn glyph_range(glyph: GlyphID) -> GlyphRange {
let start = glyph.code & 0xff00;
GlyphRange::new(start, start | 0xff, glyph.font)
}
#[derive(Clone, Copy, PartialEq, Debug, Default, mln_wire::Wire)]
pub struct GlyphMetrics {
pub width: u32,
pub height: u32,
pub left: f32,
pub top: f32,
pub advance: u32,
pub is_double_resolution: bool,
}
#[derive(Clone, PartialEq, Debug, Default, mln_wire::Wire)]
pub struct Glyph {
pub id: GlyphID,
pub bitmap: AlphaImage,
pub metrics: GlyphMetrics,
}
impl Glyph {
pub(crate) const BORDER_SIZE: u8 = 3;
}
pub(crate) type Glyphs = BTreeMap<GlyphID, Option<Arc<Glyph>>>;
pub type GlyphMap = VecMap<FontStackHash, Glyphs>;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PositionedGlyph {
pub glyph: GlyphID,
pub x: f32,
pub y: f32,
pub vertical: bool,
pub scale: f32,
pub rect: RectU16,
pub metrics: GlyphMetrics,
pub image_id: Option<String>,
pub section_index: usize,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PositionedLine {
pub glyphs: Vec<PositionedGlyph>,
pub line_offset: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Bounds {
pub left: f32,
pub top: f32,
pub right: f32,
pub bottom: f32,
}
impl Bounds {
#[must_use]
pub fn width(&self) -> f32 {
self.right - self.left
}
#[must_use]
pub fn height(&self) -> f32 {
self.bottom - self.top
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Shaping {
pub lines: Vec<PositionedLine>,
pub bounds: Bounds,
pub verticalizable: bool,
pub icons_in_text: bool,
}
impl Shaping {
pub const Y_OFFSET: f32 = -17.0;
#[must_use]
pub fn is_empty(&self) -> bool {
self.lines.iter().all(|line| line.glyphs.is_empty())
}
}
pub(crate) use mln_style::font_face::FontFaceRange;
#[derive(Clone)]
pub struct FontData {
bytes: Arc<dyn AsRef<[u8]> + Send + Sync>,
face_index: u32,
}
impl FontData {
pub(crate) fn new(bytes: Arc<dyn AsRef<[u8]> + Send + Sync>) -> Self {
FontData { bytes, face_index: 0 }
}
#[must_use]
pub fn with_face_index(self, index: u32) -> Self {
FontData { face_index: index, ..self }
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
(*self.bytes).as_ref()
}
#[must_use]
pub fn face_index(&self) -> u32 {
self.face_index
}
#[must_use]
pub(crate) fn shared(&self) -> Arc<dyn AsRef<[u8]> + Send + Sync> {
Arc::clone(&self.bytes)
}
}
impl Default for FontData {
fn default() -> Self {
FontData::from(Vec::new())
}
}
impl From<Vec<u8>> for FontData {
fn from(bytes: Vec<u8>) -> Self {
FontData::new(Arc::new(bytes))
}
}
impl From<Arc<Vec<u8>>> for FontData {
fn from(bytes: Arc<Vec<u8>>) -> Self {
FontData::new(bytes)
}
}
impl std::fmt::Debug for FontData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FontData").field("face_index", &self.face_index).finish_non_exhaustive()
}
}
impl PartialEq for FontData {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.bytes, &other.bytes) && self.face_index == other.face_index
}
}
#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
pub struct FontFace {
pub font: GlyphFont,
pub name: String,
pub(crate) url: String,
pub ranges: Vec<FontFaceRange>,
#[wire(skip)]
pub(crate) data: Option<FontData>,
#[wire(skip, default = "regular_weight")]
pub(crate) weight: u16,
}
fn regular_weight() -> u16 {
crate::text::weight::REGULAR_WEIGHT as u16
}
impl FontFace {
#[must_use]
pub fn new(name: &str, url: &str, ranges: Vec<FontFaceRange>) -> Self {
FontFace {
font: GlyphFont::FontPBF,
name: name.to_owned(),
url: url.to_owned(),
ranges,
data: None,
weight: regular_weight(),
}
}
#[must_use]
pub fn system(ranges: Vec<FontFaceRange>) -> Self {
FontFace { font: GlyphFont::SYSTEM, ..FontFace::new("", "", ranges) }
}
#[must_use]
pub fn device(url: &str, weight: u16, data: FontData) -> Self {
FontFace {
font: face_type(&format!("{url}@{weight}"), "", &[]),
weight,
..FontFace::new("", url, Vec::new()).with_data(data)
}
}
#[must_use]
pub(crate) fn with_data(mut self, data: FontData) -> Self {
self.data = Some(data);
self
}
}
impl From<&mln_style::font_face::FontFace> for FontFace {
fn from(face: &mln_style::font_face::FontFace) -> Self {
FontFace {
font: face_type(&face.url, &face.name, &face.ranges),
..FontFace::new(&face.name, &face.url, face.ranges.clone())
}
}
}
impl mln_style::font_face::FontCoverage for FontFace {
fn covers(&self, c: char) -> bool {
mln_style::font_face::ranges_cover(&self.ranges, c)
}
}
pub type FontFaces = Vec<FontFace>;
#[must_use]
pub(crate) fn style_font_faces(
style: Option<&mln_style::font_face::FontFaces>,
fallback: Option<&FontFaces>,
) -> Option<Arc<FontFaces>> {
let fallback = fallback.filter(|faces| !faces.is_empty());
if style.is_none() && fallback.is_none() {
return None;
}
let style = style.into_iter().flatten().map(FontFace::from);
Some(Arc::new(style.chain(fallback.into_iter().flatten().cloned()).collect()))
}
pub(crate) type ShapeRequests = VecMap<FontStack, VecMap<GlyphFont, BTreeSet<Vec<char>>>>;
pub type ShapeResults = VecMap<FontStack, VecMap<GlyphFont, BTreeMap<Vec<char>, Arc<crate::text::ShapedText>>>>;
#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
pub struct GlyphDependencies {
pub glyphs: VecMap<FontStack, GlyphIDs>,
pub shapes: ShapeRequests,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
pub struct GlyphPosition {
pub rect: RectU16,
pub metrics: GlyphMetrics,
}
pub type GlyphPositions = VecMap<FontStackHash, BTreeMap<GlyphID, Option<GlyphPosition>>>;
type FaceKey = (String, String, Vec<FontFaceRange>);
struct FaceTypes {
last: u16,
types: Vec<(FaceKey, NonZeroU16)>,
}
static FACE_TYPES: Mutex<FaceTypes> = Mutex::new(FaceTypes { last: 0, types: Vec::new() });
pub(crate) fn face_type(url: &str, font: &str, ranges: &[FontFaceRange]) -> GlyphFont {
let mut types = FACE_TYPES.lock();
let found = types.types.iter().find(|((u, f, r), _)| u == url && f == font && r == ranges);
if let Some(&(_, id)) = found {
return GlyphFont::Face(id);
}
types.last = if types.last >= u16::MAX - 1 { 1 } else { types.last + 1 };
let id = NonZeroU16::new(types.last).unwrap_or(NonZeroU16::MIN);
types.types.push(((url.to_owned(), font.to_owned(), ranges.to_vec()), id));
GlyphFont::Face(id)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn glyph_id_order_is_the_union_hash() {
let a = GlyphID::with_type(0xFFFF, GlyphFont::FontPBF);
let b = GlyphID::with_type(0, GlyphFont::face(NonZeroU16::MIN));
assert!(a < b);
assert_eq!(b.hash(), 0x10000);
assert_eq!(GlyphID::from_char('\u{FFFF}'), Some(GlyphID::new(0xFFFF)));
assert_eq!(GlyphID::from_char('\u{1F600}'), None);
}
#[test]
fn glyph_range_is_the_256_glyphs_around_a_glyph() {
let r = glyph_range(GlyphID::new(0x41));
assert_eq!((r.first, r.second), (0, 255));
let r = glyph_range(GlyphID::new(0xFFFF));
assert_eq!((r.first, r.second), (65280, 65535));
}
#[test]
fn a_glyph_id_is_two_u16s() {
assert_eq!(size_of::<GlyphFont>(), 2);
assert_eq!(size_of::<GlyphID>(), 4);
}
#[test]
fn non_ideograph_ranges_are_the_ranges_local_fonts_dont_draw() {
let local = (0..GLYPH_RANGES_PER_FONT_STACK)
.filter(|i| mln_style::i18n::glyph_range_is_entirely_locally_generated((i * GLYPHS_PER_GLYPH_RANGE) as u16))
.count() as u32;
assert_eq!(GLYPH_RANGES_PER_FONT_STACK - local, NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK);
}
#[test]
fn face_types_are_stable_per_key() {
let fs = "Noto Sans Regular";
let a = face_type("local://a.ttf", fs, &[(0x1780, 0x17FF)]);
let b = face_type("local://a.ttf", fs, &[(0x1780, 0x17FF)]);
let c = face_type("local://b.ttf", fs, &[(0x1780, 0x17FF)]);
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, GlyphFont::FontPBF);
}
#[test]
fn style_faces_come_before_fallback_faces() {
let style_face = mln_style::font_face::FontFace {
name: "Noto Sans Regular".to_owned(),
url: "local://a.ttf".to_owned(),
ranges: vec![(0x1000, 0x109F)],
};
let fallback = vec![FontFace::system(vec![(0x0900, 0x097F)])];
assert_eq!(style_font_faces(None, None), None);
assert_eq!(style_font_faces(None, Some(&Vec::new())), None);
assert_eq!(style_font_faces(Some(&Vec::new()), None), Some(Arc::new(Vec::new())));
let faces = style_font_faces(Some(&vec![style_face.clone()]), Some(&fallback)).unwrap();
assert_eq!(faces.len(), 2);
assert_eq!(faces[0].name, style_face.name);
assert_eq!(faces[0].font, face_type(&style_face.url, &style_face.name, &style_face.ranges));
assert_eq!(faces[1], fallback[0]);
}
}