From d4e78bc29a9fe99e2a4238b9cf725ca304c58128 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 13:01:52 +0800 Subject: [PATCH] Select named XeTeX faces by optical size --- .../src/execution/engine/paragraphs.rs | 4 +- crates/texrra-tex-core/src/execution/mod.rs | 10 ++ crates/texrra-tex-core/src/opentype.rs | 34 ++++- .../texrra-tex-core/src/opentype/font_info.rs | 40 ++++- .../src/resources/named_fonts.rs | 137 +++++++++++++++--- .../tests/execution_xetex_profile.rs | 46 ++++++ docs/P2_M1_PROGRESS.md | 28 ++++ src/native_checkpoint_probe.rs | 11 +- src/native_job.rs | 11 +- 9 files changed, 290 insertions(+), 31 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs index 93e23ca..f1a6277 100644 --- a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs +++ b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs @@ -734,7 +734,9 @@ impl Executor { let Some(request) = crate::opentype::NamedRequest::parse(&file) else { return Ok(None); }; - let Some(font) = SourceProvider::named_font(files, request.name, request.style, &from)? else { + let Some(font) = SourceProvider::named_font_with_size( + files, request.name, request.style, request.optical_points(size), &from, + )? else { return Ok(None); }; let (spec, selected) = request.request(&font)?; diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 73659fb..637f6b5 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -282,6 +282,16 @@ pub trait SourceProvider { ) -> Result, String> { Ok(None) } + /// Apply an explicit optical size in TeX points, or the named face's default. + fn named_font_with_size( + &mut self, + name: &str, + style: crate::resources::FontStyle, + _optical_points: Option, + from: &str, + ) -> Result, String> { + self.named_font(name, style, from) + } /// Resolve the exact PostScript name of a PDF TrueType device font. fn pdf_truetype( &mut self, diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index b87f5c9..44514bc 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -22,7 +22,7 @@ mod font_info; mod graphite; mod tags; pub(crate) mod vertical; -pub(crate) use font_info::LayoutTags; +pub(crate) use font_info::{LayoutTags, OpticalSize, optical_size}; mod math_layout; pub(crate) use math_layout::{MathConstants, ScriptSide, Stretch, accent_attachment, script_kern, single_glyph, stretch_glyph}; @@ -63,6 +63,22 @@ fn read_decimal_prefix(value: &str) -> f64 { value[..end].parse().unwrap_or(0.) } +fn read_optical_points(value: &str) -> f64 { + let mut digits = value.bytes().peekable(); + let mut points = 0.0; + while let Some(digit) = digits.next_if(u8::is_ascii_digit) { + points = points * 10.0 + f64::from(digit - b'0'); + } + if digits.next_if_eq(&b'.').is_some() { + let mut denominator = 1.0; + while let Some(digit) = digits.next_if(u8::is_ascii_digit) { + denominator *= 10.0; + points += f64::from(digit - b'0') / denominator; + } + } + points +} + fn read_device_factor(value: &str, option: &str, identity: f32) -> Result, String> { let value = read_decimal_prefix(value) as f32; if !value.is_finite() || i32::try_from(points_to_sp(value)).is_err() { @@ -232,6 +248,7 @@ impl Request { pub(crate) struct NamedRequest<'a> { pub name: &'a str, pub style: crate::resources::FontStyle, + optical_points: Option, options: String, } @@ -245,6 +262,7 @@ impl<'a> NamedRequest<'a> { } let mut style = crate::resources::FontStyle::default(); let mut options = String::new(); + let mut optical_points = None; for part in parts { match part { "OT" | "ICU" => options.push_str("/OT"), @@ -252,6 +270,11 @@ impl<'a> NamedRequest<'a> { "B" => style.bold = true, "I" => style.italic = true, "BI" | "IB" => style = crate::resources::FontStyle { bold: true, italic: true }, + part if part.starts_with('S') => { + let value = &part[1..]; + let value = value.strip_prefix('=').unwrap_or(value); + optical_points = Some(read_optical_points(value)); + } _ => return None, } } @@ -259,7 +282,14 @@ impl<'a> NamedRequest<'a> { options.push(':'); options.push_str(features); } - Some(Self { name, style, options }) + Some(Self { name, style, optical_points, options }) + } + + pub(crate) fn optical_points(&self, size: FontSize) -> Option { + self.optical_points.or(match size { + FontSize::At(size) => Some(size as f64 / 65_536.0), + FontSize::Design | FontSize::Scaled(_) => None, + }) } pub(crate) fn request(&self, font: &crate::resources::NamedFont) -> Result<(String, Request), String> { diff --git a/crates/texrra-tex-core/src/opentype/font_info.rs b/crates/texrra-tex-core/src/opentype/font_info.rs index b03b820..a54ad67 100644 --- a/crates/texrra-tex-core/src/opentype/font_info.rs +++ b/crates/texrra-tex-core/src/opentype/font_info.rs @@ -5,19 +5,38 @@ use read_fonts::{ tables::{gpos::Gpos, layout::FeatureParams}, }; +#[derive(Clone, Copy)] +pub(crate) struct OpticalSize { + design: u16, + pub(crate) subfamily: u16, + min: u16, + max: u16, +} + +impl OpticalSize { + fn points(size: u16) -> f64 { + f64::from(size) * 72.27 / 72.0 / 10.0 + } + + pub(crate) fn design_points(self) -> f64 { + Self::points(self.design) + } + + pub(crate) fn mismatch(self, points: f64) -> f64 { + (Self::points(self.min) - points).max(points - Self::points(self.max)) + } +} + pub(super) fn design_size(face: &ttf_parser::Face<'_>) -> i64 { - let optical_size = face - .raw_face() - .table(Tag::from_bytes(b"GPOS")) - .and_then(optical_design_decipoints); - optical_size.map_or(10 * 65_536, |size| { + optical_size(face).map_or(10 * 65_536, |size| { // The GPOS size feature uses tenths of a PostScript point. // XeTeX converts to TeX points and rounds to a scaled point. - (i64::from(size) * 7_227 * 65_536 + 36_000) / 72_000 + (i64::from(size.design) * 7_227 * 65_536 + 36_000) / 72_000 }) } -fn optical_design_decipoints(gpos: &[u8]) -> Option { +pub(crate) fn optical_size(face: &ttf_parser::Face<'_>) -> Option { + let gpos = face.raw_face().table(Tag::from_bytes(b"GPOS"))?; let features = Gpos::read(FontData::new(gpos)).ok()?.feature_list().ok()?; features .feature_records() @@ -38,7 +57,12 @@ fn optical_design_decipoints(gpos: &[u8]) -> Option { let end = params.range_end(); let design_only = [family, name, start, end] == [0; 4]; let valid_range = (start..=end).contains(&size) && (256..=32767).contains(&name); - (size != 0 && (design_only || valid_range)).then_some(size) + (size != 0 && (design_only || valid_range)).then_some(OpticalSize { + design: size, + subfamily: family, + min: start, + max: end, + }) }) } diff --git a/crates/texrra-tex-core/src/resources/named_fonts.rs b/crates/texrra-tex-core/src/resources/named_fonts.rs index ee5d244..45589c6 100644 --- a/crates/texrra-tex-core/src/resources/named_fonts.rs +++ b/crates/texrra-tex-core/src/resources/named_fonts.rs @@ -1,5 +1,6 @@ //! Named OpenType faces from the host catalogue or an atomic project. use super::*; +use crate::opentype::{OpticalSize, optical_size}; use rustybuzz::ttf_parser::{self, name_id}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -32,6 +33,10 @@ pub(super) struct NamedFace { impl NamedFace { fn at(path: &Path, data: &[u8], index: u32) -> Option { let face = ttf_parser::Face::parse(data, index).ok()?; + Self::from_face(path, &face, index) + } + + fn from_face(path: &Path, face: &ttf_parser::Face<'_>, index: u32) -> Option { let name = |id| { face.names() .into_iter() @@ -110,12 +115,35 @@ impl FontDirectory { } } +struct NamedSelection { + design_base: Option, + preferred: NamedFace, + family: Vec, +} + +struct OpenedFace { + file: SnapshotFile, + index: u32, + full_name: String, + optical: Option, +} + +impl OpenedFace { + fn into_font(self) -> NamedFont { + NamedFont { + resource: self.file.into_loaded(), + index: self.index, + full_name: self.full_name, + } + } +} + fn matching_face( scoped: &[NamedFace], name: &str, style: FontStyle, candidates: &mut Vec, -) -> Option { +) -> Option { let mut matches: Vec<_> = scoped .iter() .filter_map(|face| { @@ -130,7 +158,7 @@ fn matching_face( .collect(); matches.sort_by(|a, b| (a.0, a.1, a.2, a.3).cmp(&(b.0, b.1, b.2, b.3))); candidates.extend(matches.iter().map(|(_, _, path, _, _)| (*path).clone())); - let (_, _, _, _, base) = matches.first()?; + let (priority, _, _, _, base) = matches.first()?; let face = if style.bold || style.italic { let bold = style.bold || base.bold; let italic = style.italic || base.italic; @@ -145,7 +173,22 @@ fn matching_face( if !candidates.contains(&face.path) { candidates.push(face.path.clone()); } - Some((*face).clone()) + let mut family: Vec<_> = scoped + .iter() + .filter(|other| { + !face.family.is_empty() + && other.family == face.family + && (other.path != face.path || other.index != face.index) + }) + .cloned() + .collect(); + family.sort_by(|a, b| (&a.style, &a.path, a.index).cmp(&(&b.style, &b.path, b.index))); + Some(NamedSelection { + // A family-only match uses the manager's 10pt nominal size. + design_base: (*priority < 3).then(|| (*base).clone()), + preferred: (*face).clone(), + family, + }) } #[derive(Clone, Copy)] @@ -294,9 +337,20 @@ impl FileWorld { name: &str, style: FontStyle, from: &Path, + ) -> Result, String> { + self.read_named_font_with_size(name, style, None, from) + } + + /// Resolve a named font after applying its optical family size ranges. + pub fn read_named_font_with_size( + &mut self, + name: &str, + style: FontStyle, + optical_points: Option, + from: &Path, ) -> Result, String> { let mut candidates = Vec::new(); - let result = self.select_named_face(name, style, from, &mut candidates); + let result = self.select_named_face(name, style, optical_points, from, &mut candidates); self.trace.lookups.push(ResourceLookup { kind: ResourceKind::OpenType, name: name.into(), @@ -445,6 +499,7 @@ impl FileWorld { &mut self, name: &str, style: FontStyle, + optical_points: Option, from: &Path, candidates: &mut Vec, ) -> Result, String> { @@ -484,16 +539,17 @@ impl FileWorld { } self.project_named_fonts.as_deref().unwrap_or_default() } else { - return self.select_host_or_directory_font(name, style, from, candidates); + return self.select_host_or_directory_font(name, style, optical_points, from, candidates); }; let face = matching_face(scoped, name, style, candidates); - self.open_named_face(face) + self.open_named_selection(face, optical_points, candidates) } fn select_host_or_directory_font( &mut self, name: &str, style: FontStyle, + optical_points: Option, from: &Path, candidates: &mut Vec, ) -> Result, String> { @@ -502,7 +558,7 @@ impl FileWorld { } if let Some(faces) = &self.system_fonts { let face = matching_face(faces.as_ref().map_err(Clone::clone)?, name, style, candidates); - if let Some(font) = self.open_named_face(face)? { + if let Some(font) = self.open_named_selection(face, optical_points, candidates)? { return Ok(Some(font)); } } @@ -521,7 +577,7 @@ impl FileWorld { continue; } let face = matching_face(self.directory_faces(&scope)?, name, style, candidates); - if let Some(font) = self.open_named_face(face)? { + if let Some(font) = self.open_named_selection(face, optical_points, candidates)? { return Ok(Some(font)); } searched.push(scope); @@ -602,33 +658,78 @@ impl FileWorld { .cloned().collect()) } - fn open_named_face(&mut self, face: Option) -> Result, String> { - let Some(face) = face else { return Ok(None) }; + fn open_named_selection( + &mut self, + selection: Option, + optical_points: Option, + candidates: &mut Vec, + ) -> Result, String> { + let Some(selection) = selection else { return Ok(None) }; + let Some(mut best) = self.open_named_face(&selection.preferred)? else { return Ok(None) }; + let Some(range) = best.optical.filter(|size| size.subfamily != 0) else { + return Ok(Some(best.into_font())); + }; + let points = match (optical_points, selection.design_base) { + (Some(points), _) => points, + (None, Some(base)) if base.path == selection.preferred.path + && base.index == selection.preferred.index => range.design_points(), + (None, Some(base)) => self.open_named_face(&base)? + .and_then(|face| face.optical).map_or(10.0, OpticalSize::design_points), + (None, None) => 10.0, + }; + let mut mismatch = range.mismatch(points); + if points > 0.0 && mismatch > 0.0 { + for sibling in &selection.family { + if !candidates.contains(&sibling.path) { + candidates.push(sibling.path.clone()); + } + let Some(candidate) = self.open_named_face(sibling)? else { continue }; + let Some(other) = candidate.optical.filter(|size| size.subfamily == range.subfamily) + else { continue }; + let distance = other.mismatch(points); + if distance < mismatch { + best = candidate; + mismatch = distance; + if mismatch <= 0.0 { + break; + } + } + } + } + Ok(Some(best.into_font())) + } + + fn open_named_face(&mut self, face: &NamedFace) -> Result, String> { let Some(path) = self.probe(&face.path)? else { return Ok(None); }; - let resource = self.read_path(path)?; - if face.version.as_ref().is_some_and(|version| version != &resource.version) { - return Err(format!("named font directory changed for {}", resource.version.path.display())); + let file = self.read_shared_path(path)?; + if face.version.as_ref().is_some_and(|version| version != &file.version) { + return Err(format!("named font directory changed for {}", file.version.path.display())); } + let parsed = ttf_parser::Face::parse(&file.data, face.index).map_err(|error| { + format!("named font face {} in {}: {error}", face.index, file.version.path.display()) + })?; let actual = - NamedFace::at(&resource.version.path, &resource.data, face.index).ok_or_else(|| { + NamedFace::from_face(&file.version.path, &parsed, face.index).ok_or_else(|| { format!( "named font has no valid face {} in {}", face.index, - resource.version.path.display() + file.version.path.display() ) })?; if !face.postscript.is_empty() && face.postscript != actual.postscript { return Err(format!( "named font catalogue changed for {}", - resource.version.path.display() + file.version.path.display() )); } - Ok(Some(NamedFont { - resource, + let optical = optical_size(&parsed); + Ok(Some(OpenedFace { + file, index: face.index, full_name: actual.full_name, + optical, })) } diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 7cd3b66..3ea5367 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -84,6 +84,52 @@ fn opentype_design_and_scaled_requests_share_actual_sized_instances() { assert_eq!(messages(&result), ["657818/484811/655360", "SAME/SAME/DIFFERENT"]); } +#[test] +fn named_optical_lookup_reconsiders_new_faces_and_tracks_compared_resources() { + use std::{fs, process::Command, sync::Arc}; + use texrra_tex_core::resources::{ + FileWorld, FontStyle, ProjectDefinition, ProjectSnapshot, ResourceKind, SearchPath, + WorldConfig, + }; + + let root = std::env::temp_dir().canonicalize().unwrap().join("texrra-optical-catalogue"); + let load = |name: &str| { + let found = Command::new("kpsewhich").arg(name).output().unwrap(); + assert!(found.status.success(), "missing reference font {name}"); + Arc::<[u8]>::from(fs::read(String::from_utf8(found.stdout).unwrap().trim()).unwrap()) + }; + let base = root.join("lmroman10-regular.otf"); + let distant = root.join("lmroman17-regular.otf"); + let covering = root.join("lmroman12-regular.otf"); + let mut configuration = WorldConfig::new(&root); + configuration.paths.insert(ResourceKind::OpenType, vec![SearchPath::directory(&root, false)]); + let project = ProjectSnapshot::new(ProjectDefinition { + configuration, revision: 1, roots: [root.clone()].into(), + files: [ + (base.clone(), load("lmroman10-regular.otf")), + (distant.clone(), load("lmroman17-regular.otf")), + ].into(), + directories: Default::default(), aliases: Default::default(), + generated_roots: Default::default(), generated: Default::default(), + }).unwrap(); + let with_covering = project.with_file_changes( + 2, [(covering.clone(), Some(load("lmroman12-regular.otf")))].into(), + ).unwrap(); + for (snapshot, expected, compared) in [ + (project, &base, &distant), (with_covering, &covering, &covering), + ] { + let mut world = FileWorld::from_project(snapshot.clone()).unwrap(); + let font = world.read_named_font_with_size( + "LMRoman10-Regular", FontStyle::default(), Some(12.5), &root.join("main.tex"), + ).unwrap().unwrap(); + assert_eq!(&font.resource.version.path, expected); + assert_eq!(world.trace().reads, [ + snapshot.file(&base).unwrap().version.clone(), + snapshot.file(compared).unwrap().version.clone(), + ]); + } +} + #[test] fn xetex_primitives_follow_each_profiles_language_and_device() { let tex = r"\catcode123=1 \catcode125=2 diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 80b5687..c691703 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,34 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeTeX 同族字体的光学版本选择 + +按名称装载字体时,从同族候选字体的 GPOS `size` 读取光学组和适用范围。 +范围覆盖请求字号时选用该字体,范围均未覆盖时保留距离最近的候选。 +`at` 与 `/S=` 可指定光学字号,`/S=0` 关闭这次光学选择。未显式指定 +时按名字初次匹配的设计字号查找,按族名匹配使用 10 pt。`scaled` +仍以最终字体面的设计字号计算排版字号,方括号写法直接装载指定文件。 + +原冻结用例的 `LMRoman10-Regular at13pt` 现在选中 LM Roman 12, +44 个字形的字体身份、字号及坐标、12 个词框和 144 DPI 灰度图均与 +XeTeX 一致。扩展用例用宿主字体目录和项目配置目录各执行一次,覆盖 +默认字号、光学覆盖、缩放、按文件加载、按族名、最近范围及斜体。 +两条查找路径各有 102 个字形和 16 个词框与同一份参考逐项一致, +两份灰度图亦与参考一致。原样 ACL 的 PDF、布局清单和辅助文件 +复编一致。14 项 XeTeX 定向测试通过。 + +实际比较过的字体版本进入依赖记录。三页会话中,仅修改子文件注释时 +复用 2,176 步且无页差量。添加覆盖目标字号的字体时,重放检查识别 +选中结果变化,本轮重新执行全文,仍只发出第 2 页。移除该字体和 +替换先前比较过的未选中字体时,各复用 743 步且只发出第 2 页。 +四轮的 PDF、页面、SVG、辅助文件和来源映射均与独立全量一致。 +待处理的会话优化是新候选改变查找结果后继续尝试更早的有效检查点。 + +冻结输入、原始布局及修订记录在 `target/p3-xetex-named-optical`, +`receipt.json` 的 SHA-256 为 +`bb860734e4ab0b183d084b1c2d5da95cde7a2ac7abb79149702dd7dcf8fad1d6`。 +[XeTeX 的光学范围选择](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/XeTeXFontMgr.cpp#L311-L360) + ## 2026-11-28 XeTeX OpenType 设计字号 从已选字体面的真实 GPOS `size` 参数读取设计字号,沿用现有 diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 174a283..f0b387b 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -148,9 +148,18 @@ impl SourceProvider for RecordingHost<'_> { name: &str, style: texrra_tex_core::resources::FontStyle, from: &str, + ) -> Result, String> { + self.named_font_with_size(name, style, None, from) + } + fn named_font_with_size( + &mut self, + name: &str, + style: texrra_tex_core::resources::FontStyle, + optical_points: Option, + from: &str, ) -> Result, String> { let (name, from) = (name.to_owned(), from.to_owned()); - call!(self, named_font(&name, style, &from); |result| { + call!(self, named_font_with_size(&name, style, optical_points, &from); |result| { result.as_ref().map(|result| result.as_ref().map(|font| { (font.resource.version.clone(), font.index, font.full_name.clone()) })).map_err(Clone::clone) diff --git a/src/native_job.rs b/src/native_job.rs index 74a5d05..333b72e 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -1685,7 +1685,16 @@ impl SourceProvider for Files { style: texrra_tex_core::resources::FontStyle, from: &str, ) -> Result, String> { - let selected = self.world.read_named_font(name, style, Path::new(from))?; + self.named_font_with_size(name, style, None, from) + } + fn named_font_with_size( + &mut self, + name: &str, + style: texrra_tex_core::resources::FontStyle, + optical_points: Option, + from: &str, + ) -> Result, String> { + let selected = self.world.read_named_font_with_size(name, style, optical_points, Path::new(from))?; if let Some(font) = &selected { let kind = match font.resource.version.path.extension().and_then(|ext| ext.to_str()) { Some(ext) if ext.eq_ignore_ascii_case("ttf") || ext.eq_ignore_ascii_case("ttc") => ResourceKind::TrueType,