Refresh rendered fallback fonts when initial discovery completes

This commit is contained in:
Terra854 committed 2026-12-02 06:32:02 +08:00
1 parent ef9b23322a
commit 2b6f47f8c0
11 files changed
+289 -12

No files matched your search

+1 -1
View File
@@ -448,7 +448,7 @@ impl Cache {
&& x.glyphs
.iter()
.zip(&y.glyphs)
.all(|(g, h)| g.gid == h.gid && g.style == h.style && (g.x - h.x).abs() < 1e-9 && (g.y - h.y).abs() < 1e-9)
.all(|(g, h)| g.face == h.face && g.gid == h.gid && g.style == h.style && (g.x - h.x).abs() < 1e-9 && (g.y - h.y).abs() < 1e-9)
};
let mut out = Vec::new();
for fb in &b.frames {
@@ -19,6 +19,7 @@ fn cached_composition_retries_the_style_after_initial_catalog_publication() {
&['X'],
)
.unwrap();
let bytes = designcraft_fonts::testing::with_empty_glyph(bytes, 'X').unwrap();
std::fs::write(dir.join("Later.ttf"), &bytes).unwrap();
let mut doc = Document::new(&NewDocument::default());
let layer = doc.default_layer();
@@ -60,6 +61,16 @@ fn cached_composition_retries_the_style_after_initial_catalog_publication() {
assert_eq!(glyph.face.get().data(), bytes);
assert!(matches!(glyph.face.get().source, FontSource::Installed(_)));
}
assert_eq!(before.styles, after.styles, "this upgrade changes the face, not the run style");
for (a, b) in before.frames.iter().flat_map(|f| &f.lines).zip(after.frames.iter().flat_map(|f| &f.lines)) {
assert_eq!((a.range.clone(), a.baseline, a.x0, a.end_x), (b.range.clone(), b.baseline, b.x0, b.end_x));
for (g, h) in a.glyphs.iter().zip(&b.glyphs) {
assert_eq!((g.gid, g.style, g.x, g.y, g.adv), (h.gid, h.style, h.x, h.y, h.adv));
assert_ne!(g.face, h.face, "the fixture must exercise distinct stable face identities");
}
}
assert_eq!(Cache::changed_frames(&before, &after), doc.story(sid).unwrap().frames, "face-only changes still need repainting");
assert!(Cache::changed_frames(&after, &after).is_empty(), "an unchanged face does not damage the frame");
assert!(Arc::ptr_eq(&after, &cache.get(&doc, sid, None)), "the completed-catalog composition remains cached");
}
std::fs::remove_dir_all(dir).unwrap();
+19 -4
View File
@@ -296,13 +296,28 @@ pub fn with_table_u16(mut font: Vec<u8>, tag: &[u8; 4], at: usize, value: u16) -
/// `font` (a TrueType font) with an empty `.notdef`: glyph 0's `loca` entry starts where it ends,
/// so the glyph has no outline. `None` if the font has no `head`/`loca` tables.
pub fn with_empty_notdef(mut font: Vec<u8>) -> Option<Vec<u8>> {
pub fn with_empty_notdef(font: Vec<u8>) -> Option<Vec<u8>> {
empty_outline(font, 0)
}
/// `font` with the glyph mapped from `c` left blank, preserving its ID and horizontal metrics.
/// This makes two faces set identical glyph positions while painting different pixels.
pub fn with_empty_glyph(font: Vec<u8>, c: char) -> Option<Vec<u8>> {
let gid = skrifa::FontRef::new(&font).ok()?.charmap().map(c)?.to_u32() as usize;
empty_outline(font, gid)
}
fn empty_outline(mut font: Vec<u8>, gid: usize) -> Option<Vec<u8>> {
let (_, head, _) = table(&font, b"head")?;
let long = font.get(head + 50..head + 52)? != [0, 0];
let (_, loca, _) = table(&font, b"loca")?;
let (_, loca, len) = table(&font, b"loca")?;
let width = if long { 4 } else { 2 };
let end = font.get(loca + width..loca + 2 * width)?.to_vec();
font.get_mut(loca..loca + width)?.copy_from_slice(&end);
let at = gid.checked_mul(width)?;
if at.checked_add(2 * width)? > len {
return None;
}
let end = font.get(loca + at + width..loca + at + 2 * width)?.to_vec();
font.get_mut(loca + at..loca + at + width)?.copy_from_slice(&end);
Some(font)
}
+1
View File
@@ -25,6 +25,7 @@ serde = { workspace = true }
craft-image-codecs = { workspace = true }
[dev-dependencies]
designcraft-fonts = { workspace = true, features = ["testing"] }
image = { workspace = true, features = ["png", "gif", "tiff"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+12 -5
View File
@@ -15,6 +15,13 @@ use designcraft_geom::{Affine, Rect, Shape};
use vello_cpu::color::PremulRgba8;
use vello_cpu::{RenderContext, peniko};
/// Rendering inputs outside the document, captured before drawing a viewport.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct ViewInputs {
pub threads: u16,
pub font_cataloged: bool,
}
/// At most one viewport, capped at 64 MiB. The snapshot shares the document's large Arcs;
/// comparisons use their identity without scanning text or image bytes. Keeping it prevents address reuse.
/// All document fields, colour settings and options participate, including parent pages,
@@ -27,7 +34,7 @@ pub(crate) struct CachedView {
view: Affine,
image: Rendered,
stats: crate::FrameStats,
threads: u16,
inputs: ViewInputs,
}
/// Rounds [`transparent_area`](Renderer::transparent_area) grows the blend area by joining touching objects.
const MAX_AREA_ROUNDS: usize = 64;
@@ -43,14 +50,14 @@ impl CachedView {
height: u32,
view: Affine,
opts: &RenderOptions,
threads: u16,
inputs: ViewInputs,
) -> bool {
self.image.width == width.clamp(1, crate::MAX_SIDE)
&& self.image.height == height.clamp(1, crate::MAX_SIDE)
&& self.view == view
&& self.opts == *opts
&& self.spreads == spreads
&& self.threads == threads
&& self.inputs == inputs
&& self.settings == designcraft_color::cms::active_settings()
&& same_document(&self.doc, doc)
}
@@ -67,7 +74,7 @@ impl CachedView {
opts: &RenderOptions,
image: &Rendered,
stats: crate::FrameStats,
threads: u16,
inputs: ViewInputs,
) -> Self {
Self {
doc: doc.clone(),
@@ -77,7 +84,7 @@ impl CachedView {
view,
image: image.clone(),
stats,
threads,
inputs,
}
}
}
+5 -2
View File
@@ -55,12 +55,15 @@ impl Renderer {
pub fn render(&mut self, doc: &Document, cache: &Cache, spreads: &[Placed], size: (u32, u32), view: Affine, opts: &RenderOptions) -> Rendered {
let start = now();
let (width, height) = size;
// Capture before drawing: publication during a render must not tag earlier fallback
// pixels as catalog-complete when the viewport is inserted below.
let inputs = blendspace::ViewInputs { threads: self.threads, font_cataloged: designcraft_fonts::FontDb::global().system_fonts_cataloged() };
RICH_BLACK.with(|r| r.set(opts.rich_black));
PLATE.with(|p| p.set(opts.plate));
self.kept.begin(doc);
// A kept view had every image drawn.
self.images_pending = false;
if let Some(hit) = self.cmyk_view.as_ref().filter(|entry| entry.matches(doc, spreads, width, height, view, opts, self.threads)) {
if let Some(hit) = self.cmyk_view.as_ref().filter(|entry| entry.matches(doc, spreads, width, height, view, opts, inputs)) {
let image = hit.image();
self.stats = hit.stats();
self.stats.micros = now().saturating_sub(start);
@@ -76,7 +79,7 @@ impl Renderer {
let deferred = images::take_deferred();
self.images_pending = deferred;
if self.cmyk_ran && !deferred && image.pixels.len() <= blendspace::CachedView::MAX_BYTES {
self.cmyk_view = Some(blendspace::CachedView::new(doc, spreads, view, opts, &image, self.stats, self.threads));
self.cmyk_view = Some(blendspace::CachedView::new(doc, spreads, view, opts, &image, self.stats, inputs));
}
self.stats.micros = now().saturating_sub(start);
image
@@ -0,0 +1,86 @@
use designcraft_compose::Cache;
use designcraft_doc::{BlendSpace, Document, Item, ItemId, ParaFormat, Shape, SpreadRef, build::NewDocument};
use designcraft_fonts::{FALLBACK_FAMILY, FontDb};
use designcraft_geom::{Affine, Rect};
use designcraft_render::{Placed, RenderOptions, Renderer};
#[test]
fn initial_catalog_publication_refreshes_cached_ink_views_and_rgb_text() {
const CHILD: &str = "DESIGNCRAFT_RENDER_FONT_CATALOG_CHILD";
if std::env::var_os(CHILD).is_none() {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "initial_font_catalog::initial_catalog_publication_refreshes_cached_ink_views_and_rgb_text", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
assert!(out.status.success(), "{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
return;
}
let db = FontDb::global();
let dir = std::env::temp_dir().join(format!("designcraft-render-font-catalog-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// Original bundled OFL fixture; only the synthetic name/cmap tables are substituted.
let bytes = designcraft_fonts::testing::font_with_names(
&[(1, FALLBACK_FAMILY), (2, "Catalog Only"), (16, FALLBACK_FAMILY), (17, "Catalog Only")],
&['X'],
)
.unwrap();
let bytes = designcraft_fonts::testing::with_empty_glyph(bytes, 'X').unwrap();
let file = dir.join("Later.ttf");
std::fs::write(&file, bytes).unwrap();
let placed = [Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }];
let opts = RenderOptions { blend_space_view: true, ..Default::default() };
let mut views = db
.during_initial_catalog(vec![dir.clone()], || {
[BlendSpace::Rgb, BlendSpace::Cmyk]
.into_iter()
.map(|space| {
let mut doc = Document::new(&NewDocument { width: 160.0, height: 120.0, facing_pages: false, ..Default::default() });
doc.settings.blend_space = space;
let layer = doc.default_layer();
let (_, sid) =
doc.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 150.0, 60.0), layer, "XXX", ParaFormat::default()).unwrap();
doc.story_mut(sid).unwrap().format_chars(0..3, |f| {
f.over.font_family = Some(FALLBACK_FAMILY.into());
f.over.font_style = Some("Catalog Only".into());
});
let mut item = Item::new(
ItemId(doc.alloc()),
layer,
Shape::Rectangle,
designcraft_geom::shapes::rectangle(Rect::new(20.0, 70.0, 100.0, 100.0)),
);
item.fill = designcraft_doc::Fill::swatch("C=100 M=0 Y=0 K=0");
item.blend = designcraft_color::BlendMode::Multiply;
doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
let cache = Cache::new();
let mut renderer = Renderer::new();
renderer.threads = 0;
let before = renderer.render(&doc, &cache, &placed, (160, 120), Affine::IDENTITY, &opts);
assert!(cache.composed_for(&doc, sid).is_some());
cache.clear();
assert_eq!(renderer.render(&doc, &cache, &placed, (160, 120), Affine::IDENTITY, &opts).pixels, before.pixels);
assert_eq!(
cache.composed_for(&doc, sid).is_none(),
space == BlendSpace::Cmyk,
"the CMYK fixture must actually reuse its ink viewport"
);
(doc, sid, cache, renderer, before.pixels)
})
.collect::<Vec<_>>()
})
.expect("the subprocess must own initial catalog publication");
for (doc, sid, cache, renderer, before) in &mut views {
let after = renderer.render(doc, cache, &placed, (160, 120), Affine::IDENTITY, &opts);
let composed = cache.composed_for(doc, *sid).expect("a ready catalog must invalidate an old cached ink viewport too");
let glyphs: Vec<_> = composed.frames.iter().flat_map(|f| &f.lines).flat_map(|l| &l.glyphs).collect();
assert!(!glyphs.is_empty());
assert!(glyphs.iter().all(|g| g.face.style == "Catalog Only"));
assert_ne!(after.pixels.as_slice(), before.as_slice(), "the exact face has blank X outlines with the same metrics");
cache.clear();
assert_eq!(renderer.render(doc, cache, &placed, (160, 120), Affine::IDENTITY, &opts).pixels, after.pixels);
assert_eq!(cache.composed_for(doc, *sid).is_none(), doc.settings.blend_space == BlendSpace::Cmyk, "unchanged ready ink views remain cached");
}
std::fs::remove_file(file).unwrap();
std::fs::remove_dir(dir).unwrap();
}
+2
View File
@@ -4,6 +4,8 @@ mod effects;
mod glyph_retention;
mod gradient_inks;
mod gradients;
#[cfg(not(target_arch = "wasm32"))]
mod initial_font_catalog;
mod pdf_geometry;
mod perf;
mod placed_pdf;
+3
View File
@@ -81,6 +81,7 @@ fn grid_areas(layout: &CanvasLayout) -> Vec<(designcraft_doc::SpreadRef, DRect)>
/// The display options that change how the canvas texture looks without touching the document.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DisplayKey {
font_cataloged: bool,
quality: designcraft_render::DisplayQuality,
rich_black: bool,
overprint_preview: bool,
@@ -98,6 +99,8 @@ pub struct DisplayKey {
pub(super) fn display_key(app: &DesignApp) -> DisplayKey {
let (ui, prefs) = (&app.ui, &app.session.prefs);
DisplayKey {
// Discovery can replace fallback outlines without a document edit or view change.
font_cataloged: designcraft_fonts::FontDb::global().system_fonts_cataloged(),
quality: ui.display_quality,
rich_black: ui.rich_black,
overprint_preview: ui.overprint_preview,
@@ -0,0 +1,147 @@
//! Catalog-only canvas refresh, isolated from tests that initialize the process-wide font DB.
use std::sync::{Arc, mpsc};
use std::time::Duration;
use designcraft_engine::Session;
use designcraft_fonts::{FALLBACK_FAMILY, FontDb};
use designcraft_geom::Affine;
use designcraft_ui_egui::{DesignApp, Services, canvas, render_worker};
use serde_json::json;
fn draw(ctx: &egui::Context, app: &mut DesignApp) -> Option<Vec<egui::Color32>> {
let mut out = ctx.run_ui(
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))), ..Default::default() },
|ui| canvas::show(app, ui),
);
let pixels = app.canvas.texture.as_ref().and_then(|texture| {
out.textures_delta.set.get(&texture.id()).and_then(|deltas| deltas.last()).map(|delta| {
assert!(delta.pos.is_none(), "the catalog-only update repaints the complete canvas");
let egui::ImageData::Color(image) = &delta.image;
image.pixels.clone()
})
});
out.textures_delta.clear();
pixels
}
fn ink(pixels: &[egui::Color32]) -> usize {
pixels.iter().filter(|p| p.a() > 0 && p.r() < 128 && p.g() < 128 && p.b() < 128).count()
}
fn completed_worker(job: render_worker::Job) -> render_worker::Worker {
// Worker sends Done before requesting repaint: the notification acknowledges that the
// obsolete result is queued, without timing the renderer or draining its result channel.
let (tx, rx) = mpsc::channel();
let wake = egui::Context::default();
wake.set_request_repaint_callback(move |_| {
let _ = tx.send(());
});
let worker = render_worker::Worker::spawn(wake).unwrap();
worker.submit(job);
rx.recv_timeout(Duration::from_secs(5)).expect("the old render must finish before catalog publication");
worker
}
#[test]
fn catalog_publication_refreshes_the_unchanged_canvas_and_discards_old_results() {
const CHILD: &str = "DESIGNCRAFT_INITIAL_FONT_CANVAS_CHILD";
if std::env::var_os(CHILD).is_none() {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "initial_font_catalog::catalog_publication_refreshes_the_unchanged_canvas_and_discards_old_results", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
assert!(out.status.success(), "{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
return;
}
let db = FontDb::global();
let dir = tempfile::tempdir().unwrap();
// Existing OFL bundled-font fixture: identical glyph IDs and metrics, a distinct face.
let bytes = designcraft_fonts::testing::font_with_names(
&[(1, FALLBACK_FAMILY), (2, "Catalog Only"), (16, FALLBACK_FAMILY), (17, "Catalog Only")],
&['X'],
)
.unwrap();
let bytes = designcraft_fonts::testing::with_empty_glyph(bytes, 'X').unwrap();
std::fs::write(dir.path().join("Later.ttf"), bytes).unwrap();
let ctx = egui::Context::default();
let (mut app, sid, before, shown_doc, old_ink) = db
.during_initial_catalog(vec![dir.path().to_path_buf()], || {
let _ = designcraft_ui_egui::theme::install_fonts(&ctx, "en");
let mut app = DesignApp::new(Session::new(), Services::default());
// Keep the initial canvas synchronous; below we queue a real completed worker result.
app.canvas.worker_started = true;
app.run("file.new", json!({})).unwrap();
let made = app.run("frame.create", json!({"rect":[36,36,300,120],"content":"text","text":"XXX","caret":false})).unwrap();
let sid = designcraft_doc::StoryId(made["story"].as_u64().unwrap());
Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).story_mut(sid).unwrap().format_chars(0..3, |f| {
f.over.font_family = Some(FALLBACK_FAMILY.into());
f.over.font_style = Some("Catalog Only".into());
});
// The selected-frame task bar enumerates font styles (a separate, blocking
// catalog query); an unselected canvas isolates the texture cache under test.
app.run("edit.deselectAll", json!({})).unwrap();
let mut pixels = None;
for _ in 0..3 {
pixels = draw(&ctx, &mut app).or(pixels);
}
let old_pixels = pixels.expect("the fallback texture must be uploaded");
let old_ink = ink(&old_pixels);
assert!(old_ink > 0, "the fallback draws the bundled X outlines");
let shown_doc = app.session.doc().unwrap().doc.clone();
let before = app.canvas.pixels_generation;
assert!(before > 0 && app.canvas.texture.is_some());
let _ = draw(&ctx, &mut app);
assert_eq!(app.canvas.pixels_generation, before, "the unchanged pre-publication texture is reused");
let composed = app.session.cache.composed_for(&shown_doc, sid).unwrap();
assert!(composed.frames.iter().flat_map(|f| &f.lines).flat_map(|l| &l.glyphs).all(|g| g.face.style != "Catalog Only"));
let shown = app.canvas.shown.unwrap();
let [w, h] = app.canvas.texture.as_ref().unwrap().size();
let layout = designcraft_tools::CanvasLayout::new(&shown_doc, false);
let job = || render_worker::Job {
token: 7,
doc: shown_doc.clone(),
cache: app.session.cache.clone(),
placed: layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect(),
w: w as u32,
h: h as u32,
view: Affine::scale(ctx.pixels_per_point() as f64 * shown.zoom) * Affine::translate((-shown.origin.x, -shown.origin.y)),
opts: designcraft_render::RenderOptions {
greek_below_px: 3.0 * ctx.pixels_per_point() as f64,
quality: app.ui.display_quality,
rich_black: app.ui.rich_black,
blend_space_view: !app.ui.proof_colors,
..Default::default()
},
};
let worker = completed_worker(job());
let old = worker.poll().unwrap();
assert!(
old.image.pixels.iter().copied().eq(old_pixels.iter().flat_map(|p| p.to_array())),
"the queued result must carry the same fallback pixels as the displayed canvas"
);
drop(worker);
// Queue the identical job again so its completed old pixels reach the real delivery path.
app.canvas.worker = Some(completed_worker(job()));
app.canvas.pending = Some((7, shown));
app.canvas.pending_doc = Some(shown_doc.clone());
(app, sid, before, shown_doc, old_ink)
})
.expect("the subprocess must own a fresh initial catalog");
assert!(db.system_fonts_cataloged());
let doc_key = app.canvas.shown.unwrap().doc;
let pixels = draw(&ctx, &mut app).expect("catalog completion must upload a new canvas");
assert!(ink(&pixels) < old_ink, "the old fallback outlines must leave the displayed texture, including an obsolete completed worker result");
assert_eq!(app.canvas.shown.unwrap().doc, doc_key, "catalog completion does not change the document revision");
assert!(Arc::ptr_eq(&shown_doc, &app.session.doc().unwrap().doc), "catalog completion is not a document edit");
assert!(app.canvas.pending.is_none() && app.canvas.pending_doc.is_none(), "obsolete requests must be retired");
let after = app.session.cache.composed_for(&shown_doc, sid).expect("the canvas must actually render against the completed catalog");
let glyphs: Vec<_> = after.frames.iter().flat_map(|f| &f.lines).flat_map(|l| &l.glyphs).collect();
assert!(!glyphs.is_empty());
assert!(glyphs.iter().all(|g| g.face.style == "Catalog Only"));
assert!(app.canvas.pixels_generation > before);
let ready = app.canvas.pixels_generation;
let _ = draw(&ctx, &mut app);
assert_eq!(app.canvas.pixels_generation, ready, "the completed catalog does not rerender an unchanged canvas every frame");
}
+2
View File
@@ -1,4 +1,6 @@
#[cfg(not(target_arch = "wasm32"))]
mod color_profiles_restart;
#[cfg(not(target_arch = "wasm32"))]
mod initial_font_catalog;
#[cfg(not(target_arch = "wasm32"))]
mod native_job_lifetime_control;