diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 6109fce..8576ffa 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -40,6 +40,8 @@ pub(crate) struct Request { extend: Option, #[serde(default, skip_serializing_if = "Option::is_none")] slant: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + embolden: Option, } fn read_decimal_prefix(value: &str) -> f64 { @@ -106,6 +108,7 @@ impl Request { letterspace: None, extend: None, slant: None, + embolden: None, }; for feature in features .split([';', ',']) @@ -135,6 +138,12 @@ impl Request { request.extend = read_device_factor(value, "extend", 1.)?; } else if let Some(value) = feature.strip_prefix("slant=") { request.slant = read_device_factor(value, "slant", 0.)?; + } else if let Some(value) = feature.strip_prefix("embolden=") { + let value = read_decimal_prefix(value) as f32; + if !value.is_finite() { + return Err("invalid OpenType embolden percentage".into()); + } + request.embolden = (value != 0.).then(|| value.to_bits()); } else { feature .parse::() @@ -151,6 +160,13 @@ impl Request { }) } + fn embolden_sp(&self, size: i64) -> i64 { + self.embolden.map_or(0, |bits| { + let percent = f64::from(f32::from_bits(bits)); + points_to_sp((percent * (size as f64 / 65536.) / 100.) as f32) + }) + } + fn horizontal_scale(&self) -> f32 { self.extend.map_or(1., f32::from_bits) } @@ -281,6 +297,9 @@ impl OpenTypeFont { if !letter_space.is_finite() || letter_space.abs() > 1_073_741_823. { return Err("OpenType letterspace exceeds the TeX dimension range".into()); } + if i32::try_from(request.embolden_sp(size)).is_err() { + return Err("OpenType embolden exceeds the device fixed-point range".into()); + } let scale = |value| scale_units(value, size, face.units_per_em()); let [ascent, descent] = sized_face_metrics(&face, size); let xheight = |reported: Option, letter: char, fallback: i64| { @@ -372,6 +391,12 @@ impl OpenTypeFont { self.device_transform().map(|factor| (factor * 100_000.).round() / 100_000.) } + pub(crate) fn paint_embolden(&self) -> f64 { + let width = self.request.embolden_sp(self.size).max(0) as f64 / 65536.; + // The XDV PDF device writes the line width to six decimal places. + (width * 1_000_000.).round() / 1_000_000. + } + pub(crate) fn italic_correction(&self, glyph: u16) -> Result { let face = self.face()?; let glyph = GlyphId(glyph); @@ -769,28 +794,54 @@ impl OpenTypeRun { } } -#[derive(Default)] -struct PathBuilder(String); -impl ttf_parser::OutlineBuilder for PathBuilder { - fn move_to(&mut self, x: f32, y: f32) { - self.0.push_str(&format!("M{x} {y}")); - } - fn line_to(&mut self, x: f32, y: f32) { - self.0.push_str(&format!("L{x} {y}")); - } - fn quad_to(&mut self, a: f32, b: f32, x: f32, y: f32) { - self.0.push_str(&format!("Q{a} {b} {x} {y}")); - } - fn curve_to(&mut self, a: f32, b: f32, c: f32, d: f32, x: f32, y: f32) { - self.0.push_str(&format!("C{a} {b} {c} {d} {x} {y}")); - } - fn close(&mut self) { - self.0.push('Z'); +struct PathBuilder { + path: String, + transform: Option<[f64; 3]>, +} + +impl PathBuilder { + fn command(&mut self, command: char, points: &[[f32; 2]]) { + use std::fmt::Write as _; + + self.path.push(command); + for (index, [x, y]) in points.iter().copied().enumerate() { + if index != 0 { + self.path.push(' '); + } + if let Some([extend, shear, vertical]) = self.transform { + let (x, y) = (f64::from(x), f64::from(y)); + write!(self.path, "{:.9} {:.9}", extend * x + shear * y, vertical * y).unwrap(); + } else { + write!(self.path, "{x} {y}").unwrap(); + } + } } } -pub(crate) fn outline(face: &ttf_parser::Face<'_>, glyph: u16) -> String { - let mut path = PathBuilder::default(); +impl ttf_parser::OutlineBuilder for PathBuilder { + fn move_to(&mut self, x: f32, y: f32) { + self.command('M', &[[x, y]]); + } + fn line_to(&mut self, x: f32, y: f32) { + self.command('L', &[[x, y]]); + } + fn quad_to(&mut self, a: f32, b: f32, x: f32, y: f32) { + self.command('Q', &[[a, b], [x, y]]); + } + fn curve_to(&mut self, a: f32, b: f32, c: f32, d: f32, x: f32, y: f32) { + self.command('C', &[[a, b], [c, d], [x, y]]); + } + fn close(&mut self) { + self.path.push('Z'); + } +} + +pub(crate) fn outline( + face: &ttf_parser::Face<'_>, + glyph: u16, + transform: Option<[f64; 3]>, +) -> String { + let mut path = PathBuilder { path: String::new(), transform }; face.outline_glyph(GlyphId(glyph), &mut path); - path.0 + path.path } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index d03f5e4..272c458 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -739,10 +739,18 @@ fn page_content( } let mut native_text: Option = None; let mut tex_text: Option = None; - let mut opentype_text = None; + let mut opentype_text = opentype_fonts::TextState::default(); + let bp_per_unit = list.units.bp(1); + let one_inch = (72_000. / (bp_per_unit * f64::from(list.magnification))).round() as i64; for (index, item) in list.items.iter().enumerate() { - if opentype_text.is_some() && !matches!(item, DisplayItem::OpenTypeGlyph { .. }) { - opentype_fonts::TextRun::finish(&mut opentype_text, &mut content); + if !matches!(item, DisplayItem::OpenTypeGlyph { .. }) { + opentype_text.finish(&mut content); + } + if matches!( + item, + DisplayItem::NativeGlyph { .. } | DisplayItem::MathGlyph { .. } | DisplayItem::Text { .. } + ) { + opentype_text.reset_matrix(); } if let DisplayItem::PdfTextSpace { x, y, operation } = item { if let Some(dedicated) = list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()) @@ -858,7 +866,8 @@ fn page_content( DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => { opentype[&font.id].paint( &mut opentype_text, &mut content, font, *glyph, text, - *size, *x - h, height - *y - v, list.units.bp(1), + *size, *x - h, height - *y - v, bp_per_unit, + [one_inch - h, height - one_inch - v], ); } DisplayItem::NativeGlyph { @@ -1168,7 +1177,7 @@ fn page_content( } } } - opentype_fonts::TextRun::finish(&mut opentype_text, &mut content); + opentype_text.finish(&mut content); NativeTextRun::flush(&mut native_text, &mut content); native_text::NativeText::finish(&mut tex_text, &mut content); content.push_str("Q\n"); diff --git a/crates/texrra-tex-core/src/pdf_opentype.rs b/crates/texrra-tex-core/src/pdf_opentype.rs index 37d01a4..4467cbf 100644 --- a/crates/texrra-tex-core/src/pdf_opentype.rs +++ b/crates/texrra-tex-core/src/pdf_opentype.rs @@ -22,21 +22,40 @@ struct EmbeddedGlyph { cluster_text: Option, } -pub(super) struct TextRun { +pub(super) struct TextState { + run: Option, + matrix: [f64; 2], +} + +impl Default for TextState { + fn default() -> Self { + Self { run: None, matrix: [1., 0.] } + } +} + +impl TextState { + pub(super) fn finish(&mut self, output: &mut PageContent) { + if let Some(run) = self.run.take() { + let close = if run.emboldened { ">] TJ 0 Tr ET\n" } else { ">] TJ ET\n" }; + output.push_str(close); + } + } + + pub(super) fn reset_matrix(&mut self) { + self.matrix = [1., 0.]; + } +} + +struct TextRun { font: FontId, size: i64, start: [i64; 2], offset: i64, + emboldened: bool, } impl TextRun { - pub(super) fn finish(run: &mut Option, output: &mut PageContent) { - if run.take().is_some() { - output.push_str(">] TJ ET\n"); - } - } - - fn move_line( + fn place_line( &mut self, output: &mut PageContent, [x, y]: [i64; 2], @@ -47,7 +66,7 @@ impl TextRun { let dx = (((x - self.start[0]) as f64 - dy as f64 * slant) / extend) as i64; let (tx, x_error) = rounded_coordinate(dx, bp_per_unit); let (ty, y_error) = rounded_coordinate(dy, bp_per_unit); - output.push_str(&format!(">] TJ {tx:.3} {ty:.3} Td [<")); + output.push_str(&format!("{tx:.3} {ty:.3} Td [<")); self.start = [x - x_error, y - y_error]; self.offset = 0; } @@ -298,7 +317,7 @@ pub(super) fn begin_actual_text(output: &mut PageContent, text: &str, xdv: bool) impl EmbeddedFont { pub(super) fn paint( &self, - run: &mut Option, + state: &mut TextState, output: &mut PageContent, font: &OpenTypeFont, glyph: u16, @@ -307,72 +326,95 @@ impl EmbeddedFont { x: i64, y: i64, bp_per_unit: f64, + page_origin: [i64; 2], ) { let glyph = &self.glyphs[&glyph]; let [horizontal_scale, slant] = font.paint_transform(); let device = font.device_transform(); - let relative = device[1] != 0. && device[0] != 0.; + let embolden = font.paint_embolden(); + let emboldened = embolden > 0.; + let relative = (device[1] != 0. || emboldened) && device[0] != 0.; let horizontal_em = size as f64 * if relative { device[0] } else { horizontal_scale }; let override_text = glyph .cluster_text .as_deref() .is_some_and(|mapped| text != mapped); - if let Some(state) = run.as_mut() { - let delh = (x - state.start[0] - state.offset).abs(); - let delv = (y - state.start[1]).abs(); - if override_text || state.font != font.id || state.size != size { - TextRun::finish(run, output); + let mut repositioned = false; + if let Some(run) = state.run.as_mut() { + let delh = (x - run.start[0] - run.offset).abs(); + let delv = (y - run.start[1]).abs(); + if override_text || run.font != font.id || run.size != size { + state.finish(output); } else if relative { if delv > (0.001 / bp_per_unit).round() as i64 || delh > (3. * horizontal_em) as i64 { // Td moves in text space. Precompensate for the shear and // retain the rounded displacement error in device units. - state.move_line(output, [x, y], device, bp_per_unit); + output.push_str(">] TJ "); + run.place_line(output, [x, y], device, bp_per_unit); + repositioned = true; } } else if (horizontal_em == 0. && delh != 0) || delv as f64 * bp_per_unit > 0.001 || delh > size * 3 { - TextRun::finish(run, output); + state.finish(output); } } if override_text { begin_actual_text(output, text, false); } - let state = run.get_or_insert_with(|| { - let coordinates = [x, y].map(|value| rounded_coordinate(value, bp_per_unit)); - let start = if relative { - [x, y] - } else { - [x - coordinates[0].1, y - coordinates[1].1] - }; + let first = state.run.is_none(); + let start_relative = first && emboldened && relative && state.matrix == device; + state.matrix = device; + let run = state.run.get_or_insert_with(|| { let size_bp = size as f64 * bp_per_unit; - output.push_str(&format!( - "BT /U{} {size_bp:.4} Tf {horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<", - font.id.index(), - coordinates[0].0, - coordinates[1].0 - )); - TextRun { + output.push_str(&format!("BT /U{} {size_bp:.4} Tf ", font.id.index())); + if emboldened { + output.push_str(&format!("2 Tr {embolden:.6} w ")); + } + let mut run = TextRun { font: font.id, size, - start, - offset: x - start[0], + start: [x, y], + offset: 0, + emboldened, + }; + if start_relative { + // At a new text object the XDV device reuses the font + // matrix at the page origin, then positions the first line. + let [tx, ty] = page_origin.map(|coordinate| coordinate as f64 * bp_per_unit); + output.push_str(&format!( + "{horizontal_scale} 0 {slant} 1 {tx:.3} {ty:.3} Tm ", + )); + run.start = page_origin; + run.place_line(output, [x, y], device, bp_per_unit); + } else { + let coordinates = [x, y].map(|coordinate| rounded_coordinate(coordinate, bp_per_unit)); + output.push_str(&format!( + "{horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<", + coordinates[0].0, coordinates[1].0, + )); + if !relative { + run.start = [x - coordinates[0].1, y - coordinates[1].1]; + run.offset = coordinates[0].1; + } } + run }); // Move in PDF's thousandth-em text units, tracking widths in TeX sp. - let kernel = if horizontal_em == 0. { + let kernel = if horizontal_em == 0. || (relative && (first || repositioned)) { 0 } else { - ((state.start[0] + state.offset - x) as f64 * 1000. / horizontal_em) as i64 + ((run.start[0] + run.offset - x) as f64 * 1000. / horizontal_em) as i64 }; if kernel != 0 { output.push_str(&format!("> {kernel} <")); - state.offset -= (kernel as f64 * (horizontal_em / 1000.)) as i64; + run.offset -= (kernel as f64 * (horizontal_em / 1000.)) as i64; } output.push_str(&format!("{:04X}", glyph.cid)); - state.offset += (f64::from(glyph.advance) * horizontal_em / f64::from(self.units)) as i64; + run.offset += (f64::from(glyph.advance) * horizontal_em / f64::from(self.units)) as i64; if override_text { - TextRun::finish(run, output); + state.finish(output); output.push_str("EMC\n"); } } diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index f955207..195095d 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -560,30 +560,46 @@ impl DisplayList { std::collections::btree_map::Entry::Vacant(entry) => entry.insert(font.face()?), std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), }; - let path = opentype_paths.entry((font.id, *glyph)) - .or_insert_with(|| crate::opentype::outline(face, *glyph)); let x = *x as f64 / 65536.; let y = *y as f64 / 65536.; let scale = *size as f64 / (65536. * f64::from(face.units_per_em())); + let [extend, slant] = font.paint_transform(); + let embolden = font.paint_embolden(); + let horizontal = scale * extend; + // Place the transformed outline in page units before + // stroking. The font matrix must not distort the stroke. + let transform = (embolden > 0.).then_some([horizontal, scale * slant, -scale]); + let path_size = if transform.is_some() { *size } else { 0 }; + let path = opentype_paths.entry((font.id, *glyph, path_size)) + .or_insert_with(|| crate::opentype::outline(face, *glyph, transform)); if !path.is_empty() { use std::fmt::Write as _; - let [extend, slant] = font.paint_transform(); - let horizontal = scale * extend; write!( out, - "", + write!( + out, "\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}", fill[0], fill[1], fill[2], ).unwrap(); + if embolden > 0. { + let stroke_width = embolden / self.units.bp(65536); + write!( + out, + " stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{stroke_width:.9}\" stroke-miterlimit=\"10\"{stroke_opacity}", + stroke[0], stroke[1], stroke[2], + ).unwrap(); + } + out.push_str("/>\n"); } } DisplayItem::MathGlyph { diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index b3eb992..91965fc 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -414,9 +414,11 @@ impl SourceMap { let bottom_offset = -slant * descent as f64; let left = top_offset.min(bottom_offset).floor() as i64; let right = top_offset.max(bottom_offset).ceil() as i64; + let stroke = (font.paint_embolden() / (2. * page.units.bp(1))).ceil() as i64; Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, Bounds { - x: x + advance.min(&0) + left, y: y - ascent, - width: advance.abs() + right - left, height: ascent + descent, + x: x + advance.min(&0) + left - stroke, y: y - ascent - stroke, + width: advance.abs() + right - left + 2 * stroke, + height: ascent + descent + 2 * stroke, })) } DisplayItem::Rule { diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4ea62d2..244680e 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,34 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX OpenType 合成粗体与原生描边 + +`embolden` 按实际字号计算 XDV 描边宽度,字宽、盒宽和斜体修正 +遵循实际字体度量。原生 PDF 使用填充加描边的文字模式,在文字 +对象结束时恢复普通模式。相同字体矩阵下重新开启粗体文字时, +从 XDV 页原点计算首段位移。SVG 将变换后的真实轮廓放到页面 +坐标再描边,使用当前描边色和设备线宽。来源映射包含描边半径。 +[XeTeX 字号与合成粗体](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeX_ext.c#L1067-L1078) +[xdvipdfmx 的描边文字模式](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdev.c#L833-L849) +[xdvipdfmx 的文字对象与重置](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdev.c#L528-L591) + +原语、彩色放大页及真实 `fontspec` 的 `FakeBold` 共 6 页、56 个 +字形,编号、字号及原始位置均与参考一致。字体及盒查询、PDF +描边宽度、模式恢复和版面文本一致,144 DPI 灰度和彩色光栅 +逐样本相同。两页首版的 56 与 1 个差异像素已留档,最终复验 +其 21 个 PDF 相对位移与参考完全一致。真实 `fontspec-xetex.sty` +的实际读取指纹在两端相同。 + +三次跨文件编辑加粗参数,各复用 66 步、重放两次调用,只更新 +第二页。PDF、SVG 和来源映射与独立全量一致。实际增量 SVG 的 +彩色描边宽度、变换轮廓和来源命中已核对。12 项定向回归通过, +原样 ACL 的 PDF、aux、out、bbl 与上一版逐字节一致。 +回执 `target/p3-xetex-font-embolden/receipt.json` 的 SHA-256 为 +`8579d7fdd374be0c2f0ad7e10891a653bdf7444e4d330c6533a9bd15f767bdb9`。 + +下一入口为 OpenType `color` 和透明度。`target/p3-xetex-font-color` +保存原语和真实 `fontspec` 三页参考、透明度设备记录和当前原生诊断。 + ### XeTeX OpenType 倾斜与 PDF 基线位移 `slant` 接入 XeTeX 字体选择、实际字形位置和字体斜率。造型阶段 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 690078e..774fb43 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -758,6 +758,16 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX `target/p3-xdv-annotation/receipt.json`。 [链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形) +#### XeTeX OpenType 合成粗体复编 + +原样 ACL 使用同一 schema71、真实字体和已收敛的辅助文件复编, +PDF、aux、out、bbl 与上一版逐字节一致。另以未修改的 `fontspec` +执行 `FakeBold`,核对真实描边、字形坐标和光栅。ACL 整页版面差异 +继续留在原门槛。 +回执 `target/p3-xetex-font-embolden/receipt.json` 的 SHA-256 为 +`8579d7fdd374be0c2f0ad7e10891a653bdf7444e4d330c6533a9bd15f767bdb9`。 +[合成粗体阶段记录](P2_M1_PROGRESS.md#xetex-opentype-合成粗体与原生描边) + #### XeTeX OpenType 倾斜复编 原样 ACL 在同一 schema71、字体与收敛的生成状态下复编,PDF、