Use Base-14 fonts when possible and center natural-width tables

This commit is contained in:
gloamxun committed 2026-10-19 17:40:04 +08:00
1 parent 1da9e0dde9
commit ca5cb0b8af
8 files changed
+295 -35

No files matched your search

+9 -6
View File
@@ -127,8 +127,10 @@ page
breaks, basic display and inline math, figures, simple tables, breaks, basic display and inline math, figures, simple tables,
section/figure/table references, numeric citations from a manual bibliography or a section/figure/table references, numeric citations from a manual bibliography or a
local `.bib` file, and natbib-style author-year citations for the arXiv template. A4 pages use 25 mm margins unless local `.bib` file, and natbib-style author-year citations for the arXiv template. A4 pages use 25 mm margins unless
`geometry` sets them. Liberation Serif is embedded in the PDF for Latin and math `geometry` sets them. The PDF uses the Base-14 Times/Courier faces without
glyphs; CJK text uses an installed fallback font. embedding when all text fits the standard WinAnsi encoding, and falls back to
embedded Liberation Serif/Sans/Mono for other characters; CJK text uses an
installed fallback font.
### LaTeX compatibility layer ### LaTeX compatibility layer
@@ -364,10 +366,11 @@ parameter with a default value. Unknown packages fail with a clear error.
`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file. `\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file.
It supports `width`, `height`, and `scale`; width and height accept physical It supports `width`, `height`, and `scale`; width and height accept physical
units or fractions of `\linewidth`. Images with transparency are not supported units or fractions of `\linewidth`. Images with transparency are not supported
by the current PDF dependency. Basic `tabular` rows become equal-width PDF by the current PDF dependency. Basic `tabular` rows use natural column widths
columns; `l`, `c`, `r`, and paragraph (`p{...}`) columns are supported, as are (content width plus 6pt `\tabcolsep`), are centered in the text block, and draw
full-width `\hline` and `booktabs` rules. Spanning cells, partial `\cline` rules, `\hline`/`booktabs` rules exactly over the table columns; `l`, `c`, `r`, and
and multi-page table headers are not implemented. Figures honor `[htbp]` paragraph (`p{...}`) columns are supported. Spanning cells, partial `\cline`
rules, and multi-page table headers are not implemented. Figures honor `[htbp]`
placement hints (`[t]` is deferred to the top of the next page, `[b]` to the placement hints (`[t]` is deferred to the top of the next page, `[b]` to the
page bottom, `[p]` to a float page, `[h]` stays in the flow); tables honor page bottom, `[p]` to a float page, `[h]` stays in the flow); tables honor
`[t]` by deferring the caption and rows to the next page, `[b]` at the page `[t]` by deferring the caption and rows to the next page, `[b]` at the page
+2 -1
View File
@@ -17,7 +17,8 @@ abstract quotation formatting, unnumbered `\paragraph` headings, natbib-style
author-year citations and plainnat bibliography formatting; author-year citations and plainnat bibliography formatting;
`\vbox`/`\vtop` vertical-material capture with inline splicing `\vbox`/`\vtop` vertical-material capture with inline splicing
(`build_positioned_pages` is the only page builder and no separate break (`build_positioned_pages` is the only page builder and no separate break
planner remains). planner remains); conditional Base-14 font embedding and natural-width centered
table layout.
## 1. Float tuning and table queue ## 1. Float tuning and table queue
+4 -1
View File
@@ -101,7 +101,10 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to
one A4 page each; the arXiv template project compiles to 3 Letter pages. one A4 page each; the arXiv template project compiles to 3 Letter pages.
- `cargo fmt --check` passes; `cargo test --offline` (45 tests: 41 compiler - ASCII-only documents use non-embedded Base-14 Times/Courier (arXiv PDF is
about 0.7 MB); documents with accented/non-WinAnsi text embed Liberation
faces. Tables use natural column widths and centered rules.
- `cargo fmt --check` passes; `cargo test --offline` (47 tests: 43 compiler
integration tests + 4 server tests) covers the three examples, the arXiv integration tests + 4 server tests) covers the three examples, the arXiv
fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output, fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output,
project API, static frontend assets, path traversal, the legacy project API, static frontend assets, path traversal, the legacy
+114 -8
View File
@@ -105,9 +105,10 @@ struct PositionedTableRow {
struct PositionedTable { struct PositionedTable {
rows: Vec<PositionedTableRow>, rows: Vec<PositionedTableRow>,
column_count: usize, column_widths: Vec<i64>,
rules: HashSet<usize>, rules: HashSet<usize>,
height: i64, height: i64,
table_width: i64,
} }
struct PositionedFigure { struct PositionedFigure {
@@ -197,13 +198,23 @@ impl PositionedTable {
}); });
} }
let weights = vec![1; self.column_count]; let table_width_mm = scaled_units_to_mm(self.table_width);
let offset = ((f64::from(area.size().width) - table_width_mm) / 2.0).max(0.0);
let mut table_area = area.clone();
table_area.add_offset(Position::new(offset, 0.0));
table_area.set_width(Mm::from(table_width_mm));
let total: i64 = self.column_widths.iter().sum();
let weights: Vec<usize> = self
.column_widths
.iter()
.map(|width| (((*width).max(1) * 255) / total.max(1)).clamp(1, 255) as usize)
.collect();
let mut y = 0_i64; let mut y = 0_i64;
for (row_index, row) in self.rows.iter_mut().enumerate() { for (row_index, row) in self.rows.iter_mut().enumerate() {
let mut row_area = area.clone(); let mut row_area = table_area.clone();
row_area.add_offset(Position::new(0.0, scaled_units_to_mm(y))); row_area.add_offset(Position::new(0.0, scaled_units_to_mm(y)));
if self.rules.contains(&row_index) { if self.rules.contains(&row_index) {
let width = area.size().width; let width = table_area.size().width;
row_area.draw_line( row_area.draw_line(
vec![Position::default(), Position::new(width, 0.0)], vec![Position::default(), Position::new(width, 0.0)],
Style::new(), Style::new(),
@@ -250,9 +261,9 @@ impl PositionedTable {
y = y.saturating_add(row.height); y = y.saturating_add(row.height);
} }
if self.rules.contains(&self.rows.len()) { if self.rules.contains(&self.rows.len()) {
let mut rule_area = area.clone(); let mut rule_area = table_area.clone();
rule_area.add_offset(Position::new(0.0, scaled_units_to_mm(y))); rule_area.add_offset(Position::new(0.0, scaled_units_to_mm(y)));
let width = area.size().width; let width = table_area.size().width;
rule_area.draw_line( rule_area.draw_line(
vec![Position::default(), Position::new(width, 0.0)], vec![Position::default(), Position::new(width, 0.0)],
Style::new(), Style::new(),
@@ -1785,8 +1796,14 @@ struct FontInputs {
impl FontInputs { impl FontInputs {
fn load(model: &DocumentModel) -> Result<Self, String> { fn load(model: &DocumentModel) -> Result<Self, String> {
let latin_dir = latin_font_directory()?; let latin_dir = latin_font_directory()?;
// The embedded face is needed for math glyphs outside built-in Times's WinAnsi encoding. // Use the Base-14 faces when every text character is representable;
let latin_fonts = fonts::from_files(&latin_dir, "LiberationSerif", None) // otherwise embed the metric-compatible Liberation faces.
let builtin = if document_needs_embedded_latin(model) {
None
} else {
Some(fonts::Builtin::Times)
};
let latin_fonts = fonts::from_files(&latin_dir, "LiberationSerif", builtin)
.map_err(|error| format!("could not load Latin fonts: {error}"))?; .map_err(|error| format!("could not load Latin fonts: {error}"))?;
let cjk_path = document_contains_cjk(model) let cjk_path = document_contains_cjk(model)
.then(cjk_font_path) .then(cjk_font_path)
@@ -2744,6 +2761,95 @@ fn list_contains_monospace(
}) })
} }
fn list_contains_non_builtin(list: &ListBlock) -> bool {
list.items.iter().any(|item| {
item.runs
.iter()
.any(|run| run.text.chars().any(|ch| !builtin_safe_char(ch)))
|| item.nested.iter().any(list_contains_non_builtin)
})
}
fn builtin_safe_char(ch: char) -> bool {
ch.is_ascii()
|| matches!(
ch,
'µ' | '¹'
| '²'
| '³'
| '–'
| '—'
| '‘'
| '’'
| '“'
| '”'
| '…'
| '•'
| '\u{F7001}'
| '\u{F5000}'
| '·'
| 'μ'
| '∼'
| '⁰'
| '¹'
| '⁴'
| '⁵'
| '⁶'
| '⁷'
| '⁸'
| '⁹'
)
}
fn document_needs_embedded_latin(model: &DocumentModel) -> bool {
let text_needs_embedding = |text: &str| text.chars().any(|ch| !builtin_safe_char(ch));
let runs_need_embedding = |runs: &[Run]| {
runs.iter()
.filter(|run| run.math.is_none())
.any(|run| text_needs_embedding(&run.text))
};
if text_needs_embedding(&model.title)
|| text_needs_embedding(&model.author)
|| text_needs_embedding(&model.date)
|| runs_need_embedding(&model.title_runs)
{
return true;
}
if model
.footnotes
.iter()
.any(|note| runs_need_embedding(&note.runs))
{
return true;
}
model.blocks.iter().any(|block| match block {
Block::Paragraph(runs) | Block::Heading { runs, .. } => runs_need_embedding(runs),
Block::List(list) => list_contains_non_builtin(list),
Block::Table { rows, caption, .. } => {
rows.iter()
.flatten()
.flatten()
.any(|run| text_needs_embedding(&run.text))
|| caption
.as_ref()
.is_some_and(|runs| runs_need_embedding(runs))
}
Block::Image { caption, .. } => caption
.as_ref()
.is_some_and(|runs| runs_need_embedding(runs)),
Block::FramedBox { runs, .. } | Block::Centered { runs } => runs_need_embedding(runs),
Block::HorizontalRule { .. } => false,
Block::Bibliography(items) => items
.iter()
.flat_map(|(_, runs)| runs)
.any(|run| text_needs_embedding(&run.text)),
Block::Math { .. } => false,
Block::VerticalKern(_) | Block::VerticalGlue(_) | Block::Penalty(_) | Block::PageBreak => {
false
}
})
}
fn document_contains_cjk(model: &DocumentModel) -> bool { fn document_contains_cjk(model: &DocumentModel) -> bool {
let text_has_cjk = |text: &str| text.chars().any(is_cjk); let text_has_cjk = |text: &str| text.chars().any(is_cjk);
if text_has_cjk(&model.title) || text_has_cjk(&model.author) || text_has_cjk(&model.date) { if text_has_cjk(&model.title) || text_has_cjk(&model.author) || text_has_cjk(&model.date) {
+87 -12
View File
@@ -549,12 +549,7 @@ fn layout_table(
if column_count == 0 { if column_count == 0 {
return None; return None;
} }
let cell_width_mm = content_width_mm / column_count as f64; let cell_font_size = font_size.max(1);
if cell_width_mm <= 0.0 {
return None;
}
let cell_font_size = font_size.saturating_sub(1).max(1);
let empty_row_height = font_line_height_scaled( let empty_row_height = font_line_height_scaled(
font_cache, font_cache,
cjk_family, cjk_family,
@@ -562,6 +557,80 @@ fn layout_table(
sans_family, sans_family,
cell_font_size, cell_font_size,
); );
let natural_line_width = |content: &PositionedLineContent| -> f64 {
match content {
PositionedLineContent::Text { line, font_size } => {
text_layout::TextLine::new(line, cjk_family, mono_family, sans_family, *font_size)
.natural_width_mm(font_cache)
}
PositionedLineContent::InlineMath(_) => 0.0,
}
};
// First pass: measure each cell without imposed column widths and record the
// widest line. This gives the table its natural width instead of stretching
// every column across the whole text block.
let mut natural_widths = vec![0.0_f64; column_count];
for row in rows {
for column in 0..column_count {
let runs = row.get(column).map(Vec::as_slice).unwrap_or_default();
if runs.is_empty() {
continue;
}
let lines = measure_positioned_lines(
runs,
cell_font_size,
content_width_mm,
metrics,
font_cache,
cjk_family,
mono_family,
sans_family,
math_metrics,
math_layout,
cache,
);
let estimated = runs
.iter()
.map(|run| run.text.chars().count())
.sum::<usize>() as f64
* f64::from(cell_font_size)
* 0.6
* 25.4
/ 72.27;
for line in &lines {
let width = match &line.content {
PositionedLineContent::InlineMath(_) => estimated,
_ => natural_line_width(&line.content),
};
natural_widths[column] = natural_widths[column].max(width);
}
}
}
// TeX default tabcolsep is 6pt on each side of a column.
let padding_mm = 2.0 * 6.0 * 25.4 / 72.27;
let mut column_widths_mm: Vec<f64> = natural_widths
.iter()
.map(|width| (*width + padding_mm).max(padding_mm))
.collect();
let natural_table_width: f64 = column_widths_mm.iter().sum();
let scale = if natural_table_width > content_width_mm {
content_width_mm / natural_table_width
} else {
1.0
};
for width in &mut column_widths_mm {
*width *= scale;
}
let table_width = millimeters_to_scaled(column_widths_mm.iter().sum());
let column_widths: Vec<i64> = column_widths_mm
.iter()
.map(|width| millimeters_to_scaled(*width).max(1))
.collect();
// Second pass: wrap into the final column width.
let mut positioned_rows = Vec::with_capacity(rows.len()); let mut positioned_rows = Vec::with_capacity(rows.len());
let mut total_height = 0_i64; let mut total_height = 0_i64;
for row in rows { for row in rows {
@@ -569,10 +638,11 @@ fn layout_table(
let mut row_height = empty_row_height; let mut row_height = empty_row_height;
for column in 0..column_count { for column in 0..column_count {
let runs = row.get(column).map(Vec::as_slice).unwrap_or_default(); let runs = row.get(column).map(Vec::as_slice).unwrap_or_default();
let available_mm = (column_widths_mm[column] - padding_mm).max(1.0);
let lines = measure_positioned_lines( let lines = measure_positioned_lines(
runs, runs,
cell_font_size, cell_font_size,
cell_width_mm, available_mm,
metrics, metrics,
font_cache, font_cache,
cjk_family, cjk_family,
@@ -613,9 +683,10 @@ fn layout_table(
Some(PositionedTable { Some(PositionedTable {
rows: positioned_rows, rows: positioned_rows,
column_count, column_widths,
rules: rules.iter().copied().collect(), rules: rules.iter().copied().collect(),
height: total_height, height: total_height,
table_width,
}) })
} }
@@ -2328,8 +2399,9 @@ pub(super) fn build_positioned_pages(
} }
let PositionedTable { let PositionedTable {
rows: table_rows, rows: table_rows,
column_count, column_widths,
rules: table_rules, rules: table_rules,
table_width,
.. ..
} = table; } = table;
for (row_index, row) in table_rows.into_iter().enumerate() { for (row_index, row) in table_rows.into_iter().enumerate() {
@@ -2352,9 +2424,10 @@ pub(super) fn build_positioned_pages(
}, },
element: PositionedTable { element: PositionedTable {
rows: vec![row], rows: vec![row],
column_count, column_widths: column_widths.clone(),
rules: row_rules, rules: row_rules,
height: row_height, height: row_height,
table_width,
}, },
y, y,
}); });
@@ -2452,8 +2525,9 @@ pub(super) fn build_positioned_pages(
if let Some(table) = table { if let Some(table) = table {
let PositionedTable { let PositionedTable {
rows: table_rows, rows: table_rows,
column_count, column_widths,
rules: table_rules, rules: table_rules,
table_width,
.. ..
} = table; } = table;
for (row_index, row) in table_rows.into_iter().enumerate() { for (row_index, row) in table_rows.into_iter().enumerate() {
@@ -2499,9 +2573,10 @@ pub(super) fn build_positioned_pages(
} }
let element = PositionedTable { let element = PositionedTable {
rows: vec![row], rows: vec![row],
column_count, column_widths: column_widths.clone(),
rules: row_rules, rules: row_rules,
height: row_height, height: row_height,
table_width,
}; };
pages pages
.last_mut() .last_mut()
+15 -6
View File
@@ -163,22 +163,30 @@ fn write_table(
monospace_family: Option<FontFamily<fonts::Font>>, monospace_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>, sans_family: Option<FontFamily<fonts::Font>>,
) { ) {
let width_mm = f64::from(content_width); let text_width_mm = f64::from(content_width);
let column_width = Mm::from(width_mm / table.column_count.max(1) as f64); let table_width_mm = scaled_units_to_mm(table.table_width);
let table_x = ((text_width_mm - table_width_mm) / 2.0).max(0.0);
let mut cursor = 0.0_f64; let mut cursor = 0.0_f64;
for (row_index, row) in table.rows.iter_mut().enumerate() { for (row_index, row) in table.rows.iter_mut().enumerate() {
if table.rules.contains(&row_index) { if table.rules.contains(&row_index) {
write_rule(output, 0.0, cursor, width_mm); write_rule(output, table_x, cursor, table_width_mm);
} }
let mut x = table_x;
for (column_index, cell) in row.cells.iter_mut().enumerate() { for (column_index, cell) in row.cells.iter_mut().enumerate() {
let x = Mm::from(column_index as f64 * f64::from(column_width)); let column_width = Mm::from(
table
.column_widths
.get(column_index)
.map(|width| scaled_units_to_mm(*width))
.unwrap_or(0.0),
);
let mut cell_y = 0.0; let mut cell_y = 0.0;
for line in cell.iter_mut() { for line in cell.iter_mut() {
let alignment = line.alignment; let alignment = line.alignment;
write_line_content( write_line_content(
output, output,
&line.content, &line.content,
x, Mm::from(x),
y + Mm::from(cursor + cell_y), y + Mm::from(cursor + cell_y),
alignment, alignment,
false, false,
@@ -190,11 +198,12 @@ fn write_table(
); );
cell_y += scaled_units_to_mm(line.height); cell_y += scaled_units_to_mm(line.height);
} }
x += f64::from(column_width);
} }
cursor += scaled_units_to_mm(row.height); cursor += scaled_units_to_mm(row.height);
} }
if table.rules.contains(&table.rows.len()) { if table.rules.contains(&table.rows.len()) {
write_rule(output, 0.0, cursor, width_mm); write_rule(output, table_x, cursor, table_width_mm);
} }
} }
+1 -1
View File
@@ -258,7 +258,7 @@ fn serves_project_api_preview_and_pdf() {
assert!((value["pageWidthMm"].as_f64().unwrap() - 210.0).abs() < 0.1); assert!((value["pageWidthMm"].as_f64().unwrap() - 210.0).abs() < 0.1);
let pdf = server.request("POST", "/api/projects/hello/pdf", &[], "application/pdf"); let pdf = server.request("POST", "/api/projects/hello/pdf", &[], "application/pdf");
assert_eq!(pdf.status, 200); assert_eq!(pdf.status, 200, "{}", String::from_utf8_lossy(&pdf.body));
assert!(pdf.body.starts_with(b"%PDF-"), "missing PDF header"); assert!(pdf.body.starts_with(b"%PDF-"), "missing PDF header");
} }
+63
View File
@@ -987,6 +987,69 @@ After.
); );
} }
#[test]
fn ascii_documents_use_base14_fonts_without_embedding() {
let source = r"\documentclass{article}
\begin{document}
Plain text that only needs the standard Times encoding.
\end{document}";
let pdf = CompilerSession::default()
.compile(source, "base14.tex")
.expect("base14 PDF");
let text = String::from_utf8_lossy(&pdf);
assert!(
text.contains("Times-Roman"),
"expected a Base-14 Times face"
);
assert!(
!text.contains("FontFile2"),
"ASCII text should not embed a TrueType program"
);
}
#[test]
fn arxiv_table_rules_follow_a_narrow_centered_table() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let file_name = path.to_string_lossy().to_string();
let value = fresh_preview(&source, &file_name);
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 2);
let mut table_rules = Vec::new();
for fragment in svg.split("<line ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
let x1 = tag
.split("x1=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
let x2 = tag
.split("x2=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let (Some(x1), Some(x2)) = (x1, x2) {
let width = x2 - x1;
if x1 > 20.0 && width > 40.0 && width < 140.0 {
table_rules.push((x1, width));
}
}
}
assert!(
table_rules.len() >= 4,
"expected the table's top/mid/bottom rules, got {table_rules:?}"
);
assert!(
table_rules
.iter()
.all(|(x, width)| *x > 20.0 && *width < 140.0),
"table rules should be centered and narrower than the text block: {table_rules:?}"
);
}
#[test] #[test]
fn abstract_environment_gets_an_unumbered_heading() { fn abstract_environment_gets_an_unumbered_heading() {
let source = r"\documentclass{article} let source = r"\documentclass{article}