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:
gloamxun committed 2026-10-27 01:14:02 +08:00
1 parent 53dcedfea2
commit 57424015de
3 files changed
+119 -14

No files matched your search

+114 -10
View File
@@ -61,8 +61,7 @@ pub fn project_preview_json_with_images(
source: &str,
images: &HashMap<String, RasterImage>,
) -> Result<String, String> {
let (body, mut geometry) = geometry_and_body(source);
geometry.images = images.clone();
let (body, mut geometry) = geometry_and_body_with_images(source, images);
let body = resolve_page_references(body, &geometry);
let paragraphs = paragraphs_with_geometry(
&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.
let source = source
.replace("\\begin{figure*}", "\\begin{figure}")
@@ -2745,6 +2747,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
.replace("\\begin{table*}", "\\begin{table}")
.replace("\\end{table*}", "\\end{table}");
let mut geometry = PageGeometry::default();
geometry.images = images.clone();
let mut body = String::new();
let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None;
let mut in_document = false;
@@ -2900,6 +2903,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
&mut geometry.macros,
&mut geometry.savebox_dimensions,
base,
images,
);
continue;
}
@@ -5195,6 +5199,7 @@ fn expand_saveboxes(
macros: &mut Vec<MacroDefinition>,
dimensions: &mut Vec<(String, (i64, i64, i64))>,
base_size: i64,
images: &HashMap<String, RasterImage>,
) -> String {
let mut out = String::new();
let mut index = 0;
@@ -5237,7 +5242,11 @@ fn expand_saveboxes(
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;
continue;
}
@@ -5256,6 +5265,7 @@ fn handle_savebox_line(
macros: &mut Vec<MacroDefinition>,
dimensions: &mut Vec<(String, (i64, i64, i64))>,
base_size: i64,
images: &HashMap<String, RasterImage>,
) {
let rest = line.trim_start();
if let Some(after) = rest.strip_prefix("\\newsavebox") {
@@ -5299,7 +5309,7 @@ fn handle_savebox_line(
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(
@@ -5315,7 +5325,65 @@ fn set_savebox_dimensions(
}
/// 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 metrics = Cmr10Metrics::Roman;
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
// expand_saveboxes once the geometry is available.
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;
continue;
}
@@ -5994,6 +6068,13 @@ fn collapse_braced_command(source: &str, command: &str) -> String {
}
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
// body before `\begin{document}` so its commands are consumed as setup
// 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, "\\author");
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);
// Removed assignments can leave blank lines at the edges; they are not
// paragraphs of their own.
@@ -6039,6 +6120,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
&mut geometry.macros,
&mut geometry.savebox_dimensions,
savebox_base,
&geometry.images,
);
body = expand_box_dimensions(&body, &geometry.savebox_dimensions);
dedupe_macros(&mut geometry.macros);
@@ -6788,8 +6870,7 @@ pub fn pdf_bytes_with_images(
source: &str,
images: &HashMap<String, RasterImage>,
) -> Result<Vec<u8>, String> {
let (body, mut geometry) = geometry_and_body(source);
geometry.images = images.clone();
let (body, mut geometry) = geometry_and_body_with_images(source, images);
let body = resolve_page_references(body, &geometry);
let paragraphs = paragraphs_with_geometry(
&body,
@@ -15922,6 +16003,29 @@ A definition.
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]
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";