From 43b20ecd0d2b69238c87add0895b9c0b3cdb1345 Mon Sep 17 00:00:00 2001 From: meehl <12648828+meehl@users.noreply.github.com> Date: Thu, 30 Oct 2025 13:10:42 +0100 Subject: [PATCH] Refactor font loading --- src/api/rendering.rs | 9 ++--- src/app.rs | 42 ++++++++++++++++++++-- src/fonts.rs | 83 ++++++++++++++++++++++---------------------- src/fonts/layout.rs | 26 +++++++++++--- src/installer.rs | 3 +- 5 files changed, 111 insertions(+), 52 deletions(-) diff --git a/src/api/rendering.rs b/src/api/rendering.rs index a07e249..d683599 100644 --- a/src/api/rendering.rs +++ b/src/api/rendering.rs @@ -11,8 +11,9 @@ use mlua::{ LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value, ffi::{self}, }; +use parley::FontFamily; use regex::Regex; -use std::sync::LazyLock; +use std::{borrow::Cow, sync::LazyLock}; pub fn register_globals(lua: &Lua) -> LuaResult<()> { let globals = lua.globals(); @@ -468,11 +469,11 @@ fn build_layout_job<'a>( ) -> LayoutJob<'a> { let mut font_weight = None; let font_family = match font_type { - PoBFontType::Fixed => parley::GenericFamily::Monospace, - PoBFontType::Var => parley::GenericFamily::SansSerif, + PoBFontType::Fixed => FontFamily::Named(Cow::Borrowed("Bitstream Vera Sans Mono")), + PoBFontType::Var => FontFamily::Named(Cow::Borrowed("Liberation Sans")), PoBFontType::VarBold => { font_weight = Some(700.0); - parley::GenericFamily::SansSerif + FontFamily::Named(Cow::Borrowed("Liberation Sans")) } }; diff --git a/src/app.rs b/src/app.rs index 0a574c6..3939e02 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,6 +1,6 @@ use crate::{ dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize}, - fonts::Fonts, + fonts::{FontData, FontDefinitions, Fonts}, gfx::{GraphicsContext, RenderJob}, input::InputState, installer::InstallMode, @@ -54,7 +54,7 @@ impl App { state: AppState { window: WindowState::default(), input: InputState::default(), - fonts: Fonts::new(), + fonts: Fonts::new(pob_font_definitions()), texture_manager: WrappedTextureManager::new(), clipboard: arboard::Clipboard::new()?, }, @@ -277,3 +277,41 @@ impl ApplicationHandler for App { } } } + +fn pob_font_definitions() -> FontDefinitions { + let mut definitions = FontDefinitions::default(); + + definitions.font_data.insert( + "bitstream-vera-sans-mono".to_owned(), + Arc::new(FontData::from_static(include_bytes!( + "../fonts/VeraMono.ttf" + ))), + ); + definitions.font_data.insert( + "liberation-sans".to_owned(), + Arc::new(FontData::from_static(include_bytes!( + "../fonts/LiberationSans-Regular.ttf" + ))), + ); + definitions.font_data.insert( + "liberation-sans-bold".to_owned(), + Arc::new(FontData::from_static(include_bytes!( + "../fonts/LiberationSans-Bold.ttf" + ))), + ); + + definitions.generic_families.insert( + parley::GenericFamily::Monospace, + vec!["bitstream-vera-sans-mono".to_owned()], + ); + + definitions.generic_families.insert( + parley::GenericFamily::SansSerif, + vec![ + "liberation-sans".to_owned(), + "liberation-sans-bold".to_owned(), + ], + ); + + definitions +} diff --git a/src/fonts.rs b/src/fonts.rs index 7c3ca5e..4490bcb 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -7,9 +7,11 @@ use crate::{ renderer::image::ImageDelta, util::calculate_hash, }; +use ahash::HashMap; use ordered_float::OrderedFloat; use parley::{ - FontContext, FontWeight, GenericFamily, LayoutContext, StyleProperty, TextStyle, fontique::Blob, + FontContext, FontFamily, FontStack, FontWeight, GenericFamily, LayoutContext, StyleProperty, + TextStyle, fontique::Blob, }; use std::sync::Arc; @@ -21,10 +23,8 @@ mod glyph_key; mod layout; mod rasterizer; -pub const BITSTREAM_VERA_SANS_MONO: &[u8] = include_bytes!("../fonts/VeraMono.ttf"); -pub const LIBERATION_SANS: &[u8] = include_bytes!("../fonts/LiberationSans-Regular.ttf"); -pub const LIBERATION_SANS_BOLD: &[u8] = include_bytes!("../fonts/LiberationSans-Bold.ttf"); - +/// Data of a .ttf or .otf file +#[derive(Clone, Debug)] pub struct FontData { data: std::borrow::Cow<'static, [u8]>, } @@ -43,13 +43,14 @@ impl AsRef<[u8]> for FontData { } } -pub struct FontDefinition { - pub generic_families: Vec, - pub data: Arc, +#[derive(Clone, Debug, Default)] +pub struct FontDefinitions { + pub font_data: HashMap>, + pub generic_families: HashMap>, } pub struct Fonts { - font_definitions: Vec, + definitions: FontDefinitions, font_context: FontContext, layout_context: LayoutContext, atlas: FontAtlas, @@ -58,25 +59,9 @@ pub struct Fonts { } impl Fonts { - pub fn new() -> Self { - // add fonts used by PoB - let font_definitions = vec![ - FontDefinition { - generic_families: vec![GenericFamily::Monospace], - data: Arc::new(FontData::from_static(BITSTREAM_VERA_SANS_MONO)), - }, - FontDefinition { - generic_families: vec![GenericFamily::SansSerif], - data: Arc::new(FontData::from_static(LIBERATION_SANS)), - }, - FontDefinition { - generic_families: vec![GenericFamily::SansSerif], - data: Arc::new(FontData::from_static(LIBERATION_SANS_BOLD)), - }, - ]; - + pub fn new(definitions: FontDefinitions) -> Self { let mut fonts = Self { - font_definitions, + definitions, font_context: FontContext::new(), layout_context: LayoutContext::new(), atlas: FontAtlas::new(1024), @@ -92,14 +77,20 @@ impl Fonts { } fn register_fonts(&mut self) { - for definition in &self.font_definitions { - let blob = Blob::new(Arc::new(definition.data.data.clone())); - let registered_fonts = self.font_context.collection.register_fonts(blob, None); - for generic_family in &definition.generic_families { - self.font_context - .collection - .append_generic_families(*generic_family, registered_fonts.iter().map(|f| f.0)); - } + for data in self.definitions.font_data.values() { + let blob = Blob::new(Arc::new(data.data.clone())); + self.font_context.collection.register_fonts(blob, None); + } + + for (generic_family, family_fonts) in &self.definitions.generic_families { + let family_ids: Vec<_> = family_fonts + .iter() + .filter_map(|family_name| self.font_context.collection.family_id(family_name)) + .collect(); + + self.font_context + .collection + .set_generic_families(*generic_family, family_ids.into_iter()); } } @@ -128,12 +119,22 @@ impl Fonts { common_chars.push(c as char); } - self.preload_text(&common_chars, font_size, GenericFamily::Monospace, None); - self.preload_text(&common_chars, font_size, GenericFamily::SansSerif, None); self.preload_text( &common_chars, font_size, - GenericFamily::SansSerif, + FontFamily::Generic(GenericFamily::Monospace), + None, + ); + self.preload_text( + &common_chars, + font_size, + FontFamily::Generic(GenericFamily::SansSerif), + None, + ); + self.preload_text( + &common_chars, + font_size, + FontFamily::Generic(GenericFamily::SansSerif), Some(FontWeight::BOLD), ); } @@ -142,13 +143,13 @@ impl Fonts { &mut self, text: &str, font_size: f32, - generic_family: GenericFamily, + font_family: FontFamily, font_weight: Option, ) { profiling::scope!("preload_text"); let style = TextStyle { - font_stack: parley::FontStack::Single(parley::FontFamily::Generic(generic_family)), + font_stack: FontStack::Single(font_family), font_weight: font_weight.unwrap_or(FontWeight::NORMAL), font_size, ..Default::default() @@ -194,7 +195,7 @@ impl Fonts { let default_style = TextStyle::default(); let style = TextStyle { - font_stack: parley::FontStack::Single(parley::FontFamily::Generic(job.font_family)), + font_stack: parley::FontStack::Single(job.font_family), font_size: job.font_size.into(), line_height: parley::LineHeight::Absolute(job.line_height.into()), font_weight: job diff --git a/src/fonts/layout.rs b/src/fonts/layout.rs index 952016b..6640114 100644 --- a/src/fonts/layout.rs +++ b/src/fonts/layout.rs @@ -1,6 +1,6 @@ use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph}; use ordered_float::OrderedFloat; -use parley::GenericFamily; +use parley::FontFamily; #[derive(Copy, Clone, Debug, Hash)] pub enum Alignment { @@ -15,10 +15,10 @@ pub struct LayoutSegment<'s> { pub color: Srgba, } -#[derive(Clone, Debug, Hash)] +#[derive(Clone, Debug)] pub struct LayoutJob<'s> { pub segments: Vec>, - pub font_family: GenericFamily, + pub font_family: FontFamily<'static>, pub font_size: OrderedFloat, pub line_height: OrderedFloat, pub alignment: Option, @@ -27,7 +27,7 @@ pub struct LayoutJob<'s> { impl<'s> LayoutJob<'s> { pub fn new( - font_family: GenericFamily, + font_family: FontFamily<'static>, font_size: f32, line_height: f32, alignment: Option, @@ -48,6 +48,24 @@ impl<'s> LayoutJob<'s> { } } +impl std::hash::Hash for LayoutJob<'_> { + fn hash(&self, state: &mut H) { + self.segments.hash(state); + match &self.font_family { + FontFamily::Named(cow) => { + cow.hash(state); + } + FontFamily::Generic(generic_family) => { + generic_family.hash(state); + } + } + self.font_size.hash(state); + self.line_height.hash(state); + self.alignment.hash(state); + self.font_weight.hash(state); + } +} + #[derive(Default)] pub struct LayoutRow { pub glyphs: Vec, diff --git a/src/installer.rs b/src/installer.rs index dec88ab..d3b8538 100644 --- a/src/installer.rs +++ b/src/installer.rs @@ -9,6 +9,7 @@ use crate::{ }; use anyhow::bail; use flate2::read::GzDecoder; +use parley::{FontFamily, GenericFamily}; use regex::Regex; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::{ @@ -114,7 +115,7 @@ impl InstallMode { app_state: &mut AppState, ) -> Box> { let mut job = LayoutJob::new( - parley::GenericFamily::SansSerif, + FontFamily::Generic(GenericFamily::SansSerif), 32.0, 34.0, Some(Alignment::Center),