Measure image saveboxes from decoded pixels
A savebox whose body was only \includegraphics measured as empty text because images were attached to the geometry after geometry_and_body had measured the box. geometry_and_body_with_images now seeds the image map before stripping, so measure_savebox sees the decoded RasterImage: natural size is pixels at 72 dpi (65,782 sp per pixel), and explicit width/height options in the optional argument win, with the other dimension scaled proportionally. Project preview/PDF paths pass their decoded images into the new entry point; the flat preview keeps the empty map. The body-definition capture only handles \newsavebox, so its call passes an empty map too. A test stores a 100x50 image in \logo and checks the frozen width/height and a zero depth.
This commit is contained in:
1 parent
53dcedfea2
commit
57424015de
3 files changed
+119
-14
No files matched your search
@@ -49,7 +49,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
|
|||||||
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
|
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
|
||||||
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
|
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
|
||||||
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
|
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
|
||||||
prefer route-D with a v1 fallback). 1004 workspace tests are green and no oracle
|
prefer route-D with a v1 fallback). 1005 workspace tests are green and no oracle
|
||||||
fixture is ignored. Preview JSON also carries a `warnings` array naming
|
fixture is ignored. Preview JSON also carries a `warnings` array naming
|
||||||
environments route-D cannot lay out and control words that survived layout, so
|
environments route-D cannot lay out and control words that survived layout, so
|
||||||
unsupported source is reported instead of being silently typeset.
|
unsupported source is reported instead of being silently typeset.
|
||||||
|
|||||||
+4
-3
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
|
|||||||
|
|
||||||
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
|
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
|
||||||
|
|
||||||
The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1004 tests (437 route-D unit, 377 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
|
The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1005 tests (437 route-D unit, 378 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
|
||||||
|
|
||||||
### M0 incremental demo
|
### M0 incremental demo
|
||||||
|
|
||||||
@@ -576,8 +576,9 @@ are:
|
|||||||
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
|
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
|
||||||
width/height/depth are measured at definition and frozen (a box keeps its
|
width/height/depth are measured at definition and frozen (a box keeps its
|
||||||
definition size inside differently sized text), and `\wd`/`\ht`/`\dp`
|
definition size inside differently sized text), and `\wd`/`\ht`/`\dp`
|
||||||
expand to those metrics; a box whose content is only an image still measures
|
expand to those metrics; a box whose body contains `\includegraphics`
|
||||||
as empty text.
|
measures the decoded image at 72 dpi, honouring explicit width/height
|
||||||
|
options.
|
||||||
- **Tables**: `\multirow` centres over its rows, `array` column modifiers
|
- **Tables**: `\multirow` centres over its rows, `array` column modifiers
|
||||||
`>{}`/`<{}` and the outer `\tabcolsep` margins are parsed. A nested
|
`>{}`/`<{}` and the outer `\tabcolsep` margins are parsed. A nested
|
||||||
`tabular` is attached to its outer cell as a real inner table: column widths
|
`tabular` is attached to its outer cell as a real inner table: column widths
|
||||||
|
|||||||
+114
-10
@@ -61,8 +61,7 @@ pub fn project_preview_json_with_images(
|
|||||||
source: &str,
|
source: &str,
|
||||||
images: &HashMap<String, RasterImage>,
|
images: &HashMap<String, RasterImage>,
|
||||||
) -> Result<String, String> {
|
) -> Result<String, String> {
|
||||||
let (body, mut geometry) = geometry_and_body(source);
|
let (body, mut geometry) = geometry_and_body_with_images(source, images);
|
||||||
geometry.images = images.clone();
|
|
||||||
let body = resolve_page_references(body, &geometry);
|
let body = resolve_page_references(body, &geometry);
|
||||||
let paragraphs = paragraphs_with_geometry(
|
let paragraphs = paragraphs_with_geometry(
|
||||||
&body,
|
&body,
|
||||||
@@ -2737,7 +2736,10 @@ fn fontspec_family(name: &str) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
fn strip_page_geometry(
|
||||||
|
source: &str,
|
||||||
|
images: &HashMap<String, RasterImage>,
|
||||||
|
) -> (String, PageGeometry) {
|
||||||
// Full-width floats behave like their single-column counterparts here.
|
// Full-width floats behave like their single-column counterparts here.
|
||||||
let source = source
|
let source = source
|
||||||
.replace("\\begin{figure*}", "\\begin{figure}")
|
.replace("\\begin{figure*}", "\\begin{figure}")
|
||||||
@@ -2745,6 +2747,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
|||||||
.replace("\\begin{table*}", "\\begin{table}")
|
.replace("\\begin{table*}", "\\begin{table}")
|
||||||
.replace("\\end{table*}", "\\end{table}");
|
.replace("\\end{table*}", "\\end{table}");
|
||||||
let mut geometry = PageGeometry::default();
|
let mut geometry = PageGeometry::default();
|
||||||
|
geometry.images = images.clone();
|
||||||
let mut body = String::new();
|
let mut body = String::new();
|
||||||
let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None;
|
let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None;
|
||||||
let mut in_document = false;
|
let mut in_document = false;
|
||||||
@@ -2900,6 +2903,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
|||||||
&mut geometry.macros,
|
&mut geometry.macros,
|
||||||
&mut geometry.savebox_dimensions,
|
&mut geometry.savebox_dimensions,
|
||||||
base,
|
base,
|
||||||
|
images,
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -5195,6 +5199,7 @@ fn expand_saveboxes(
|
|||||||
macros: &mut Vec<MacroDefinition>,
|
macros: &mut Vec<MacroDefinition>,
|
||||||
dimensions: &mut Vec<(String, (i64, i64, i64))>,
|
dimensions: &mut Vec<(String, (i64, i64, i64))>,
|
||||||
base_size: i64,
|
base_size: i64,
|
||||||
|
images: &HashMap<String, RasterImage>,
|
||||||
) -> String {
|
) -> String {
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
let mut index = 0;
|
let mut index = 0;
|
||||||
@@ -5237,7 +5242,11 @@ fn expand_saveboxes(
|
|||||||
body: content.to_string(),
|
body: content.to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
set_savebox_dimensions(dimensions, &name, measure_savebox(content, base_size));
|
set_savebox_dimensions(
|
||||||
|
dimensions,
|
||||||
|
&name,
|
||||||
|
measure_savebox(content, base_size, images),
|
||||||
|
);
|
||||||
index += rest.len() - body_rest.len() + used_body;
|
index += rest.len() - body_rest.len() + used_body;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -5256,6 +5265,7 @@ fn handle_savebox_line(
|
|||||||
macros: &mut Vec<MacroDefinition>,
|
macros: &mut Vec<MacroDefinition>,
|
||||||
dimensions: &mut Vec<(String, (i64, i64, i64))>,
|
dimensions: &mut Vec<(String, (i64, i64, i64))>,
|
||||||
base_size: i64,
|
base_size: i64,
|
||||||
|
images: &HashMap<String, RasterImage>,
|
||||||
) {
|
) {
|
||||||
let rest = line.trim_start();
|
let rest = line.trim_start();
|
||||||
if let Some(after) = rest.strip_prefix("\\newsavebox") {
|
if let Some(after) = rest.strip_prefix("\\newsavebox") {
|
||||||
@@ -5299,7 +5309,7 @@ fn handle_savebox_line(
|
|||||||
body: body.to_string(),
|
body: body.to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
set_savebox_dimensions(dimensions, &name, measure_savebox(body, base_size));
|
set_savebox_dimensions(dimensions, &name, measure_savebox(body, base_size, images));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_savebox_dimensions(
|
fn set_savebox_dimensions(
|
||||||
@@ -5315,7 +5325,65 @@ fn set_savebox_dimensions(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Measure a savebox body with the Roman metrics at `base_size`.
|
/// Measure a savebox body with the Roman metrics at `base_size`.
|
||||||
fn measure_savebox(content: &str, base_size: i64) -> (i64, i64, i64) {
|
/// Measure an `\includegraphics` body from decoded image pixels (72 dpi),
|
||||||
|
/// honouring explicit width/height options.
|
||||||
|
fn graphic_measure(content: &str, images: &HashMap<String, RasterImage>) -> Option<(i64, i64)> {
|
||||||
|
const SP_PER_PIXEL: i64 = 65_782;
|
||||||
|
let index = content.find("\\includegraphics")?;
|
||||||
|
let after = &content[index + "\\includegraphics".len()..];
|
||||||
|
let trimmed = after.trim_start();
|
||||||
|
let mut rest = trimmed;
|
||||||
|
let options = if let Some(stripped) = rest.strip_prefix('[') {
|
||||||
|
let (inside, tail) = stripped.split_once(']')?;
|
||||||
|
rest = tail.trim_start();
|
||||||
|
Some(inside)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let (path, _) = braced_group(rest)?;
|
||||||
|
let path = path.trim().trim_matches('"');
|
||||||
|
let image = images.get(path)?;
|
||||||
|
let natural_width = image.width as i64 * SP_PER_PIXEL;
|
||||||
|
let natural_height = image.height as i64 * SP_PER_PIXEL;
|
||||||
|
let mut width = None;
|
||||||
|
let mut height = None;
|
||||||
|
if let Some(options) = options {
|
||||||
|
for option in options.split(',') {
|
||||||
|
let option = option.trim();
|
||||||
|
if let Some(value) = option.strip_prefix("width") {
|
||||||
|
if let Some((_, dimension)) = value.split_once('=') {
|
||||||
|
width = parse_dimension(dimension.trim());
|
||||||
|
}
|
||||||
|
} else if let Some(value) = option.strip_prefix("height")
|
||||||
|
&& let Some((_, dimension)) = value.split_once('=')
|
||||||
|
{
|
||||||
|
height = parse_dimension(dimension.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (width, height) = match (width, height) {
|
||||||
|
(Some(width), Some(height)) => (width, height),
|
||||||
|
(Some(width), None) => (
|
||||||
|
width,
|
||||||
|
width.saturating_mul(natural_height) / natural_width.max(1),
|
||||||
|
),
|
||||||
|
(None, Some(height)) => (
|
||||||
|
height.saturating_mul(natural_width) / natural_height.max(1),
|
||||||
|
height,
|
||||||
|
),
|
||||||
|
(None, None) => (natural_width, natural_height),
|
||||||
|
};
|
||||||
|
Some((width, height))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn measure_savebox(
|
||||||
|
content: &str,
|
||||||
|
base_size: i64,
|
||||||
|
images: &HashMap<String, RasterImage>,
|
||||||
|
) -> (i64, i64, i64) {
|
||||||
|
if let Some((width, height)) = graphic_measure(content, images) {
|
||||||
|
return (width, height, 0);
|
||||||
|
}
|
||||||
let cleaned = scrub_title_metadata(&strip_box_commands(content));
|
let cleaned = scrub_title_metadata(&strip_box_commands(content));
|
||||||
let metrics = Cmr10Metrics::Roman;
|
let metrics = Cmr10Metrics::Roman;
|
||||||
let scale = |value: i64| value.saturating_mul(base_size) / 655_360;
|
let scale = |value: i64| value.saturating_mul(base_size) / 655_360;
|
||||||
@@ -5514,7 +5582,13 @@ fn capture_body_definitions(
|
|||||||
// Only the name is reserved here; the body's \sbox is measured by
|
// Only the name is reserved here; the body's \sbox is measured by
|
||||||
// expand_saveboxes once the geometry is available.
|
// expand_saveboxes once the geometry is available.
|
||||||
let mut ignored_dimensions = Vec::new();
|
let mut ignored_dimensions = Vec::new();
|
||||||
handle_savebox_line(trimmed, macros, &mut ignored_dimensions, 655_360);
|
handle_savebox_line(
|
||||||
|
trimmed,
|
||||||
|
macros,
|
||||||
|
&mut ignored_dimensions,
|
||||||
|
655_360,
|
||||||
|
&HashMap::new(),
|
||||||
|
);
|
||||||
changed = true;
|
changed = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -5994,6 +6068,13 @@ fn collapse_braced_command(source: &str, command: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
||||||
|
geometry_and_body_with_images(source, &HashMap::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn geometry_and_body_with_images(
|
||||||
|
source: &str,
|
||||||
|
images: &HashMap<String, RasterImage>,
|
||||||
|
) -> (String, PageGeometry) {
|
||||||
// Class files put page setup inside `\AtBeginDocument{...}`; run that
|
// Class files put page setup inside `\AtBeginDocument{...}`; run that
|
||||||
// body before `\begin{document}` so its commands are consumed as setup
|
// body before `\begin{document}` so its commands are consumed as setup
|
||||||
// instead of being typeset as text at the top of page one.
|
// instead of being typeset as text at the top of page one.
|
||||||
@@ -6007,7 +6088,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
|||||||
let source = collapse_braced_command(&source, "\\title");
|
let source = collapse_braced_command(&source, "\\title");
|
||||||
let source = collapse_braced_command(&source, "\\author");
|
let source = collapse_braced_command(&source, "\\author");
|
||||||
let source = collapse_braced_command(&source, "\\date");
|
let source = collapse_braced_command(&source, "\\date");
|
||||||
let (stripped, mut geometry) = strip_page_geometry(&source);
|
let (stripped, mut geometry) = strip_page_geometry(&source, images);
|
||||||
dedupe_macros(&mut geometry.macros);
|
dedupe_macros(&mut geometry.macros);
|
||||||
// Removed assignments can leave blank lines at the edges; they are not
|
// Removed assignments can leave blank lines at the edges; they are not
|
||||||
// paragraphs of their own.
|
// paragraphs of their own.
|
||||||
@@ -6039,6 +6120,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
|||||||
&mut geometry.macros,
|
&mut geometry.macros,
|
||||||
&mut geometry.savebox_dimensions,
|
&mut geometry.savebox_dimensions,
|
||||||
savebox_base,
|
savebox_base,
|
||||||
|
&geometry.images,
|
||||||
);
|
);
|
||||||
body = expand_box_dimensions(&body, &geometry.savebox_dimensions);
|
body = expand_box_dimensions(&body, &geometry.savebox_dimensions);
|
||||||
dedupe_macros(&mut geometry.macros);
|
dedupe_macros(&mut geometry.macros);
|
||||||
@@ -6788,8 +6870,7 @@ pub fn pdf_bytes_with_images(
|
|||||||
source: &str,
|
source: &str,
|
||||||
images: &HashMap<String, RasterImage>,
|
images: &HashMap<String, RasterImage>,
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> Result<Vec<u8>, String> {
|
||||||
let (body, mut geometry) = geometry_and_body(source);
|
let (body, mut geometry) = geometry_and_body_with_images(source, images);
|
||||||
geometry.images = images.clone();
|
|
||||||
let body = resolve_page_references(body, &geometry);
|
let body = resolve_page_references(body, &geometry);
|
||||||
let paragraphs = paragraphs_with_geometry(
|
let paragraphs = paragraphs_with_geometry(
|
||||||
&body,
|
&body,
|
||||||
@@ -15922,6 +16003,29 @@ A definition.
|
|||||||
assert!(!text.contains("makeatletter"), "{text}");
|
assert!(!text.contains("makeatletter"), "{text}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_saveboxes_measure_the_image() {
|
||||||
|
let mut images = HashMap::new();
|
||||||
|
images.insert(
|
||||||
|
"plot.png".to_string(),
|
||||||
|
RasterImage {
|
||||||
|
width: 100,
|
||||||
|
height: 50,
|
||||||
|
rgb: vec![0; 100 * 50 * 3],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let source = "\\newsavebox{\\logo}\n\\sbox{\\logo}{\\includegraphics{plot.png}}\n\nX\\hspace{\\wd\\logo}Y";
|
||||||
|
let (_body, geometry) = geometry_and_body_with_images(source, &images);
|
||||||
|
let (_, (width, height, depth)) = geometry
|
||||||
|
.savebox_dimensions
|
||||||
|
.iter()
|
||||||
|
.find(|(name, _)| name == "\\logo")
|
||||||
|
.expect("savebox dimensions");
|
||||||
|
assert_eq!(*width, 100 * 65_782);
|
||||||
|
assert_eq!(*height, 50 * 65_782);
|
||||||
|
assert_eq!(*depth, 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn token_registers_store_and_expand() {
|
fn token_registers_store_and_expand() {
|
||||||
let source = "\\documentclass{article}\n\\begin{document}\n\n\\newtoks\\greet\n\\greet={Hello}\n\\toks0={A}\n\n\\the\\greet and \\the\\toks0 B\n\n\\end{document}\n";
|
let source = "\\documentclass{article}\n\\begin{document}\n\n\\newtoks\\greet\n\\greet={Hello}\n\\toks0={A}\n\n\\the\\greet and \\the\\toks0 B\n\n\\end{document}\n";
|
||||||
|
|||||||
Reference in new issue
Block a user