mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
fix(web): retain verified runtime fonts across UI rebuilds
This commit is contained in:
1 parent
36ade0c3a4
commit
b4c6ef3814
5 files changed
+241
-8
No files matched your search
@@ -444,7 +444,7 @@ impl WebShell {
|
||||
}
|
||||
});
|
||||
}
|
||||
served_fonts::install(&mut self.app, arrived);
|
||||
served_fonts::install(&mut self.app, ctx, arrived);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Fonts a host serves next to the app, for the platform shell that fetches them (the web build;
|
||||
//! see `photocraft_text::served`): reading the manifest, the families to fetch, and installing
|
||||
//! what arrived, which registers the files for documents and re-renders the type layers drawn
|
||||
//! without them. The UI's own font stack takes its served faces through `UiFonts::served_faces`
|
||||
//! without them. Runtime-manifest deliveries also populate owned UI fallbacks. A build-generated
|
||||
//! UI font stack takes its served faces through `UiFonts::served_faces`
|
||||
//! ([`serve`]); the framework's loader fetches them and puts them in the stack.
|
||||
|
||||
mod loaded;
|
||||
|
||||
pub(crate) use loaded::append as append_loaded;
|
||||
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft::ui::fonts::{FontFetcher, ServedFace};
|
||||
@@ -65,10 +70,11 @@ pub(crate) fn served(ctx: &egui::Context) -> Option<Served> {
|
||||
/// re-renders the type layers that use those families, or whose text falls back to them (a script
|
||||
/// fallback, e.g. Arabic set in Inter), and show our own layout. A PSD layer still
|
||||
/// showing Photoshop's pixels (not edited yet) keeps them, as it does when its font is installed
|
||||
/// from the start. Call it every frame: it also retries the layers of a document that was busy.
|
||||
// PLAN: dialogs-w59 (`apps/photocraft-web/src/web.rs`) calls this with the `ctx` argument the UI stack used to take;
|
||||
// the framework's loader puts a delivered script fallback in the UI stack, so the argument is gone.
|
||||
pub fn install(app: &mut PhotocraftApp, delivered: Vec<(String, Vec<u8>)>) {
|
||||
/// from the start. Successful host deliveries also populate `ctx`'s UI fallbacks. The caller
|
||||
/// must apply the manifest's integrity check before delivery. Call it every frame: it also retries
|
||||
/// the layers of a document that was busy.
|
||||
pub fn install(app: &mut PhotocraftApp, ctx: &egui::Context, delivered: Vec<(String, Vec<u8>)>) {
|
||||
let mut ui_changed = false;
|
||||
let mut layers = std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
if !delivered.is_empty() {
|
||||
let families: Vec<String> = delivered.iter().map(|(f, _)| f.clone()).collect();
|
||||
@@ -77,12 +83,16 @@ pub fn install(app: &mut PhotocraftApp, delivered: Vec<(String, Vec<u8>)>) {
|
||||
pick(&app.session, &families, &mut layers);
|
||||
let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for (family, bytes) in delivered {
|
||||
ui_changed |= loaded::cache(ctx, &bytes);
|
||||
let added = eng.fonts.register_font_data(bytes);
|
||||
if !added.contains(&family) {
|
||||
log::warn!("a served font file listed as {family:?} registers {added:?}; the family in fonts/manifest.txt must be the font's own");
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui_changed {
|
||||
crate::theme::install_fonts(ctx);
|
||||
}
|
||||
if !layers.is_empty() {
|
||||
let busy = app.session.refresh_type_layers(&layers);
|
||||
PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(busy);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! UI fallbacks from the host's runtime manifest. Unlike a build-generated `ServedFace`, that
|
||||
//! manifest has no cmap coverage or static metadata. Keep the verified, downloaded bytes owned
|
||||
//! by the context instead of inventing a served-face table or starting another fetch path.
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::font_catalog::sfnt::{FaceNames, read_faces_bytes};
|
||||
use craft::ui::fonts::{FontRef, SEMIBOLD, UiFonts, set_weight};
|
||||
use egui::epaint::text::Blob;
|
||||
|
||||
// UI fallbacks are an optional cache, not an unbounded second document-font database. These
|
||||
// limits also bound metadata work for hostile collections and repeated host deliveries.
|
||||
const MAX_BYTES: usize = 128 << 20;
|
||||
const MAX_FILE_BYTES: usize = 64 << 20;
|
||||
const MAX_FACES: usize = 256;
|
||||
const MAX_FILES: usize = 64;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct File {
|
||||
bytes: Blob,
|
||||
faces: Vec<FaceNames>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Loaded {
|
||||
files: Vec<File>,
|
||||
bytes: usize,
|
||||
faces: usize,
|
||||
}
|
||||
|
||||
impl Loaded {
|
||||
fn add(&mut self, bytes: &[u8], families: &[String]) -> bool {
|
||||
if bytes.is_empty()
|
||||
|| bytes.len() > MAX_FILE_BYTES
|
||||
|| bytes.len() > MAX_BYTES.saturating_sub(self.bytes)
|
||||
|| self.files.len() >= MAX_FILES
|
||||
|| self.files.iter().any(|file| file.bytes.as_ref().as_ref() == bytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let faces: Vec<_> = read_faces_bytes(bytes).into_iter().filter(|face| !face.italic && families.contains(&face.family)).collect();
|
||||
if faces.is_empty() || faces.len() > MAX_FACES.saturating_sub(self.faces) {
|
||||
return false;
|
||||
}
|
||||
self.bytes += bytes.len();
|
||||
self.faces += faces.len();
|
||||
// One owned copy for the UI, shared by every face/weight and later stack rebuild. The
|
||||
// document engine consumes the original Vec independently.
|
||||
self.files.push(File { bytes: Arc::new(bytes.to_vec()), faces });
|
||||
true
|
||||
}
|
||||
|
||||
fn selected(&self, families: &[String]) -> Vec<(String, egui::FontData)> {
|
||||
families
|
||||
.iter()
|
||||
.filter_map(|family| {
|
||||
let (file_index, file, face) = self
|
||||
.files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, file)| file.faces.iter().map(move |face| (i, file, face)))
|
||||
.filter(|(_, _, face)| &face.family == family)
|
||||
.min_by_key(|(_, _, face)| face.weight.abs_diff(400))?;
|
||||
let mut data = egui::FontData::from_blob(Arc::clone(&file.bytes), face.index);
|
||||
data.tweak.set_baseline_fallback(true);
|
||||
Some((format!("photocraft-host-font-{file_index}-{}", face.index), data))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn id() -> egui::Id {
|
||||
egui::Id::unique("photocraft-loaded-host-fonts")
|
||||
}
|
||||
|
||||
/// Called only on successful host delivery, after its path and optional SRI were checked.
|
||||
/// Document-only families do not become UI fallbacks merely because a document uses them.
|
||||
pub(super) fn cache(ctx: &egui::Context, bytes: &[u8]) -> bool {
|
||||
let families = photocraft_text::served::script_fallback_families();
|
||||
ctx.data_mut(|d| d.get_temp_mut_or_default::<Loaded>(id()).add(bytes, &families))
|
||||
}
|
||||
|
||||
/// Append to the app's primary faces, retaining language order on every theme/size rebuild.
|
||||
pub(crate) fn append<'a>(ctx: &egui::Context, mut fonts: UiFonts<'a>, language: &str) -> UiFonts<'a> {
|
||||
let mut families = photocraft_text::served::script_fallback_families();
|
||||
if let Some(preferred) = photocraft_text::served::fallback_for_language(language) {
|
||||
families.retain(|family| family != &preferred);
|
||||
families.insert(0, preferred);
|
||||
}
|
||||
let faces = ctx.data(|d| d.get_temp::<Loaded>(id()).map(|loaded| loaded.selected(&families))).unwrap_or_default();
|
||||
for (name, data) in faces {
|
||||
for (family, weight) in [(FontRef::proportional(), 400), (FontRef::monospace(), 400), (FontRef::named("medium"), 500), (FontRef::named(SEMIBOLD), 600)]
|
||||
{
|
||||
let mut data = data.clone();
|
||||
set_weight(&mut data, weight);
|
||||
fonts = fonts.app_face(&format!("{name}@{weight}"), data, &[family]);
|
||||
}
|
||||
}
|
||||
fonts
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::*;
|
||||
use craft::ui::fonts::{I18nScripts, SystemFonts};
|
||||
|
||||
fn inter() -> &'static [u8] {
|
||||
photocraft_text::fonts::INTER_REGULAR.as_slice()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_faces_are_owned_deduplicated_and_bounded() {
|
||||
let mut loaded = Loaded::default();
|
||||
let families = vec!["Inter".into()];
|
||||
assert!(!loaded.add(b"not a font", &families));
|
||||
assert!(!loaded.add(inter(), &["different manifest family".into()]));
|
||||
assert!(loaded.add(inter(), &families));
|
||||
assert!(!loaded.add(inter(), &families));
|
||||
assert_eq!((loaded.files.len(), loaded.faces, loaded.bytes), (1, 1, inter().len()));
|
||||
let clone = loaded.clone();
|
||||
assert!(Arc::ptr_eq(&loaded.files[0].bytes, &clone.files[0].bytes));
|
||||
assert_eq!(loaded.selected(&families)[0].1.index, 0);
|
||||
let mut full = Loaded { bytes: MAX_BYTES, ..Loaded::default() };
|
||||
assert!(!full.add(inter(), &families));
|
||||
let mut full = Loaded { faces: MAX_FACES, ..Loaded::default() };
|
||||
assert!(!full.add(inter(), &families));
|
||||
}
|
||||
|
||||
// Build a collection from attributed bundled fonts, relocating its table offsets.
|
||||
// No font fixture is added to the repository.
|
||||
fn collection(fonts: &[&[u8]]) -> Vec<u8> {
|
||||
let mut out = b"ttcf\0\x01\0\0".to_vec();
|
||||
out.extend_from_slice(&(fonts.len() as u32).to_be_bytes());
|
||||
out.resize(12 + 4 * fonts.len(), 0);
|
||||
for (i, font) in fonts.iter().enumerate() {
|
||||
let start = out.len();
|
||||
out[12 + 4 * i..16 + 4 * i].copy_from_slice(&(start as u32).to_be_bytes());
|
||||
out.extend_from_slice(font);
|
||||
let tables = u16::from_be_bytes([font[4], font[5]]) as usize;
|
||||
for table in 0..tables {
|
||||
let offset = start + 12 + table * 16 + 8;
|
||||
let value = u32::from_be_bytes(out[offset..offset + 4].try_into().unwrap());
|
||||
out[offset..offset + 4].copy_from_slice(&(value + start as u32).to_be_bytes());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_uses_actual_regular_face_index_not_the_first_face() {
|
||||
let medium = photocraft_text::fonts::INTER_MEDIUM.as_slice();
|
||||
let ttc = collection(&[medium, inter()]);
|
||||
let mut loaded = Loaded::default();
|
||||
let families = vec!["Inter".into()];
|
||||
assert!(loaded.add(&ttc, &families));
|
||||
assert_eq!(loaded.faces, 2);
|
||||
let selected = loaded.selected(&families);
|
||||
assert_eq!(selected.len(), 1);
|
||||
assert_eq!(selected[0].1.index, 1, "regular, not the collection's first (medium) face");
|
||||
assert!(selected[0].0.ends_with("-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_delivery_reaches_all_ui_families_and_survives_reinstalls() {
|
||||
let _catalog = super::super::changing_catalog();
|
||||
let ctx = egui::Context::default();
|
||||
// A real attributed font posing as the host's script fallback, independent of optional
|
||||
// platform Arabic/Japanese font installations.
|
||||
photocraft_text::served::add_fonts(&super::super::parse_manifest("Inter | Regular | fonts/Inter.ttf | Zzzz").0);
|
||||
let mut app = crate::PhotocraftApp::with_context(ctx.clone(), photocraft_engine::Session::new(), crate::Services::default());
|
||||
super::super::install(&mut app, &ctx, vec![("Inter".into(), inter().to_vec())]);
|
||||
for _ in 0..2 {
|
||||
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
|
||||
}
|
||||
for size in [photocraft_engine::prefs::UiFontSize::Large, photocraft_engine::prefs::UiFontSize::Small] {
|
||||
crate::theme::set_ui_font_size(&ctx, size);
|
||||
crate::theme::install_fonts(&ctx);
|
||||
for _ in 0..2 {
|
||||
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
|
||||
}
|
||||
let definitions = ctx.fonts(|fonts| fonts.definitions().clone());
|
||||
for family in
|
||||
[egui::FontFamily::Proportional, egui::FontFamily::Monospace, egui::FontFamily::Name("medium".into()), egui::FontFamily::Name("semibold".into())]
|
||||
{
|
||||
let chain = &definitions.families[&family];
|
||||
let hosts: Vec<_> = chain.iter().filter(|name| name.starts_with("photocraft-host-font-")).collect();
|
||||
assert_eq!(hosts.len(), 1);
|
||||
assert_ne!(chain.first(), hosts.first().copied(), "bundled primary face remains first");
|
||||
let expected = if size == photocraft_engine::prefs::UiFontSize::Large { 16.0 / 12.0 } else { 1.0 };
|
||||
assert_eq!(definitions.font_data[hosts[0]].tweak.scale, expected);
|
||||
}
|
||||
}
|
||||
assert!(!cache(&ctx, inter()), "repeated delivery neither copies nor reinstalls");
|
||||
for language in ["ar", "ja"] {
|
||||
let fonts = append(&ctx, UiFonts::new(&I18nScripts).system_fonts(SystemFonts::Off), language);
|
||||
fonts.install(&ctx);
|
||||
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
|
||||
assert!(ctx.fonts_mut(|fonts| fonts.has_glyphs(&egui::FontId::proportional(12.0), "Hello")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_follows_requested_family_order() {
|
||||
let mut loaded = Loaded::default();
|
||||
let families = vec!["Inter".into(), "JetBrains Mono".into()];
|
||||
assert!(loaded.add(inter(), &families));
|
||||
assert!(loaded.add(photocraft_text::fonts::JETBRAINS_MONO_REGULAR.as_slice(), &families));
|
||||
let forward = loaded.selected(&families);
|
||||
let reverse = loaded.selected(&families.into_iter().rev().collect::<Vec<_>>());
|
||||
assert_eq!(forward[0].0, reverse[1].0);
|
||||
assert_eq!(forward[1].0, reverse[0].0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn italic_faces_do_not_replace_upright_ui_fallbacks() {
|
||||
let mut italic = inter().to_vec();
|
||||
let tables = u16::from_be_bytes([italic[4], italic[5]]) as usize;
|
||||
let table = (0..tables).map(|i| 12 + 16 * i).find(|&i| &italic[i..i + 4] == b"OS/2").unwrap();
|
||||
let offset = u32::from_be_bytes(italic[table + 8..table + 12].try_into().unwrap()) as usize;
|
||||
italic[offset + 63] |= 1; // OS/2 fsSelection ITALIC bit.
|
||||
assert!(read_faces_bytes(&italic)[0].italic);
|
||||
assert!(!Loaded::default().add(&italic, &["Inter".into()]));
|
||||
}
|
||||
@@ -961,7 +961,7 @@ pub fn install_fonts(ctx: &egui::Context) {
|
||||
/// `medium` and `semibold` families, JetBrains Mono for numbers. The framework puts egui's default
|
||||
/// faces after them, for symbols Inter lacks, and orders the craft-fonts faces this build embeds
|
||||
/// (`cjk_fonts::craft_faces`) by `ui_language`. A web build's served faces and their fetcher come
|
||||
/// from `served_fonts::serve`.
|
||||
/// from `served_fonts::serve`; runtime-manifest deliveries use its owned fallback cache.
|
||||
fn ui_fonts(ctx: &egui::Context, ui_language: &str) -> UiFonts<'static> {
|
||||
use craft::ui::fonts::{Emoji, Family, FontRef, I18nScripts, SEMIBOLD};
|
||||
let (proportional, monospace, medium, semibold) = (FontRef::proportional(), FontRef::monospace(), FontRef::named("medium"), FontRef::named(SEMIBOLD));
|
||||
@@ -993,7 +993,8 @@ fn ui_fonts(ctx: &egui::Context, ui_language: &str) -> UiFonts<'static> {
|
||||
if let Some(served) = crate::served_fonts::served(ctx) {
|
||||
fonts = fonts.served_faces(&served.faces).fetcher(served.fetcher);
|
||||
}
|
||||
faces.into_iter().fold(fonts, |fonts, (name, data, families)| fonts.app_face(&name, data, &families))
|
||||
let fonts = faces.into_iter().fold(fonts, |fonts, (name, data, families)| fonts.app_face(&name, data, &families));
|
||||
crate::served_fonts::append_loaded(ctx, fonts, ui_language)
|
||||
}
|
||||
|
||||
/// Installs the craft runtime on `ctx` with the font stack (see [`install_fonts`]) and the root
|
||||
|
||||
Reference in new issue
Block a user