Reuse verified Type 1 glyph and PDF subset output across edits
This commit is contained in:
1 parent
6939ff71ff
commit
11c8ad1eaa
12 files changed
+236
-11
No files matched your search
@@ -1924,6 +1924,7 @@ impl State {
|
||||
fonts: &self.fonts,
|
||||
page_tree_attributes: &self.pdf_pages_attributes,
|
||||
xdv_glyph_names: None,
|
||||
font_cache: None,
|
||||
xdv_font_unicode: self.input_profile == super::InputProfile::XeTeX,
|
||||
xdv_keep_destinations: self.xdv_setup.keep_destinations,
|
||||
xdv_outline_open_depth: self.xdv_setup.outline_open_depth.unwrap_or_default(),
|
||||
|
||||
@@ -19,11 +19,13 @@ mod device_type1;
|
||||
mod map;
|
||||
mod sfd;
|
||||
mod truetype;
|
||||
mod type1_cache;
|
||||
mod virtual_paint;
|
||||
pub use cff::OpenTypeCffProgram;
|
||||
pub use composite_type1::CompositeType1Program;
|
||||
pub use device_type1::DeviceType1Program;
|
||||
pub use truetype::TrueTypeProgram;
|
||||
pub use type1_cache::Type1FontWork;
|
||||
pub(crate) use truetype::cid_width;
|
||||
pub use map::PdfFontBindings;
|
||||
pub(crate) use map::XdvFontMatrix;
|
||||
@@ -305,15 +307,17 @@ pub(crate) fn verify_resource(
|
||||
const MAX_TYPE1_PROGRAMS: usize = 16;
|
||||
const MAX_CACHED_TYPE1_BYTES: usize = 256 * 1024;
|
||||
|
||||
/// Decoded Type 1 programs shared across revisions in one compiler.
|
||||
/// Verified Type 1 programs and derived device data shared across revisions.
|
||||
#[derive(Default)]
|
||||
pub struct NativeFontCache {
|
||||
type1: Mutex<VecDeque<((ResourceVersion, Type1Transform), Arc<DecodedType1>)>>,
|
||||
type1_output: type1_cache::Type1OutputCache,
|
||||
}
|
||||
|
||||
struct DecodedType1 {
|
||||
program: Arc<Type1Font>,
|
||||
outlines: Type1Outlines,
|
||||
glyphs: Mutex<type1_cache::GlyphMeasurements>,
|
||||
bbox: [i32; 4],
|
||||
stem_v: i32,
|
||||
xdv_descriptor: OnceLock<Result<XdvDescriptor, String>>,
|
||||
@@ -334,6 +338,7 @@ impl DecodedType1 {
|
||||
Ok(Self {
|
||||
program: Arc::new(program),
|
||||
outlines,
|
||||
glyphs: Mutex::default(),
|
||||
bbox,
|
||||
stem_v,
|
||||
xdv_descriptor: OnceLock::new(),
|
||||
@@ -758,7 +763,7 @@ fn resolve_physical_fonts(
|
||||
font.name
|
||||
));
|
||||
}
|
||||
let (path, width) = outlines.glyph_path_and_width(name)?;
|
||||
let (path, width) = font_cache.type1_glyph(decoded, name)?;
|
||||
paint.glyph_paths.insert(slot, path);
|
||||
if paint.xdv_descriptor.is_some() {
|
||||
paint.xdv_widths.insert(slot, width);
|
||||
|
||||
@@ -62,7 +62,7 @@ pub(super) fn resolve(
|
||||
let mut cells = Vec::with_capacity(256);
|
||||
let mut glyph_paths = BTreeMap::new();
|
||||
let mut measured = BTreeMap::new();
|
||||
let (_, default_width) = outlines.glyph_path_and_width(".notdef")?;
|
||||
let (_, default_width) = cache.type1_glyph(&decoded, ".notdef")?;
|
||||
let width = |value: i64| {
|
||||
value
|
||||
.saturating_add(5)
|
||||
@@ -88,7 +88,7 @@ pub(super) fn resolve(
|
||||
let (path, advance) = match measured.entry(cid) {
|
||||
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
|
||||
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||
entry.insert(outlines.glyph_path_and_width(name)?)
|
||||
entry.insert(cache.type1_glyph(&decoded, name)?)
|
||||
}
|
||||
};
|
||||
glyph_paths.insert(slot, path.clone());
|
||||
|
||||
@@ -122,7 +122,7 @@ pub(super) fn resolve(
|
||||
for slot in slots {
|
||||
let glyph = &encoding[usize::from(slot)];
|
||||
if preview.outlines.has_glyph(glyph) {
|
||||
glyph_paths.insert(slot, preview.outlines.glyph_path(glyph)?);
|
||||
glyph_paths.insert(slot, cache.type1_glyph(preview, glyph)?.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Device output derived from verified Type 1 programs within a session.
|
||||
use super::{DecodedType1, NativeFontCache, Type1ProgramKey};
|
||||
use crate::{
|
||||
resources::ResourceVersion,
|
||||
type1::{Type1Font, Type1Transform},
|
||||
type1_outline::{SubsetProgram, write_subset},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering::Relaxed},
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_GLYPH_BYTES_PER_PROGRAM: usize = 256 * 1024;
|
||||
const MAX_GLYPHS_PER_PROGRAM: usize = 512;
|
||||
const MAX_SUBSETS: usize = 32;
|
||||
const MAX_SUBSET_PROGRAM_BYTES: usize = 64 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Type1FontWork {
|
||||
pub glyphs_measured: usize,
|
||||
pub glyphs_reused: usize,
|
||||
pub subsets_written: usize,
|
||||
pub subsets_reused: usize,
|
||||
}
|
||||
|
||||
impl Type1FontWork {
|
||||
pub fn since(self, earlier: Self) -> Self {
|
||||
Self {
|
||||
glyphs_measured: self.glyphs_measured.saturating_sub(earlier.glyphs_measured),
|
||||
glyphs_reused: self.glyphs_reused.saturating_sub(earlier.glyphs_reused),
|
||||
subsets_written: self.subsets_written.saturating_sub(earlier.subsets_written),
|
||||
subsets_reused: self.subsets_reused.saturating_sub(earlier.subsets_reused),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Type1OutputCache {
|
||||
glyphs_measured: AtomicUsize,
|
||||
glyphs_reused: AtomicUsize,
|
||||
subsets_written: AtomicUsize,
|
||||
subsets_reused: AtomicUsize,
|
||||
subsets: Mutex<VecDeque<CachedSubset>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct GlyphMeasurements {
|
||||
values: BTreeMap<String, (String, i64)>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
struct CachedSubset {
|
||||
version: ResourceVersion,
|
||||
transform: Type1Transform,
|
||||
font: Type1Font,
|
||||
glyphs: BTreeSet<String>,
|
||||
all_glyphs: bool,
|
||||
tag: String,
|
||||
subset: Arc<SubsetProgram>,
|
||||
}
|
||||
|
||||
impl NativeFontCache {
|
||||
pub fn type1_work(&self) -> Type1FontWork {
|
||||
let work = &self.type1_output;
|
||||
Type1FontWork {
|
||||
glyphs_measured: work.glyphs_measured.load(Relaxed),
|
||||
glyphs_reused: work.glyphs_reused.load(Relaxed),
|
||||
subsets_written: work.subsets_written.load(Relaxed),
|
||||
subsets_reused: work.subsets_reused.load(Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn type1_glyph(
|
||||
&self,
|
||||
decoded: &DecodedType1,
|
||||
name: &str,
|
||||
) -> Result<(String, i64), String> {
|
||||
let mut measurements = decoded.glyphs.lock().expect("Type 1 glyph cache poisoned");
|
||||
if let Some(glyph) = measurements.values.get(name) {
|
||||
self.type1_output.glyphs_reused.fetch_add(1, Relaxed);
|
||||
return Ok(glyph.clone());
|
||||
}
|
||||
let glyph = decoded.outlines.glyph_path_and_width(name)?;
|
||||
self.type1_output.glyphs_measured.fetch_add(1, Relaxed);
|
||||
let needed = name.len().saturating_add(glyph.0.len());
|
||||
if needed <= MAX_GLYPH_BYTES_PER_PROGRAM - measurements.bytes
|
||||
&& measurements.values.len() < MAX_GLYPHS_PER_PROGRAM
|
||||
{
|
||||
measurements.values.insert(name.to_owned(), glyph.clone());
|
||||
measurements.bytes += needed;
|
||||
}
|
||||
Ok(glyph)
|
||||
}
|
||||
|
||||
pub(crate) fn type1_subset(
|
||||
&self,
|
||||
(version, transform): Type1ProgramKey<'_>,
|
||||
font: &Type1Font,
|
||||
glyphs: &BTreeSet<String>,
|
||||
all_glyphs: bool,
|
||||
tag: &str,
|
||||
) -> Result<Arc<SubsetProgram>, String> {
|
||||
let cacheable = font.program.len() <= MAX_SUBSET_PROGRAM_BYTES
|
||||
&& glyphs.len() <= MAX_GLYPHS_PER_PROGRAM
|
||||
&& glyphs.iter().all(|name| name.len() <= 128);
|
||||
let work = &self.type1_output;
|
||||
if !cacheable {
|
||||
let subset = write_subset(font, glyphs, all_glyphs, tag)?;
|
||||
work.subsets_written.fetch_add(1, Relaxed);
|
||||
return Ok(Arc::new(subset));
|
||||
}
|
||||
let mut subsets = work.subsets.lock().expect("Type 1 subset cache poisoned");
|
||||
if let Some(index) = subsets.iter().position(|prior| {
|
||||
prior.version == *version
|
||||
&& prior.transform == transform
|
||||
&& prior.tag == tag
|
||||
&& prior.all_glyphs == all_glyphs
|
||||
&& prior.glyphs == *glyphs
|
||||
&& prior.font == *font
|
||||
}) {
|
||||
let hit = subsets.remove(index).expect("cached Type 1 subset exists");
|
||||
let subset = hit.subset.clone();
|
||||
subsets.push_back(hit);
|
||||
work.subsets_reused.fetch_add(1, Relaxed);
|
||||
return Ok(subset);
|
||||
}
|
||||
let subset = Arc::new(write_subset(font, glyphs, all_glyphs, tag)?);
|
||||
work.subsets_written.fetch_add(1, Relaxed);
|
||||
if subset.program.len() <= MAX_SUBSET_PROGRAM_BYTES {
|
||||
if subsets.len() == MAX_SUBSETS {
|
||||
subsets.pop_front();
|
||||
}
|
||||
subsets.push_back(CachedSubset {
|
||||
version: version.clone(),
|
||||
transform,
|
||||
font: font.clone(),
|
||||
glyphs: glyphs.clone(),
|
||||
all_glyphs,
|
||||
tag: tag.into(),
|
||||
subset: subset.clone(),
|
||||
});
|
||||
}
|
||||
Ok(subset)
|
||||
}
|
||||
}
|
||||
@@ -2658,7 +2658,8 @@ fn write_pdf(
|
||||
|| native_type1_parameters(program, owner_paint, owner.metrics()), glyphs);
|
||||
}
|
||||
let omit_charset = unicode.is_some_and(|options| options.omit_charset);
|
||||
let type1_references = type1_plans.write(&mut objects, compression, omit_charset, |key| {
|
||||
let font_cache = unicode.and_then(|options| options.font_cache);
|
||||
let type1_references = type1_plans.write(&mut objects, compression, omit_charset, font_cache, |key| {
|
||||
let (descriptor, name) = registry?.imported_type1_slots(key)?;
|
||||
let physical = |number| device_objects[&number] as usize;
|
||||
Some((physical(descriptor), name.map(physical)))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Document-wide physical Type 1 embeddings for TeX glyphs and included PDFs.
|
||||
use super::{native_pdf_name, objects};
|
||||
use crate::{
|
||||
native_font::Type1ProgramKey,
|
||||
native_font::{NativeFontCache, Type1ProgramKey},
|
||||
pdf_image::ImportedType1Use,
|
||||
type1::Type1Font,
|
||||
type1_outline::{subset_tag, write_subset, write_type1c},
|
||||
@@ -9,6 +9,7 @@ use crate::{
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, HashMap},
|
||||
fmt::Write as _,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub(crate) struct Reference {
|
||||
@@ -85,6 +86,7 @@ impl<'a> FontPlans<'a> {
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
compression: u8,
|
||||
omit_charset: bool,
|
||||
font_cache: Option<&NativeFontCache>,
|
||||
reserved: impl Fn(Type1ProgramKey<'a>) -> Option<(usize, Option<usize>)>,
|
||||
) -> Result<References<'a>, String> {
|
||||
let mut plans: Vec<_> = self.0.into_iter().collect();
|
||||
@@ -107,7 +109,11 @@ impl<'a> FontPlans<'a> {
|
||||
.map(|salt| subset_tag(&plan.font.name, &plan.glyphs, salt))
|
||||
.find(|tag| tags.insert(tag.clone()))
|
||||
.ok_or("Type1 subset name collision limit exceeded")?;
|
||||
let subset = write_subset(plan.font, &plan.glyphs, plan.all_glyphs, &tag)?;
|
||||
let subset = if let Some(cache) = font_cache {
|
||||
cache.type1_subset(key, plan.font, &plan.glyphs, plan.all_glyphs, &tag)?
|
||||
} else {
|
||||
Arc::new(write_subset(plan.font, &plan.glyphs, plan.all_glyphs, &tag)?)
|
||||
};
|
||||
let lengths = [subset.length1, subset.program.len() - subset.length1, 0];
|
||||
Reference {
|
||||
object: write_embedding(
|
||||
@@ -120,7 +126,7 @@ impl<'a> FontPlans<'a> {
|
||||
compression,
|
||||
slots,
|
||||
),
|
||||
name: subset.name,
|
||||
name: subset.name.clone(),
|
||||
name_object,
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -139,6 +139,8 @@ pub struct PdfFinalOptions<'a> {
|
||||
pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>,
|
||||
pub info: crate::pdf_device::PdfInfo<'a>,
|
||||
pub xdv_glyph_names: Option<&'a XdvGlyphNames>,
|
||||
/// Reuse physical font output after current-job resources were resolved.
|
||||
pub font_cache: Option<&'a crate::native_font::NativeFontCache>,
|
||||
pub(crate) xdv_font_unicode: bool,
|
||||
pub(crate) xdv_keep_destinations: bool,
|
||||
pub(crate) xdv_outline_open_depth: usize,
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
|
||||
mod subset;
|
||||
pub(crate) mod cff;
|
||||
pub(crate) use cff::write_type1c;
|
||||
pub(crate) use subset::{subset_tag, write_subset};
|
||||
pub(crate) use subset::{SubsetProgram, subset_tag, write_subset};
|
||||
use subset::{GlyphUse, ProgramRanges, SubrRange};
|
||||
fn decrypt(data: &[u8], mut key: u16, skip: usize) -> Result<Vec<u8>, String> {
|
||||
if data.len() < skip {
|
||||
|
||||
@@ -18,6 +18,29 @@
|
||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||
|
||||
## 2026-11-28 Type 1 字形测量与 PDF 字体子集复用
|
||||
|
||||
Type 1 的实际轮廓和宽度按已校验的字体程序与变换跨修订复用。pdfTeX 的
|
||||
Type 1 嵌入子集还核对程序字节、当前字形集合、嵌入模式和本轮选定的子集名。
|
||||
当前作业仍从项目解析并核对字体、映射和编码。文字、来源定位、PDF 对象
|
||||
编号以及压缩都按当前修订生成。XeTeX 共用 Type 1 字形测量,仍会转换 CFF
|
||||
设备子集。字形数据与子集缓存分别有容量上限。
|
||||
|
||||
定向回归覆盖同一字形集合的文字编辑、新字形、原路径更换 PFB 和资源缺失。
|
||||
新字形只测量新增项并重新生成相应子集,换版采用实际新字体,缺失字体时
|
||||
保留上次 PDF 和预览。三份 XeTeX 对照覆盖复合 Type 1、横竖混排与重音,
|
||||
PDF 与上一版逐字节一致。
|
||||
|
||||
原样 A4 多文件项目冷编译测量 49 个字形、生成两个 Type 1 子集。主文件
|
||||
编辑复用 49 个字形和两个子集。子文件编辑复用 48 个字形和一个子集,另一个
|
||||
子集按当前字形集合重新生成。两次编辑均无新字形测量。库会话与独立全量的
|
||||
PDF、绘制列表、SVG、来源映射、aux 及资源读取版本一致。XeTeX 更改字形表
|
||||
时复用四个轮廓测量,换 PFB 时测量四个新字形,导出等于独立全量。
|
||||
|
||||
本批记录实际测量和子集生成次数。下一批检查格式来源的实际复制和保留成本。
|
||||
正式编辑可见 p95、内存、出版矩阵和产品入口迁移仍按既定顺序验收。
|
||||
本地证据见 target/p4-type1-output-reuse/。
|
||||
|
||||
## 2026-11-28 已出页盒的增量绘制复用
|
||||
|
||||
检查点恢复后按页比对上次发布的出页快照。实际盒列表共享同一份存储,
|
||||
|
||||
@@ -235,6 +235,8 @@ pub struct CompiledDocument {
|
||||
pub line_break_work: texrra_tex_core::execution::LineBreakWork,
|
||||
/// Work converting shipped boxes to local drawing lists before resolving PDF resources.
|
||||
pub shipout_layout_work: ShipoutLayoutWork,
|
||||
/// Type 1 glyph and PDF subset work in this revision.
|
||||
pub type1_font_work: texrra_tex_core::native_font::Type1FontWork,
|
||||
/// Original measurements with actual resolved font programs.
|
||||
pub pages: Vec<DisplayList>,
|
||||
/// Revision-local measured paint and source versions. `unmapped` explicitly
|
||||
@@ -1123,6 +1125,8 @@ impl CompileJob {
|
||||
notify(&request, revision, CompileStage::Executed, &cancellation)?;
|
||||
evidence.phase = AttemptPhase::Layout;
|
||||
let e = &execution.execution;
|
||||
let font_cache = &self.compiler.font_cache;
|
||||
let type1_before = font_cache.type1_work();
|
||||
let prior_layout = (entry_checkpoint_work.reused_steps > 0)
|
||||
.then(|| self.compiler.latest())
|
||||
.flatten();
|
||||
@@ -1257,6 +1261,7 @@ impl CompileJob {
|
||||
} else if request.target == Target::Shipouts {
|
||||
let mut options = e.state.pdf_final_options();
|
||||
options.xdv_glyph_names = xdv_glyph_names.as_ref();
|
||||
options.font_cache = Some(font_cache);
|
||||
let document = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document(
|
||||
&pages,
|
||||
options,
|
||||
@@ -1329,6 +1334,7 @@ impl CompileJob {
|
||||
entry_checkpoint_work,
|
||||
line_break_work,
|
||||
shipout_layout_work,
|
||||
type1_font_work: font_cache.type1_work().since(type1_before),
|
||||
execution,
|
||||
pages,
|
||||
source_map,
|
||||
|
||||
@@ -180,13 +180,37 @@ fn replacing_a_type1_program_at_the_same_path_updates_native_pdf_and_preview() {
|
||||
let before = compiler.compile(request_for_font()).unwrap();
|
||||
assert!(before.resources.trace.reads.contains(&actual_first));
|
||||
let old_svg = before.preview_since(None).unwrap().pages[0].svg.clone();
|
||||
assert!(before.type1_font_work.glyphs_measured > 0);
|
||||
assert_eq!(before.type1_font_work.subsets_written, 1);
|
||||
|
||||
write(&p, r"\shipout\hbox{A stable word A}\end");
|
||||
let warm = compiler.compile(request_for_font()).unwrap();
|
||||
assert_ne!(warm.pdf, before.pdf);
|
||||
assert!(warm.resources.trace.reads.contains(&actual_first));
|
||||
let work = warm.type1_font_work;
|
||||
assert!(work.glyphs_reused > 0, "{work:?}");
|
||||
assert_eq!(work.glyphs_measured, 0);
|
||||
assert_eq!(work.subsets_reused, 1);
|
||||
assert_eq!(work.subsets_written, 0);
|
||||
|
||||
write(&p, r"\shipout\hbox{A stable word z}\end");
|
||||
let expanded = compiler.compile(request_for_font()).unwrap();
|
||||
assert_eq!(expanded.type1_font_work.glyphs_measured, 1);
|
||||
assert_eq!(expanded.type1_font_work.subsets_written, 1);
|
||||
let fresh = NativeCompiler::default().compile(request_for_font()).unwrap();
|
||||
assert_eq!(expanded.pdf, fresh.pdf);
|
||||
assert_eq!(expanded.pages, fresh.pages);
|
||||
|
||||
write(&p, r"\shipout\hbox{A stable word}\end");
|
||||
fs::copy(root.join("cmss10.pfb"), &font).unwrap();
|
||||
let actual_second = file_version(&font).unwrap().unwrap();
|
||||
assert_ne!(actual_first.sha256, actual_second.sha256);
|
||||
let after = compiler.compile(request_for_font()).unwrap();
|
||||
assert!(after.resources.trace.reads.contains(&actual_second));
|
||||
let delta = after.preview_since(Some(before.revision())).unwrap();
|
||||
assert!(after.type1_font_work.glyphs_measured > 0);
|
||||
assert_eq!(after.type1_font_work.subsets_written, 1);
|
||||
assert_eq!(after.type1_font_work.subsets_reused, 0);
|
||||
let delta = after.preview_since(Some(expanded.revision())).unwrap();
|
||||
assert_eq!(delta.pages.len(), 1);
|
||||
assert_ne!(old_svg, delta.pages[0].svg);
|
||||
assert!(before.pdf != after.pdf);
|
||||
@@ -196,6 +220,15 @@ fn replacing_a_type1_program_at_the_same_path_updates_native_pdf_and_preview() {
|
||||
assert!(after.pdf == cold.pdf);
|
||||
assert_eq!(after.source_map.pages, cold.source_map.pages);
|
||||
assert_eq!(before.preview_since(None).unwrap().pages[0].svg, old_svg);
|
||||
|
||||
fs::remove_file(&font).unwrap();
|
||||
let error = compiler.compile(request_for_font()).err().unwrap();
|
||||
assert!(error.to_string().contains("example.pfb"));
|
||||
assert!(Arc::ptr_eq(&after, &compiler.latest().unwrap()));
|
||||
assert_eq!(
|
||||
after.pdf.as_deref().unwrap(),
|
||||
fs::read(p.join("job.pdf")).unwrap()
|
||||
);
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user