diff --git a/crates/texrra-tex-core/src/pdf_opentype.rs b/crates/texrra-tex-core/src/pdf_opentype.rs index 866e86c..12a4cb7 100644 --- a/crates/texrra-tex-core/src/pdf_opentype.rs +++ b/crates/texrra-tex-core/src/pdf_opentype.rs @@ -60,6 +60,26 @@ struct TextRun { } impl TextRun { + fn select_font( + &mut self, + output: &mut PageContent, + font: FontId, + size: i64, + bp_per_unit: f64, + embolden: f64, + ) { + let size_bp = size as f64 * bp_per_unit; + output.push_str(&format!("/U{} {size_bp:.4} Tf ", font.index())); + if embolden > 0. { + output.push_str(&format!("2 Tr {embolden:.6} w ")); + } else if self.emboldened { + output.push_str("0 Tr "); + } + self.font = font; + self.size = size; + self.emboldened = embolden > 0.; + } + fn place_line( &mut self, output: &mut PageContent, @@ -86,6 +106,23 @@ fn rounded_coordinate(value: i64, bp_per_unit: f64) -> (f64, i64) { (rounded, ((exact - rounded) / bp_per_unit).round() as i64) } +fn place_absolute( + output: &mut PageContent, + [a, b, c, d]: [f64; 4], + position: [i64; 2], + origin: [i64; 2], + bp_per_unit: f64, +) -> [i64; 2] { + let [tx, ty] = std::array::from_fn(|axis| { + let (delta, error) = rounded_coordinate(position[axis] - origin[axis], bp_per_unit); + (rounded_coordinate(origin[axis], bp_per_unit).0 + delta, error) + }); + output.push_str(&format!( + "{a} {b} {c} {d} {:.3} {:.3} Tm [<", tx.0, ty.0, + )); + [tx.1, ty.1] +} + #[derive(Default)] pub(super) struct UsedFonts<'a>(BTreeMap)>); @@ -575,8 +612,25 @@ impl EmbeddedFont { 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 { + if override_text { state.finish(output); + } else if run.font != font.id || run.size != size { + if xdv { + // Selecting a font ends the string but retains the text + // line matrix. Recompute Tm only when its shape changes. + output.push_str(">] TJ "); + run.select_font(output, font.id, size, bp_per_unit, embolden); + if relative && state.matrix == (device, vertical) { + run.place_line(output, [x, y], device, vertical, bp_per_unit); + } else { + place_absolute(output, [a, b, c, d], [x, y], page_origin, bp_per_unit); + run.start = [x, y]; + run.offset = 0; + } + repositioned = true; + } else { + 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 @@ -599,18 +653,15 @@ impl EmbeddedFont { let start_relative = first && (xdv || emboldened || font_colors) && relative && state.matrix == (device, vertical); state.matrix = (device, vertical); 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 ", font.id.index())); - if emboldened { - output.push_str(&format!("2 Tr {embolden:.6} w ")); - } + output.push_str("BT "); let mut run = TextRun { font: font.id, size, start: [x, y], offset: 0, - emboldened, + emboldened: false, }; + run.select_font(output, font.id, size, bp_per_unit, embolden); if start_relative { // At a new text object the XDV device reuses the font // matrix at the page origin, then positions the first line. @@ -622,25 +673,19 @@ impl EmbeddedFont { run.place_line(output, [x, y], device, vertical, bp_per_unit); } else { let origin = if xdv { page_origin } else { [0, 0] }; - let [tx, ty] = std::array::from_fn(|axis| { - let value = [x, y][axis]; - let (delta, error) = rounded_coordinate(value - origin[axis], bp_per_unit); - (rounded_coordinate(origin[axis], bp_per_unit).0 + delta, error) - }); - output.push_str(&format!( - "{a} {b} {c} {d} {:.3} {:.3} Tm [<", tx.0, ty.0, - )); + let [dx, dy] = + place_absolute(output, [a, b, c, d], [x, y], origin, bp_per_unit); if xdv || !relative { - run.start = [x - tx.1, y - ty.1]; + run.start = [x - dx, y - dy]; } if !xdv && !relative { - run.offset = tx.1; + run.offset = dx; } } run }); // Move in PDF's thousandth-em text units, tracking widths in TeX sp. - let kernel = if horizontal_em == 0. || (relative && (first || repositioned)) { + let kernel = if horizontal_em == 0. || repositioned || (relative && first) { 0 } else { ((run.start[0] + run.offset - x) as f64 * 1000. / horizontal_em) as i64 diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4a5538c..ead402f 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,45 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### XeTeX OpenType 字体切换的文本行定位 + +切换 OpenType 字体时,XDV 结束当前字形字符串,保留同一 PDF +文本对象及文字行原点。矩阵兼容时按当前行原点写相对 Td。 +字宽缩放、倾斜或方向变化时写实际 Tm。合成粗体随字体选择 +应用和恢复文字描边。出页规则、图形、special 和实际文本 +标记继续结束文字对象。 +[参考驱动的文本状态与选字体](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/pdfdev.c#L804-L909) + +Latin Modern 和 Fandol 四字形对照从三个 BT 改为一个 BT +及三次 Td,消除全部 87 个灰度像素差。字宽缩放、倾斜、 +合成粗体及横纵混排的两个对照各保留一个 BT。三页的词框与 +144 DPI 灰度图均与参考相同。五项 XeTeX 管线回归通过。 + +原样 xeCJK 边界间距样稿的 515 个原生布局字形保持一致。 +一页 PDF 的 380 个词框和 144 DPI 灰度图、40 条出页警告 +及 aux 与参考逐项一致。原生的文本对象从 267 个降为 155 +个,参考为 131 个,两端均有 267 次选字体和 277 次相对 +定位。最新逐像素结果的摘要为 +a580ad47e553d267ed64e4177063c7597e9b51ad90c191a3bdbb37950d5663ec。 +三个直接对照与原样编译的回执在 target/p3-xetex-text-switch, +receipt.json 为 aab8f07abc6e43ce255e30db3c9f71c653ae298a96d4b6539c78907af60720a9。 +保留之前的 PDF、光栅及失败记录。 + +四页混合字体会话替换实际字体、移动子文件内容,再从缺字体 +恢复并改变倾斜。三次成功修订只更新第 2 页,后两次分别复用 +66 步。PDF、测量页面、SVG、来源映射和 aux 与独立全量一致。 +缺字体时保留已发布预览和 aux。revision.log 为 +e55443174ab5b28e8f3c03a517b79ba02ae42c59daf4358c4868abba22bfc7d9。 + +另一份原样 xeCJK-example-autofake.tex 通过真实 article、 +xeCJK 和 fontspec 排版。参考与原生从同一份实际 SimSun TTC、 +SimHei 和 KaiTi 读取中文排版字形。两端各生成一页,94 个词框、 +144 DPI 灰度图及 aux 相同。参考有 20 份 Type0 字典,原生有 +18 份,差别来自 SimSun 资源的组织。原样源、字体摘要和输出 +在 next-autofake,compare.log 为 +b3b22c3c8bc2b49f87b0ca1b093055ef34b44e34056c0fa8faf9456e94a9b25b。 +[xeCJK 官方发布](https://ctan.org/pkg/xecjk) + ### XeTeX Type 1 字幅和传统字体的文字定位 原生 Type 1 字形解释器在生成实际轮廓时一并取出 hsbw 或 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 20e56b2..473d2f5 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -774,6 +774,54 @@ fn xetex_type1_widths_follow_the_encoded_glyph_program() { fs::remove_dir_all(root).unwrap(); } +#[test] +fn xetex_opentype_font_switch_uses_the_current_text_line_origin() { + use lopdf::{Document, content::Content}; + use texrra_tex_core::execution::InputProfile; + + let root = directory("xetex-opentype-font-switch"); + let mut job = request(&root); + job.world = WorldConfig::new(&root); + job.input_profile = InputProfile::XeTeX; + fs::write( + root.join("serif.ttf"), + include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf"), + ) + .unwrap(); + fs::write( + root.join("sans.ttf"), + include_bytes!("../assets/fonts-subset/LiberationSans-Regular.ttf"), + ) + .unwrap(); + fs::write( + root.join("main.tex"), + br#"\catcode123=1 \catcode125=2 +\font\serif="[serif.ttf]" at 9pt +\font\sans="[sans.ttf]" at 12pt +\shipout\hbox{\serif AA\kern14pt\sans B\kern9pt\serif C} +\end"#, + ) + .unwrap(); + + let result = NativeCompiler::default().compile(job).unwrap(); + let pdf = Document::load_mem(result.pdf.as_deref().unwrap()).unwrap(); + let page = pdf.get_page_content(pdf.get_pages()[&1]).unwrap(); + let content = Content::decode(&page).unwrap(); + let operators = content + .operations + .iter() + .filter_map(|operation| match operation.operator.as_str() { + name @ ("BT" | "ET" | "Tf" | "Tm" | "Td" | "TJ") => Some(name), + _ => None, + }) + .collect::>(); + assert_eq!( + operators, + ["BT", "Tf", "Tm", "Td", "TJ", "Tf", "Td", "TJ", "Tf", "Td", "TJ", "ET"] + ); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn xetex_unclaimed_special_warns_at_shipout_and_retains_the_whatsit() { use texrra_tex_core::execution::{Event, InputProfile};