diff --git a/README.md b/README.md index e9a5bd3..64e8db8 100644 --- a/README.md +++ b/README.md @@ -127,8 +127,10 @@ page breaks, basic display and inline math, figures, simple tables, 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 -`geometry` sets them. Liberation Serif is embedded in the PDF for Latin and math -glyphs; CJK text uses an installed fallback font. +`geometry` sets them. The PDF uses the Base-14 Times/Courier faces without +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 @@ -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. It supports `width`, `height`, and `scale`; width and height accept physical units or fractions of `\linewidth`. Images with transparency are not supported -by the current PDF dependency. Basic `tabular` rows become equal-width PDF -columns; `l`, `c`, `r`, and paragraph (`p{...}`) columns are supported, as are -full-width `\hline` and `booktabs` rules. Spanning cells, partial `\cline` rules, -and multi-page table headers are not implemented. Figures honor `[htbp]` +by the current PDF dependency. Basic `tabular` rows use natural column widths +(content width plus 6pt `\tabcolsep`), are centered in the text block, and draw +`\hline`/`booktabs` rules exactly over the table columns; `l`, `c`, `r`, and +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 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 diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 93e82fd..f92d9f3 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -17,7 +17,8 @@ abstract quotation formatting, unnumbered `\paragraph` headings, natbib-style author-year citations and plainnat bibliography formatting; `\vbox`/`\vtop` vertical-material capture with inline splicing (`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 diff --git a/docs/STATUS.md b/docs/STATUS.md index e3c97fe..93d02c2 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -101,7 +101,10 @@ See `docs/ROADMAP.md` for concrete implementation plans. - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to 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 fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output, project API, static frontend assets, path traversal, the legacy diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index dd4ca0a..3735624 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -105,9 +105,10 @@ struct PositionedTableRow { struct PositionedTable { rows: Vec, - column_count: usize, + column_widths: Vec, rules: HashSet, height: i64, + table_width: i64, } 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 = self + .column_widths + .iter() + .map(|width| (((*width).max(1) * 255) / total.max(1)).clamp(1, 255) as usize) + .collect(); let mut y = 0_i64; 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))); if self.rules.contains(&row_index) { - let width = area.size().width; + let width = table_area.size().width; row_area.draw_line( vec![Position::default(), Position::new(width, 0.0)], Style::new(), @@ -250,9 +261,9 @@ impl PositionedTable { y = y.saturating_add(row.height); } 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))); - let width = area.size().width; + let width = table_area.size().width; rule_area.draw_line( vec![Position::default(), Position::new(width, 0.0)], Style::new(), @@ -1785,8 +1796,14 @@ struct FontInputs { impl FontInputs { fn load(model: &DocumentModel) -> Result { let latin_dir = latin_font_directory()?; - // The embedded face is needed for math glyphs outside built-in Times's WinAnsi encoding. - let latin_fonts = fonts::from_files(&latin_dir, "LiberationSerif", None) + // Use the Base-14 faces when every text character is representable; + // 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}"))?; let cjk_path = document_contains_cjk(model) .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(¬e.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 { 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) { diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 7a8f1ce..2f5f5b2 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -549,12 +549,7 @@ fn layout_table( if column_count == 0 { return None; } - let cell_width_mm = content_width_mm / column_count as f64; - if cell_width_mm <= 0.0 { - return None; - } - - let cell_font_size = font_size.saturating_sub(1).max(1); + let cell_font_size = font_size.max(1); let empty_row_height = font_line_height_scaled( font_cache, cjk_family, @@ -562,6 +557,80 @@ fn layout_table( sans_family, 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::() 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 = 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 = 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 total_height = 0_i64; for row in rows { @@ -569,10 +638,11 @@ fn layout_table( let mut row_height = empty_row_height; for column in 0..column_count { 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( runs, cell_font_size, - cell_width_mm, + available_mm, metrics, font_cache, cjk_family, @@ -613,9 +683,10 @@ fn layout_table( Some(PositionedTable { rows: positioned_rows, - column_count, + column_widths, rules: rules.iter().copied().collect(), height: total_height, + table_width, }) } @@ -2328,8 +2399,9 @@ pub(super) fn build_positioned_pages( } let PositionedTable { rows: table_rows, - column_count, + column_widths, rules: table_rules, + table_width, .. } = table; for (row_index, row) in table_rows.into_iter().enumerate() { @@ -2352,9 +2424,10 @@ pub(super) fn build_positioned_pages( }, element: PositionedTable { rows: vec![row], - column_count, + column_widths: column_widths.clone(), rules: row_rules, height: row_height, + table_width, }, y, }); @@ -2452,8 +2525,9 @@ pub(super) fn build_positioned_pages( if let Some(table) = table { let PositionedTable { rows: table_rows, - column_count, + column_widths, rules: table_rules, + table_width, .. } = table; for (row_index, row) in table_rows.into_iter().enumerate() { @@ -2499,9 +2573,10 @@ pub(super) fn build_positioned_pages( } let element = PositionedTable { rows: vec![row], - column_count, + column_widths: column_widths.clone(), rules: row_rules, height: row_height, + table_width, }; pages .last_mut() diff --git a/src/rust_typeset/pdf/preview.rs b/src/rust_typeset/pdf/preview.rs index bd2165b..7f2921e 100644 --- a/src/rust_typeset/pdf/preview.rs +++ b/src/rust_typeset/pdf/preview.rs @@ -163,22 +163,30 @@ fn write_table( monospace_family: Option>, sans_family: Option>, ) { - let width_mm = f64::from(content_width); - let column_width = Mm::from(width_mm / table.column_count.max(1) as f64); + let text_width_mm = f64::from(content_width); + 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; for (row_index, row) in table.rows.iter_mut().enumerate() { 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() { - 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; for line in cell.iter_mut() { let alignment = line.alignment; write_line_content( output, &line.content, - x, + Mm::from(x), y + Mm::from(cursor + cell_y), alignment, false, @@ -190,11 +198,12 @@ fn write_table( ); cell_y += scaled_units_to_mm(line.height); } + x += f64::from(column_width); } cursor += scaled_units_to_mm(row.height); } if table.rules.contains(&table.rows.len()) { - write_rule(output, 0.0, cursor, width_mm); + write_rule(output, table_x, cursor, table_width_mm); } } diff --git a/tests/server.rs b/tests/server.rs index a658850..39ab5f7 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -258,7 +258,7 @@ fn serves_project_api_preview_and_pdf() { assert!((value["pageWidthMm"].as_f64().unwrap() - 210.0).abs() < 0.1); 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"); } diff --git a/tests/typeset.rs b/tests/typeset.rs index f62c4b5..c3314a2 100644 --- a/tests/typeset.rs +++ b/tests/typeset.rs @@ -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("').next().unwrap_or(fragment); + let x1 = tag + .split("x1=\"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .and_then(|value| value.parse::().ok()); + let x2 = tag + .split("x2=\"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .and_then(|value| value.parse::().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] fn abstract_environment_gets_an_unumbered_heading() { let source = r"\documentclass{article}