diff --git a/crates/layout/src/boxes.rs b/crates/layout/src/boxes.rs index 9f3b589859..bd51035e8c 100644 --- a/crates/layout/src/boxes.rs +++ b/crates/layout/src/boxes.rs @@ -157,7 +157,7 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool { { return false; } - let layout = table::layout_table(ctx, story, t, path, width, depth + 1); + let layout = table::layout_table(ctx, story, t, path, width, depth + 1, table::TURNED_MAX); let (tx, ty) = match t.props.float { Some(float) => { let legacy = (ctx.doc.settings.compat_mode < 15).then(|| table::first_cell_left_margin(ctx, t)); diff --git a/crates/layout/src/table.rs b/crates/layout/src/table.rs index 64da7285fe..b6257780cf 100644 --- a/crates/layout/src/table.rs +++ b/crates/layout/src/table.rs @@ -68,7 +68,7 @@ const DEFAULT_MARGINS: [f32; 4] = [0.0, 5.4, 0.0, 5.4]; /// The longest line turned text gets when its row height isn't exact (a Letter page's body /// height): longer text wraps. -const TURNED_MAX: f32 = 648.0; +pub(crate) const TURNED_MAX: f32 = 648.0; /// The longest line turned text ever gets (Word's largest page, 22 inches). const TURNED_LIMIT: f32 = 1584.0; @@ -614,7 +614,7 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option TableFrame { ncols, colx, acc, total, margins_def, tborders, rtl, x } } -pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize) -> TableLayout { +pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], avail: f32, depth: usize, align_room: f32) -> TableLayout { let style = table_style(ctx, t); // Cell text formatting and looks per set of style parts, built once per table. let mut cell_text: Vec<(Region, CellText)> = Vec::new(); @@ -794,7 +794,7 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava rows.push(cells); } grow_vertical_merges(&rows, &mut heights); - finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total }) + finish_table_rows(ctx, TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, align_room }) } fn grow_vertical_merges(rows: &[Vec], heights: &mut [f32]) { @@ -829,13 +829,14 @@ struct TableRows<'a> { edges: Vec, x: f32, total: f32, + align_room: f32, } /// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell /// rectangles, clipped where the row's exact height or a fixed table's column is too small for /// the cell's text. fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { - let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total } = input; + let TableRows { story, table: t, path, depth, cell_text, rows, heights, bottoms, edges, x, total, align_room } = input; // Grid columns holding a vertical-merge continuation, per row. let cont: Vec> = t .rows @@ -854,6 +855,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { .collect(); // Second pass: place cells with their row height, fills and borders. let mut out = Vec::with_capacity(rows.len()); + let mut row_top = 0.0; for (ri, cells) in rows.into_iter().enumerate() { let rh = heights.get(ri).copied().unwrap_or(0.0); let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)); @@ -895,10 +897,13 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { _ => None, }) .fold(c.h, f32::max); + // A merged cell's text is drawn with its restart row, even when the merge spans + // later pages. Only the remaining body height on that first page can align it. + let align_span = if c.vmerge == VMerge::Restart { span_h.min((align_room - row_top).max(0.0)) } else { span_h }; let mut dy = match c.valign { VAlign::Top => 0.0, - VAlign::Center => ((span_h - align_h) / 2.0).max(0.0), - VAlign::Bottom => (span_h - align_h).max(0.0), + VAlign::Center => ((align_span - align_h) / 2.0).max(0.0), + VAlign::Bottom => (align_span - align_h).max(0.0), }; let end = (c.vmerge != VMerge::Continue && c.turned.is_none()).then_some(c.end + dy); let mut cell_items = c.items; @@ -906,7 +911,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { dy = 0.0; let m = c.margins; // The lines run the cell's whole height (laid out again if the row grew). - let len = (span_h - (c.h - tn.len)).clamp(4.0, TURNED_LIMIT); + let len = (align_span - (c.h - tn.len)).clamp(4.0, align_span.clamp(4.0, TURNED_LIMIT)); let mut across = tn.across; if (len - tn.len).abs() > 0.01 && let Some(cell) = t.rows.get(ri).and_then(|r| r.cells.get(tn.ci)) @@ -983,6 +988,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout { edge: edges.get(ri).copied().unwrap_or(0.0), cells: parts, }); + row_top += rh; } TableLayout { x, width: total, rows: out } } diff --git a/crates/layout/src/table_flow.rs b/crates/layout/src/table_flow.rs index 3748fa778f..504f71e182 100644 --- a/crates/layout/src/table_flow.rs +++ b/crates/layout/src/table_flow.rs @@ -76,7 +76,7 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec f32 { // A look ahead: list and equation numbers in the cells don't count yet. let (counters, eq_count) = (ctx.counters.clone(), ctx.eq_count); - let tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1); + let tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1, table::TURNED_MAX); (ctx.counters, ctx.eq_count) = (counters, eq_count); let headers = t.rows.iter().take_while(|r| r.props.header).count(); let head: f32 = tl.rows.iter().take(headers).map(|r| r.height).sum(); @@ -198,7 +198,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc ctx.fields.page = pb.number; } let width = pb.col_w(); - let mut tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1); + let mut tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1, (pb.bottom - pb.y).max(0.0)); if let Some(f) = t.props.float.filter(|_| !pb.web) { // Before Word 2013 layout (compatibility mode 15) an offset places the first cell's text, // so the edge sits a cell margin further out. diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index e663ebdfcc..391c97f9b4 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -3211,7 +3211,90 @@ fn a_vertical_merge_lays_out_as_one_cell() { assert_eq!((hit.2, hit.3), (0, 0)); } +#[test] +fn a_vertical_merge_aligns_its_text_with_the_first_page() { + crate::test_fonts(); + use wordcraft_doc::props::{HeightRule, VAlign, VMerge}; + let mut d = Document::new(); + let mut t = Table::new(60, 2, 468.0); + for (i, row) in t.rows.iter_mut().enumerate() { + row.props.height = Some(40.0); + row.props.height_rule = HeightRule::Exact; + row.cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("row", Default::default()))]; + row.cells[0].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text(if i == 0 { "MERGED LABEL" } else { "" }, Default::default()))]; + row.cells[0].props.vmerge = if i == 0 { VMerge::Restart } else { VMerge::Continue }; + } + t.rows[0].cells[0].props.valign = Some(VAlign::Center); + d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let label = l.pages[0].items.iter().find_map(|item| match item { + Placed::Lines { path, para, l0, l1, y, .. } if path.0 == [1, 0, 0, 0] => Some((*y, para.lines[*l1 - 1].top + para.lines[*l1 - 1].height)), + _ => None, + }); + assert!(label.is_some_and(|(y, _)| y >= l.pages[0].body.y && y <= l.pages[0].body.bottom()), "{label:?}, body {:?}", l.pages[0].body); +} + /// A 1×3 table after "before" whose middle cell holds `text` running `dir`. +#[test] +fn a_vertical_merge_keeps_center_bottom_and_turned_text_in_first_page_body() { + crate::test_fonts(); + use wordcraft_doc::props::{HeightRule, VAlign, VMerge}; + for valign in [VAlign::Center, VAlign::Bottom] { + for direction in [TextDirection::Horizontal, TextDirection::Up] { + let mut d = Document::from_text("before"); + let mut t = Table::new(60, 2, 468.0); + for (i, row) in t.rows.iter_mut().enumerate() { + row.props.height = Some(40.0); + row.props.height_rule = HeightRule::Exact; + row.cells[1].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("row", Default::default()))]; + row.cells[0].blocks = + vec![wordcraft_doc::para_block(Paragraph::with_text(if i == 0 { "MERGED LABEL" } else { "" }, Default::default()))]; + row.cells[0].props.vmerge = if i == 0 { VMerge::Restart } else { VMerge::Continue }; + } + t.rows[0].cells[0].props.valign = Some(valign); + t.rows[0].cells[0].props.text_direction = direction; + d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap(); + let l = lay(&d); + let body = l.pages[0].body; + let restart_top = l.pages[0] + .items + .iter() + .find_map(|item| match item { + Placed::Cell { rect, row: 0, cell: 0, .. } => Some(rect.y), + _ => None, + }) + .unwrap(); + let item = l.pages[0].items.iter().find(|item| matches!(item, Placed::Lines { path, .. } if path.0 == [1, 0, 0, 0])); + assert!( + item.is_some(), + "{valign:?} {direction:?}: label is missing from the first page: {:?}", + l.pages[0] + .items + .iter() + .filter_map(|i| if let Placed::Lines { path, .. } = i { Some(path.0.clone()) } else { None }) + .collect::>() + ); + if direction.is_turned() { + let bounds = item.and_then(Placed::turned_bounds).unwrap(); + assert!(bounds.y >= restart_top && bounds.bottom() <= body.bottom(), "{valign:?} {direction:?}: {bounds:?}, body {body:?}"); + } else { + let Some(Placed::Lines { para, l0, l1, y: top, .. }) = item else { + continue; + }; + let bottom = para.lines[*l1 - 1].top + para.lines[*l1 - 1].height; + let height = para.lines[*l0].height; + assert!(*top >= body.y && bottom <= body.bottom(), "{valign:?} {direction:?}: {top}..{bottom}, body {body:?}"); + let expected = match valign { + VAlign::Center => restart_top + (body.bottom() - restart_top - height) / 2.0, + VAlign::Bottom => body.bottom() - height, + VAlign::Top => restart_top, + }; + assert!((*top - expected).abs() < 1.0, "{valign:?} {direction:?}: top {top}, expected {expected}, body {body:?}"); + } + } + } +} + fn turned_table(dir: TextDirection, text: &str, row: Option) -> Document { let mut d = Document::from_text("before\nafter"); let mut t = Table::new(1, 3, 468.0);