fix(pdf): view images keep their proportions, full width from 3:1

An image over its row budget is reduced as a whole and centred in its
cell; views at least 3:1 take a full row; the views' order is kept (A4).
Frozen O1 draw logs and R4 digests unchanged.
Wasm gzip: 596453 B of 600000 (margin 3547).
This commit is contained in:
bchanot committed 2026-11-23 00:45:13 +01:00
1 parent 6b7e1da1bc
commit 13a198045c
1 file changed
+286 -62
+286 -62
View File
@@ -16,11 +16,17 @@ use crate::domain::sheet::IndexedDocument;
use crate::domain::sheet::schema::{LocalizedText, SheetView};
use crate::json::js_number;
use crate::pdf::write::draw_log::{
ImageOp, LineOp, PAGE_HEIGHT, PAGE_WIDTH, Point, RectangleOp, Rgb, TextOp, rgb,
DrawLog, ImageOp, LineOp, PAGE_HEIGHT, PAGE_WIDTH, Point, RectangleOp, Rgb, TextOp, rgb,
};
use crate::pdf::write::text::{js_trim, js_upper, measure, safe_text, wrap_lines};
const MARGIN_BOTTOM: f64 = 48.0;
/// Views at least this many times wider than high take a whole row (owner, 2026-11-22). The
/// editor's « Page du PDF » preview decides on the same frame numbers (`PDF_FULL_WIDTH_RATIO`).
pub(crate) const FULL_WIDTH_MIN_RATIO: f64 = 3.0;
/// The lowest baseline a body line may take. The footer rule is drawn at y 70 (`footer.rs`);
/// a 10 pt line's descender reaches about 2.1 pt under its baseline, and the 14 pt bullet of a
/// segmented line is drawn 1.2 pt lower: at 76 both keep a point clear of the rule.
const TEXT_FLOOR_Y: f64 = 76.0;
const IMAGE_TOP_GAP: f64 = 32.0;
const IMAGE_LABEL_GAP: f64 = 14.0;
const IMAGE_BOTTOM_GAP: f64 = 14.0;
@@ -30,6 +36,10 @@ const IMAGE_MIN_CELL_H: f64 = 60.0;
const TEXT_TOP_GAP: f64 = 10.0;
const TEXT_LINE_HEIGHT: f64 = 13.0;
const SECTION_BLOCK_GAP: f64 = 10.0;
/// The cursor after the last section when its last line sits on the floor.
const TEXT_BOTTOM: f64 = TEXT_FLOOR_Y - TEXT_LINE_HEIGHT - SECTION_BLOCK_GAP;
/// The text width, and the width of a full-width image.
const BODY_W: f64 = PAGE_WIDTH - MARGIN_X * 2.0;
const COLOR_WHITE: Rgb = rgb(1.0, 1.0, 1.0);
const SECTION_TEXT_SIZE: f64 = 10.0;
const SEPARATOR_GLYPH: &str = "•";
@@ -298,6 +308,19 @@ struct Rendered {
label: String,
image: Image,
aspect: f64,
wide: bool,
}
/// A view at least `FULL_WIDTH_MIN_RATIO` times wider than high: by its frame when it has one,
/// else by its raster's pixels.
fn is_wide(view: Option<&SheetView>, image: &Image) -> bool {
match view.and_then(SheetView::view_box) {
Some(frame) => frame.width >= FULL_WIDTH_MIN_RATIO * frame.height,
None => {
image.height > 0
&& f64::from(image.width) >= FULL_WIDTH_MIN_RATIO * f64::from(image.height)
}
}
}
/// The embedded views with their labels and aspects (`buildObservationImages` after
@@ -307,9 +330,8 @@ fn build_images(layout: &Layout<'_>, images: &[ViewImage]) -> Vec<Rendered> {
images
.iter()
.map(|ViewImage { view_id, image }| {
let label = sheet
.view(view_id)
.map_or_else(String::new, |v| view_label(layout, v));
let view = sheet.view(view_id);
let label = view.map_or_else(String::new, |v| view_label(layout, v));
let aspect = if image.width > 0 {
f64::from(image.height) / f64::from(image.width)
} else {
@@ -319,23 +341,57 @@ fn build_images(layout: &Layout<'_>, images: &[ViewImage]) -> Vec<Rendered> {
label,
image: *image,
aspect,
wide: is_wide(view, image),
}
})
.collect()
}
struct Grid {
cols: usize,
rows: usize,
/// One row of images of the same cell width, the first cell at `x`.
struct Row<'a> {
items: Vec<&'a Rendered>,
cell_w: f64,
offset_x: f64,
row_budget: f64,
x: f64,
}
fn grid_of(count: usize, avail_h: f64) -> Grid {
let is_single = count == 1;
impl Row<'_> {
fn cell_x(&self, column: usize) -> f64 {
self.x + column as f64 * (self.cell_w + IMAGE_COL_GAP)
}
}
/// A4 (owner 2026-11-22: the reading order never changes): the views in their order; each run
/// of classic views fills the two-column grid as before (one alone centred at half width, an odd
/// last one in the left column), and each wide view takes a full row where it stands.
fn rows_of(rendered: &[Rendered]) -> Vec<Row<'_>> {
let mut rows = Vec::new();
let mut run: Vec<&Rendered> = Vec::new();
for it in rendered {
if it.wide {
rows.extend(grid_rows(&run));
run.clear();
rows.push(full_row(it));
} else {
run.push(it);
}
}
rows.extend(grid_rows(&run));
rows
}
fn full_row(it: &Rendered) -> Row<'_> {
Row {
items: vec![it],
cell_w: BODY_W,
x: MARGIN_X,
}
}
/// The grid of before 2026-11-22 (`grid_of`), the same arithmetic, so a page that fits draws
/// the same calls to the last bit (O1).
fn grid_rows<'a>(narrow: &[&'a Rendered]) -> Vec<Row<'a>> {
let is_single = narrow.len() == 1;
let cols = if is_single { 1 } else { 2 };
let rows = count.div_ceil(cols);
let full_cell_w =
(PAGE_WIDTH - MARGIN_X * 2.0 - IMAGE_COL_GAP * (cols - 1) as f64) / cols as f64;
let cell_w = if is_single {
@@ -343,40 +399,56 @@ fn grid_of(count: usize, avail_h: f64) -> Grid {
} else {
full_cell_w
};
let offset_x = if is_single {
(full_cell_w - cell_w) / 2.0
} else {
0.0
};
narrow
.chunks(cols)
.map(|chunk| Row {
items: chunk.to_vec(),
cell_w,
x: MARGIN_X + offset_x,
})
.collect()
}
/// The height each row's images may take, as before 2026-11-22 (`grid_of`): the room the
/// text leaves, split between the rows, never under `IMAGE_MIN_CELL_H`.
fn row_budget(rows: usize, avail: f64) -> f64 {
let rows_f = rows as f64;
Grid {
cols,
rows,
cell_w,
offset_x: if is_single {
(full_cell_w - cell_w) / 2.0
} else {
0.0
},
row_budget: IMAGE_MIN_CELL_H
.max((avail_h - rows_f * IMAGE_LABEL_GAP - (rows_f - 1.0) * IMAGE_ROW_GAP) / rows_f),
IMAGE_MIN_CELL_H
.max((avail - rows_f * IMAGE_LABEL_GAP - (rows_f - 1.0) * IMAGE_ROW_GAP) / rows_f)
}
/// The image's size in a cell `cell_w` wide and `budget` high, keeping its own proportions
/// (R2: never squashed, never stretched); under the budget, its natural size.
fn fitted(cell_w: f64, aspect: f64, budget: f64) -> (f64, f64) {
let natural = cell_w * aspect;
if natural <= budget {
(cell_w, natural)
} else {
(budget / aspect, budget)
}
}
/// One row of the grid: labels above, then the images; returns the row height.
fn draw_image_row(
layout: &mut Layout<'_>,
page: usize,
row: &[Rendered],
grid: &Grid,
top_y: f64,
) -> f64 {
let cell_hs: Vec<f64> = row
/// One row: the labels at their cells' left edge, as before, then each image fitted in its cell
/// and centred in it; returns the row height. An image under the budget is drawn as before
/// 2026-11-22, to the last bit.
fn draw_row(log: &mut DrawLog, page: usize, row: &Row<'_>, budget: f64, top_y: f64) -> f64 {
let sizes: Vec<(f64, f64)> = row
.items
.iter()
.map(|it| (grid.cell_w * it.aspect).min(grid.row_budget))
.map(|it| fitted(row.cell_w, it.aspect, budget))
.collect();
let cell_x = |c: usize| MARGIN_X + grid.offset_x + c as f64 * (grid.cell_w + IMAGE_COL_GAP);
for (c, it) in row.iter().enumerate() {
layout.log.text(
let x_of = |c: usize, width: f64| row.cell_x(c) + (row.cell_w - width) / 2.0;
for (c, it) in row.items.iter().enumerate() {
log.text(
page,
TextOp {
text: safe_text(&it.label),
x: cell_x(c),
x: row.cell_x(c),
y: top_y,
size: 8.0,
font: BODY_BOLD,
@@ -385,40 +457,40 @@ fn draw_image_row(
);
}
let images_y = top_y - IMAGE_LABEL_GAP;
for (c, it) in row.iter().enumerate() {
layout.log.image(
for (c, (it, (width, height))) in row.items.iter().zip(&sizes).enumerate() {
log.image(
page,
ImageOp {
embed: it.image.embed,
x: cell_x(c),
y: images_y - cell_hs[c],
width: grid.cell_w,
height: cell_hs[c],
x: x_of(c, *width),
y: images_y - height,
width: *width,
height: *height,
},
);
}
cell_hs.iter().fold(0.0, |max, h| f64::max(max, *h))
sizes.iter().fold(0.0, |max, (_, h)| f64::max(max, *h))
}
/// The (up to 2-column) image grid; returns the cursor y below it.
fn draw_image_grid(
layout: &mut Layout<'_>,
/// The views' rows from `start_y` down; returns the cursor under them (`start_y` when none).
fn draw_images(
log: &mut DrawLog,
page: usize,
rendered: &[Rendered],
start_y: f64,
reserved_bottom: f64,
text_need: f64,
) -> f64 {
if rendered.is_empty() {
return start_y;
}
let avail_h = IMAGE_MIN_CELL_H.max(start_y - reserved_bottom);
let grid = grid_of(rendered.len(), avail_h);
let rows = rows_of(rendered);
let avail = IMAGE_MIN_CELL_H.max(start_y - (TEXT_BOTTOM + text_need + IMAGE_BOTTOM_GAP));
let budget = row_budget(rows.len(), avail);
let mut cursor_y = start_y;
for r in 0..grid.rows {
let row = &rendered[r * grid.cols..(r * grid.cols + grid.cols).min(rendered.len())];
let row_h = draw_image_row(layout, page, row, &grid, cursor_y);
for (r, row) in rows.iter().enumerate() {
let row_h = draw_row(log, page, row, budget, cursor_y);
cursor_y -= IMAGE_LABEL_GAP + row_h;
if r < grid.rows - 1 {
if r < rows.len() - 1 {
cursor_y -= IMAGE_ROW_GAP;
}
}
@@ -641,17 +713,169 @@ pub fn add_observation_page(
draw_header(layout, page, header);
let title_y = draw_title_block(layout, page, position, observation.severity);
let rendered = build_images(layout, images);
let max_text_w = PAGE_WIDTH - MARGIN_X * 2.0;
let sections = sections(layout, observation);
let reserved_bottom =
MARGIN_BOTTOM + estimate_sections_height(&sections, max_text_w) + IMAGE_BOTTOM_GAP;
let mut cursor_y = draw_image_grid(
layout,
let text_need = estimate_sections_height(&sections, BODY_W);
let mut cursor_y = draw_images(
&mut layout.log,
page,
&rendered,
title_y - IMAGE_TOP_GAP,
reserved_bottom,
text_need,
);
cursor_y -= TEXT_TOP_GAP;
draw_sections(layout, page, &sections, cursor_y, max_text_w);
draw_sections(layout, page, &sections, cursor_y, BODY_W);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pdf::write::draw_log::DrawOp;
fn rendered(embed: usize, width: u32, height: u32, wide: bool) -> Rendered {
Rendered {
label: format!("V{embed}"),
image: Image {
embed,
width,
height,
},
aspect: f64::from(height) / f64::from(width),
wide,
}
}
/// Draws the rows with a text need leaving `avail`, from the usual start; the image ops.
fn draw(rendered: &[Rendered], avail: f64) -> Vec<ImageOp> {
let mut log = DrawLog::default();
let page = log.add_page();
let rows = rows_of(rendered);
let budget = row_budget(rows.len(), avail);
let mut top_y = 687.89;
for row in &rows {
top_y -= IMAGE_LABEL_GAP + draw_row(&mut log, page, row, budget, top_y);
top_y -= IMAGE_ROW_GAP;
}
log.calls_in_order()
.filter_map(|(_, op)| match op {
DrawOp::Image(image) => Some(*image),
_ => None,
})
.collect()
}
fn row_embeds(rendered: &[Rendered]) -> Vec<Vec<usize>> {
rows_of(rendered)
.iter()
.map(|row| row.items.iter().map(|it| it.image.embed).collect())
.collect()
}
#[allow(clippy::expect_used)]
fn view(width: f64, height: f64) -> SheetView {
serde_json::from_value(serde_json::json!({
"id": "d1",
"name": { "fr": "a", "en": "b" },
"svg_asset_id": null,
"view_box": { "min_x": 0, "min_y": 0, "width": width, "height": height },
"kind": "detail",
"parent_view_id": "main",
}))
.expect("a detail view")
}
#[test]
fn natural_fit_keeps_todays_geometry() {
let one = draw(&[rendered(0, 1200, 1200, false)], 600.0);
assert_eq!(one.len(), 1);
assert!((one[0].x - 166.82).abs() < 1e-9);
assert!((one[0].width - 261.64).abs() < 1e-9);
assert!((one[0].height - 261.64).abs() < 1e-9);
assert!((one[0].y - (687.89 - 14.0 - 261.64)).abs() < 1e-9);
let two = draw(
&[
rendered(0, 1200, 1200, false),
rendered(1, 1200, 1200, false),
],
600.0,
);
assert!((two[0].x - 36.0).abs() < 1e-9);
assert!((two[1].x - 305.64).abs() < 1e-9);
assert!((two[1].width - 253.64).abs() < 1e-9);
}
#[test]
fn capped_image_keeps_proportions_alone() {
let views = [rendered(0, 1200, 943, false), rendered(1, 800, 2400, false)];
// avail - 14 = 300 for one row.
let ops = draw(&views, 314.0);
assert!((ops[0].width - 253.64).abs() < 1e-9);
assert!((ops[0].height - 253.64 * 943.0 / 1200.0).abs() < 1e-9);
assert!((ops[0].x - 36.0).abs() < 1e-9);
assert!((ops[1].width - 100.0).abs() < 1e-9);
assert!((ops[1].height - 300.0).abs() < 1e-9);
assert!((ops[1].width / ops[1].height - 1.0 / 3.0).abs() < 1e-9);
assert!((ops[1].x - (305.64 + (253.64 - 100.0) / 2.0)).abs() < 1e-9);
let mut log = DrawLog::default();
let page = log.add_page();
let rows = rows_of(&views);
draw_row(&mut log, page, &rows[0], 300.0, 687.89);
let label_x: Vec<f64> = log
.calls_in_order()
.filter_map(|(_, op)| match op {
DrawOp::Text(text) => Some(text.x),
_ => None,
})
.collect();
assert!((label_x[1] - 305.64).abs() < 1e-9);
}
#[test]
fn full_width_from_three_to_one_on_the_frame() {
assert!(is_wide(
Some(&view(300.0, 100.0)),
&rendered(0, 10, 10, false).image
));
assert!(!is_wide(
Some(&view(299.0, 100.0)),
&rendered(0, 10, 10, false).image
));
assert!(is_wide(None, &rendered(0, 300, 100, false).image));
assert!(!is_wide(None, &rendered(0, 299, 100, false).image));
let wide = draw(&[rendered(0, 300, 100, true)], 600.0);
assert!((wide[0].width - 523.28).abs() < 1e-9);
assert!((wide[0].height - 174.426_666_666_666_66).abs() < 1e-6);
}
#[test]
fn views_keep_their_order_around_a_wide_view() {
let main = rendered(0, 1200, 1200, false);
let head = rendered(1, 1200, 1200, false);
let wide = rendered(2, 700, 100, true);
let list = [main, wide, head];
assert_eq!(row_embeds(&list), vec![vec![0], vec![2], vec![1]]);
let rows = rows_of(&list);
assert!((rows[0].cell_w - 261.64).abs() < 1e-9);
assert!((rows[2].cell_w - 261.64).abs() < 1e-9);
let list = [
rendered(0, 1200, 1200, false),
rendered(1, 1200, 1200, false),
rendered(2, 700, 100, true),
rendered(3, 1200, 1200, false),
rendered(4, 1200, 1200, false),
rendered(5, 1200, 1200, false),
];
assert_eq!(
row_embeds(&list),
vec![vec![0, 1], vec![2], vec![3, 4], vec![5]]
);
let rows = rows_of(&list);
assert!((rows[3].x - 36.0).abs() < 1e-9);
assert!((rows[3].cell_w - 253.64).abs() < 1e-9);
}
#[test]
fn without_a_wide_view_the_grid_is_todays() {
let list: Vec<Rendered> = (0..5).map(|i| rendered(i, 1200, 1200, false)).collect();
assert_eq!(row_embeds(&list), vec![vec![0, 1], vec![2, 3], vec![4]]);
}
}