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 GlyphIDType {
#[default]
FontPBF,
Face(NonZeroU16),
}
impl GlyphIDType {
pub const SYSTEM: GlyphIDType = GlyphIDType::Face(NonZeroU16::MAX);
#[must_use]
pub const fn face(id: NonZeroU16) -> Self {
GlyphIDType::Face(id)
}
#[must_use]
pub const fn id(self) -> u16 {
match self {
GlyphIDType::FontPBF => 0,
GlyphIDType::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 type_: GlyphIDType,
}
impl GlyphRange {
#[must_use]
pub fn new(first: u32, second: u32, type_: GlyphIDType) -> Self {
GlyphRange { first: first as u16, second: second as u16, type_ }
}
}
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.type_).cmp(&(other.first, other.second, other.type_))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, mln_wire::Wire)]
pub struct GlyphID {
pub code: u16,
pub(crate) type_: GlyphIDType,
}
impl GlyphID {
#[must_use]
pub fn new(codepoint: u32) -> Self {
GlyphID { code: codepoint as u16, type_: GlyphIDType::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, type_: GlyphIDType) -> Self {
GlyphID { code: index, type_ }
}
#[must_use]
pub(crate) fn hash(self) -> u32 {
(u32::from(self.type_.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(u32::from(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 get_glyph_range(glyph: GlyphID) -> GlyphRange {
let start = (u32::from(glyph.code) / 256) * 256;
let end = start + 255;
let start = start.min(65280);
let end = end.min(65535);
GlyphRange::new(start, end, glyph.type_)
}
#[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 type_: GlyphIDType,
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 {
type_: GlyphIDType::FontPBF,
name: name.to_string(),
url: url.to_string(),
ranges,
data: None,
weight: regular_weight(),
}
}
#[must_use]
pub fn system(ranges: Vec<FontFaceRange>) -> Self {
FontFace { type_: GlyphIDType::SYSTEM, ..FontFace::new("", "", ranges) }
}
#[must_use]
pub fn device(url: &str, weight: u16, data: FontData) -> Self {
FontFace {
type_: 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 {
type_: 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<GlyphIDType, BTreeSet<Vec<char>>>>;
pub type ShapeResults = VecMap<FontStack, VecMap<GlyphIDType, 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]) -> GlyphIDType {
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 GlyphIDType::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));
GlyphIDType::Face(id)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn glyph_id_order_is_the_union_hash() {
let a = GlyphID::with_type(0xFFFF, GlyphIDType::FontPBF);
let b = GlyphID::with_type(0, GlyphIDType::face(NonZeroU16::MIN));
assert!(a < b);
assert_eq!(b.hash(), 0x10000);
assert_eq!(GlyphID::new(0x1F600).code, 0xF600);
assert_eq!(GlyphID::from_char('\u{FFFF}'), Some(GlyphID::new(0xFFFF)));
assert_eq!(GlyphID::from_char('\u{1F600}'), None);
}
#[test]
fn glyph_range() {
let r = get_glyph_range(GlyphID::new(0x41));
assert_eq!((r.first, r.second), (0, 255));
let r = get_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::<GlyphIDType>(), 2);
assert_eq!(size_of::<GlyphID>(), 4);
}
#[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, GlyphIDType::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].type_, face_type(&style_face.url, &style_face.name, &style_face.ranges));
assert_eq!(faces[1], fallback[0]);
}
}