Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Integration: installed CJK UI faces are read once per process (#394)

aiongg6b3d7c4ba847
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 287e6e492..07e041f9a 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -80,7 +80,6 @@ pub struct ShapedGlyph {
pub rtl: bool,
}
-/// An OpenType feature setting: `"liga"`, `"-kern"`, `"ss01"`.
/// Line metrics of the font at `index` of `data`, in font units: (units per em, ascent, descent
/// (negative below the baseline), line gap) — what text layouts such as egui's build lines from.
/// `None` if the font can't be read.
@@ -91,6 +90,7 @@ pub fn line_metrics(data: &[u8], index: u32) -> Option<(f32, f32, f32, f32)> {
Some((f32::from(m.units_per_em.max(1)), m.ascent, m.descent, m.leading))
}
+/// An OpenType feature setting: `"liga"`, `"-kern"`, `"ss01"`.
pub fn feature(tag: &str) -> Option<Feature> {
let (on, t) = match tag.strip_prefix('-') {
Some(r) => (false, r),
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 4be603d16..5c6c6e019 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -2683,7 +2683,7 @@ mod tests {
for (max_side, patches) in [(None, true), (Some(1024), false)] {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
- let mut frame = |app: &mut DesignApp| {
+ let frame = |app: &mut DesignApp| {
// Wider than the limit (egui's font atlas needs at least 1024).
let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1900.0, 900.0))), ..Default::default() };
if let Some(m) = max_side {
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index 911b74188..418a03f72 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -1,6 +1,7 @@
//! Design tokens (InDesign's four interface brightness levels), fonts and egui style.
-use std::sync::Arc;
+use std::borrow::Cow;
+use std::sync::{Arc, OnceLock};
use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, TextStyle, Visuals};
use serde::{Deserialize, Serialize};
@@ -255,9 +256,19 @@ impl Tokens {
/// Install the UI fonts for the interface language `lang` (it orders the CJK fallbacks).
pub fn install_fonts(ctx: &egui::Context, lang: &str) {
+ // Installed faces are read once per process, so a language change only reorders them. Their
+ // bytes are leaked once and borrowed by every `FontData` (`set_fonts` takes the definitions
+ // by value on each call).
+ static SYSTEM: OnceLock<Vec<SystemFont>> = OnceLock::new();
let craft = designcraft_fonts::CRAFT_FONTS;
+ let system = SYSTEM.get_or_init(|| {
+ system_ui_fonts(craft)
+ .into_iter()
+ .map(|f| SystemFont { bytes: Cow::Borrowed(Box::leak(f.bytes.into_owned().into_boxed_slice())), ..f })
+ .collect()
+ });
let mut defs = font_definitions(craft, lang);
- add_system_fallbacks(&mut defs, &system_ui_fonts(craft), lang);
+ add_system_fallbacks(&mut defs, system, lang);
ctx.set_fonts(defs);
}
@@ -266,7 +277,7 @@ pub(crate) struct SystemFont {
/// "Jpan", "Hans", "Hant" or "Kore".
script: &'static str,
family: String,
- bytes: Vec<u8>,
+ bytes: Cow<'static, [u8]>,
index: u32,
}
@@ -311,7 +322,7 @@ fn system_ui_fonts(craft: &[designcraft_fonts::CraftFont]) -> Vec<SystemFont> {
(face.family.eq_ignore_ascii_case(family) && !face.data().is_empty()).then(|| SystemFont {
script,
family: (*family).to_string(),
- bytes: face.data().to_vec(),
+ bytes: Cow::Owned(face.data().to_vec()),
index: face.index(),
})
})
@@ -354,10 +365,7 @@ fn cjk_script(lang: &str) -> &'static str {
pub(crate) fn add_system_fallbacks(fonts: &mut FontDefinitions, system: &[SystemFont], lang: &str) {
let name = |f: &SystemFont| format!("system-{}", f.family);
for f in system {
- fonts.font_data.insert(
- name(f),
- Arc::new(FontData { index: f.index, tweak: baseline_tweak(&f.bytes, f.index), ..FontData::from_owned(f.bytes.clone()) }),
- );
+ fonts.font_data.insert(name(f), Arc::new(FontData { font: f.bytes.clone(), index: f.index, tweak: baseline_tweak(&f.bytes, f.index) }));
}
let first = cjk_script(lang);
let preferred: Vec<String> = system.iter().filter(|f| f.script == first).map(name).collect();
@@ -533,7 +541,7 @@ mod japanese_font_tests {
#[test]
fn installed_fonts_give_japanese_glyphs_without_craft_fonts() {
let bytes = designcraft_fonts::testing::font_with("DC UI Japanese", &['日', '本', '語']).unwrap();
- let system = [super::SystemFont { script: "Jpan", family: "DC UI Japanese".into(), bytes, index: 0 }];
+ let system = [super::SystemFont { script: "Jpan", family: "DC UI Japanese".into(), bytes: bytes.into(), index: 0 }];
let mut defs = super::font_definitions(&[], "ja");
super::add_system_fallbacks(&mut defs, &system, "ja");
for family in families() {
@@ -578,7 +586,7 @@ mod japanese_font_tests {
let face = |family: &str, chars: &[char], script| super::SystemFont {
script,
family: family.into(),
- bytes: designcraft_fonts::testing::font_with(family, chars).unwrap(),
+ bytes: designcraft_fonts::testing::font_with(family, chars).unwrap().into(),
index: 0,
};
let system = [face("DC UI Korean", &['한', '글'], "Kore"), face("DC UI Japanese", &['日'], "Jpan")];
@@ -604,7 +612,7 @@ mod japanese_font_tests {
let face = |family: &str, script| super::SystemFont {
script,
family: family.into(),
- bytes: designcraft_fonts::testing::font_with(family, &['日']).unwrap(),
+ bytes: designcraft_fonts::testing::font_with(family, &['日']).unwrap().into(),
index: 0,
};
let system = [face("DC Ja", "Jpan"), face("DC Hans", "Hans"), face("DC Hant", "Hant"), face("DC Ko", "Kore")];