diff --git a/crates/engine/src/cmd/table/paste.rs b/crates/engine/src/cmd/table/paste.rs index 746d2c0ca..24b8f33d7 100644 --- a/crates/engine/src/cmd/table/paste.rs +++ b/crates/engine/src/cmd/table/paste.rs @@ -1,6 +1,6 @@ //! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`. -use cadcraft_doc::{EntityKind, Table, TableCell, TableStyle}; +use cadcraft_doc::{CellStyle, EntityKind, Table, TableCell, TableStyle}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; @@ -85,33 +85,54 @@ pub fn is_tsv_table(text: &str) -> bool { } /// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly. -fn build_table(st: &TableStyle, at: Vec2, data: &[Vec], text_height: Option) -> Table { +fn build_table(doc: &cadcraft_doc::Drawing, st: &TableStyle, at: Vec2, data: &[Vec], text_height: Option) -> Table { let cols = data.first().map_or(1, Vec::len).max(1); let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 }); - let margin = if st.text_height.is_finite() && st.text_height > 0.0 { st.margin * (th / st.text_height) } else { th * 0.5 }; + // Why: `cadcraft_render::table::layout` scales the resolved `Data` cell style's text height + // and horizontal/vertical margins by `th / st.text_height`, so sizing widths, wrap width, and + // row heights with the same scaled `Data` metrics keeps wrapped text inside custom-styled cells. + let scale = if st.text_height.is_finite() && st.text_height > 0.0 { th / st.text_height } else { 1.0 }; + let data_cs = st.cell_style(CellStyle::DATA); + let cell_th = Some(data_cs.text_height * scale).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(th); + let margin_h = Some(data_cs.margin_h * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5); + let margin_v = Some(data_cs.margin_v * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5); let mut col_chars = vec![1usize; cols]; - let mut row_heights = Vec::with_capacity(data.len()); let mut cells = Vec::with_capacity(data.len()); for row in data { - let mut max_lines = 1usize; let mut table_row = Vec::with_capacity(cols); for (c, raw) in row.iter().enumerate() { - let line_count = raw.split('\n').count().clamp(1, 50); - max_lines = max_lines.max(line_count); let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60); if let Some(slot) = col_chars.get_mut(c) { *slot = (*slot).max(max_chars); } table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() }); } - row_heights.push(th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin); cells.push(table_row); } - let min_col_w = (th * 4.0 + 2.0 * margin).max(th * 5.0); - let col_widths: Vec = col_chars.into_iter().map(|chars| (0.75 * th * chars as f64 + 2.0 * margin + 0.5 * th).max(min_col_w)).collect(); + let min_col_w = (cell_th * 4.0 + 2.0 * margin_h).max(cell_th * 5.0); + let col_widths: Vec = + col_chars.into_iter().map(|chars| (0.95 * cell_th * chars as f64 + 2.0 * margin_h + 0.5 * cell_th).max(min_col_w)).collect(); + + let mut row_heights = Vec::with_capacity(cells.len()); + for row in &cells { + let mut max_lines = 1usize; + for (c, cell) in row.iter().enumerate() { + if cell.text.is_empty() { + continue; + } + // Why: share the renderer's resolved MTEXT sizing inputs (named font, width_factor, + // oblique) so pasted row heights match how `cadcraft_render::table::draw` wraps cells. + let inner_w = col_widths.get(c).copied().unwrap_or(0.0) - 2.0 * margin_h; + let wrap_w = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 }; + let mp = cadcraft_render::table_text_mtext_params(doc, &data_cs.text_style, Vec2::ZERO, cell_th, data_cs.align.clamp(1, 9), wrap_w); + let line_count = cadcraft_fonts::layout_mtext_with(&cell.text, &mp).lines.len().max(1); + max_lines = max_lines.max(line_count); + } + row_heights.push(cell_th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin_v); + } Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() } } @@ -142,7 +163,7 @@ pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result { let rows = data.len(); let cols = data.first().map_or(0, Vec::len); let st = style_of(s); - let table = build_table(&st, at, &data, th); + let table = build_table(s.doc()?, &st, at, &data, th); let h = s.add_entity(EntityKind::Table(table))?; s.set_selection(vec![h]); Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols })) @@ -207,7 +228,15 @@ impl Session { let rows = data.len(); let cols = data.first().map_or(0, Vec::len); let st = style_of(self); - let table = build_table(&st, Vec2::ZERO, &data, text_height); + let fallback; + let doc = match self.doc() { + Ok(d) => d, + Err(_) => { + fallback = cadcraft_doc::Drawing::default(); + &fallback + } + }; + let table = build_table(doc, &st, Vec2::ZERO, &data, text_height); let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled); self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols })) } @@ -301,4 +330,101 @@ mod tests { assert_eq!(s.commands_started, before_started + 1); assert_eq!(s.last_command.as_deref(), Some("pastetable")); } + + #[test] + fn long_wrapped_cells_cap_col_width_and_grow_row_height() { + let mut s = Session::new(); + let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega"; + assert!(long_cell.chars().count() > 60); + let tsv = format!("Short\t{long_cell}\n\"First line\n{long_cell}\"\t\nA\tB",); + let res = s.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0], "text_height": 2.0 })).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap(); + let e = s.doc().unwrap().entity(h).unwrap(); + let EntityKind::Table(t) = &e.kind else { panic!("expected table") }; + + // Column 1 width is capped at 60 characters rather than growing unboundedly. + let st = style_of(&s); + let expected_cap_w = 0.95 * 2.0 * 60.0 + 2.0 * (st.margin * (2.0 / st.text_height)) + 0.5 * 2.0; + assert!((t.col_widths[1] - expected_cap_w).abs() < 1e-9); + // Row 0 wraps into multiple lines and is taller than single-line Row 2. + assert!(t.row_heights[0] > t.row_heights[2]); + // Row 1 combines a hard newline and a long wrapped line, making it taller than Row 0. + assert!(t.row_heights[1] > t.row_heights[0]); + } + + #[test] + fn custom_data_cell_style_sizes_wrapped_rows_and_columns() { + let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega"; + let tsv = format!("Short\t{long_cell}\nA\tB"); + + let mut base = Session::new(); + let r_base = base.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap(); + let h_base = cadcraft_doc::Handle::parse_hex(r_base["handle"].as_str().unwrap()).unwrap(); + let EntityKind::Table(t_base) = &base.doc().unwrap().entity(h_base).unwrap().kind else { panic!("expected table") }; + + let mut custom = Session::new(); + { + let doc = custom.doc_mut().unwrap(); + doc.text_styles.push(cadcraft_doc::TextStyle { name: "WideNotes".into(), width_factor: 1.8, ..cadcraft_doc::TextStyle::default() }); + doc.table_styles.iter_mut().find(|ts| ts.name.eq_ignore_ascii_case("Standard")).unwrap().set_cell_style(CellStyle { + name: CellStyle::DATA.into(), + text_style: "WideNotes".into(), + text_height: 5.0, + margin_h: 4.0, + margin_v: 3.0, + ..CellStyle::default() + }); + } + let r_custom = custom.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap(); + let h_custom = cadcraft_doc::Handle::parse_hex(r_custom["handle"].as_str().unwrap()).unwrap(); + let doc = custom.doc().unwrap(); + let EntityKind::Table(t_custom) = &doc.entity(h_custom).unwrap().kind else { panic!("expected table") }; + + assert!(t_custom.col_widths[1] > t_base.col_widths[1]); + assert!(t_custom.row_heights[0] > t_base.row_heights[0]); + assert!(t_custom.row_heights[0] > t_custom.row_heights[1]); + + let g = cadcraft_render::table_geometry(doc, t_custom); + let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap(); + assert_eq!(tx.style, "WideNotes"); + let laid = cadcraft_render::layout_table_text(doc, tx); + let default_laid = cadcraft_fonts::layout_mtext_with( + &tx.text, + &cadcraft_fonts::MTextParams { attach: tx.attach, width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) }, + ); + assert!(laid.lines.len() > default_laid.lines.len(), "wider text style must wrap into more lines"); + assert!(t_custom.row_heights[0] >= laid.lines.len() as f64 * tx.height * 5.0 / 3.0 + 2.0 * 3.0 - 1e-6); + assert!(!laid.strokes.is_empty()); + for s in &laid.strokes { + for p in s { + assert!( + p.y <= t_custom.insert.y + 1e-6 && p.y >= t_custom.insert.y - t_custom.row_heights[0] - 1e-6, + "rendered stroke spilled outside row 0 [{}..={}]: y={}", + t_custom.insert.y - t_custom.row_heights[0], + t_custom.insert.y, + p.y + ); + } + } + } + + #[test] + fn cell_wrapping_past_fifty_lines_is_not_clamped() { + let mut s = Session::new(); + let long_cell = vec!["word"; 800].join(" "); + let res = s.execute("pastetable", &json!({ "tsv": format!("A\t{long_cell}\n1\t2"), "at": [0, 0], "text_height": 2.0 })).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap(); + let doc = s.doc().unwrap(); + let EntityKind::Table(t) = &doc.entity(h).unwrap().kind else { panic!("expected table") }; + + let g = cadcraft_render::table_geometry(doc, t); + let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap(); + let laid = cadcraft_render::layout_table_text(doc, tx); + assert!(laid.lines.len() > 50, "expected >50 wrapped lines, got {}", laid.lines.len()); + let st = style_of(&s); + let margin_v = st.margin * (2.0 / st.text_height); + let fifty_line_h = 2.0 * (50.0 * 5.0 / 3.0) + 2.0 * margin_v; + assert!(t.row_heights[0] > fifty_line_h); + assert!((t.row_heights[0] - (2.0 * (laid.lines.len() as f64 * 5.0 / 3.0) + 2.0 * margin_v)).abs() < 1e-9); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 9b8a2d77c..4b2e0a7ba 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -481,7 +481,10 @@ fn image_clip(i: &cadcraft_doc::Image, place: impl Fn(Vec2) -> Vec2) -> Option TableGeom { 1 => (y0 + y1) / 2.0, _ => y1 - cs.margin_v, }; + // Why: wrap cell text inside the cell's horizontal bounds (excluding margins) so long lines + // do not spill into adjacent columns; clamp non-finite or narrow spans to 0 (no wrap). + let inner_w = x1 - x0 - 2.0 * cs.margin_h; + let wrap_width = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 }; g.texts.push(TableText { row: a.row, col: a.col, at: p(x, y), attach, height: cell.text_height.filter(|h| h.is_finite() && *h > 0.0).map_or(cs.text_height, |h| h * k), + wrap_width, color: cs.text_color, style: cs.text_style.clone(), text: cell.text.clone(), @@ -385,6 +392,28 @@ fn style_ink(c: Color, table: Ink) -> Ink { } } +/// Resolve the [`cadcraft_fonts::MTextParams`] the renderer uses for a table cell's text style, +/// alignment point, text height, attachment, and horizontal wrap width. +pub fn table_text_mtext_params(d: &Drawing, style: &str, at: Vec2, height: f64, attach: u8, wrap_width: f64) -> cadcraft_fonts::MTextParams { + let ts = crate::text_style(d, style); + let font = crate::style_font(&ts); + cadcraft_fonts::MTextParams { + attach, + width: wrap_width, + font, + width_factor: ts.width_factor, + oblique: ts.oblique, + ..cadcraft_fonts::MTextParams::new(at, height) + } +} + +/// Lay out a [`TableText`] with the exact resolved text style, font, width factor, and oblique +/// angle used when drawing the table. +pub fn layout_table_text(d: &Drawing, tx: &TableText) -> cadcraft_fonts::MTextLayout { + let mp = table_text_mtext_params(d, &tx.style, tx.at, tx.height, tx.attach, tx.wrap_width); + cadcraft_fonts::layout_mtext_with(&tx.text, &mp) +} + /// Draw a table into the display list. pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { let g = table_geometry(ctx.d, t); @@ -406,18 +435,9 @@ pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { return; } for tx in &g.texts { - let ts = crate::text_style(ctx.d, &tx.style); - let font = crate::style_font(&ts); // Cell content is MTEXT (`\P`, `{\Q15;…}`, `\F…;`): laid out as such, at the cell's // alignment point (its numbering is MTEXT's attachment). - let mp = cadcraft_fonts::MTextParams { - attach: tx.attach, - font, - width_factor: ts.width_factor, - oblique: ts.oblique, - ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) - }; - let layout = cadcraft_fonts::layout_mtext_with(&tx.text, &mp); + let layout = layout_table_text(ctx.d, tx); for piece in &layout.pieces { b.shaped(ctx, style_ink(tx.color, rgb), lw, &piece.shaped); } @@ -458,4 +478,77 @@ mod budget_tests { let part = part_table(&t, &rows, Vec2::ZERO); assert_eq!(part.cells[0][0].merged, Some((99, 1))); } + + #[test] + fn cell_text_wraps_within_column_and_merged_bounds() { + let mut d = Drawing::default(); + let long_text = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu"; + let t = Table { + col_widths: vec![30.0, 20.0], + row_heights: vec![40.0, 40.0], + text_height: 2.5, + cells: vec![ + vec![TableCell { text: long_text.into(), ..Default::default() }, TableCell { text: "B".into(), ..Default::default() }], + vec![TableCell { text: long_text.into(), merged: Some((1, 2)), ..Default::default() }, TableCell::default()], + ], + ..Default::default() + }; + let g = table_geometry(&d, &t); + assert!(g.texts[0].wrap_width > 0.0 && g.texts[0].wrap_width < 30.0); + // Merged cell spans both columns (50.0 total), so its wrap width exceeds a single column. + assert!(g.texts[2].wrap_width > g.texts[0].wrap_width); + + // Render via `crate::build` and verify all stroke vertices of cell (0,0) stay inside column 0 [0, 30]. + d.model.push(cadcraft_doc::Entity::new( + cadcraft_doc::Handle(1), + cadcraft_doc::EntityKind::Table(Table { + col_widths: vec![30.0, 20.0], + row_heights: vec![40.0], + text_height: 2.5, + cells: vec![vec![TableCell { text: long_text.into(), ..Default::default() }, TableCell::default()]], + ..Default::default() + }), + )); + let list = crate::build(&d, &cadcraft_doc::Space::Model, &crate::Options::default()); + assert!(!list.verts.is_empty()); + for p in &list.verts { + assert!(p.x >= -1e-6 && p.x <= 50.0 + 1e-6, "vertex outside table: {p:?}"); + } + // Verify layout_mtext_with at tx.wrap_width wraps into multiple lines and stays inside column 0 [0, 30]. + let mp = cadcraft_fonts::MTextParams { + attach: g.texts[0].attach, + width: g.texts[0].wrap_width, + ..cadcraft_fonts::MTextParams::new(g.texts[0].at, g.texts[0].height) + }; + let laid = cadcraft_fonts::layout_mtext_with(&g.texts[0].text, &mp); + assert!(laid.lines.len() > 1); + for s in &laid.strokes { + for p in s { + assert!(p.x >= -1e-6 && p.x <= 30.0 + 1e-6, "glyph spilled past column 0: {p:?}"); + } + } + } + + #[test] + fn narrow_or_non_finite_columns_and_escapes_do_not_panic() { + let mut d = Drawing::default(); + let t = Table { + col_widths: vec![0.1, f64::NAN, 40.0], + row_heights: vec![10.0], + cells: vec![vec![ + TableCell { text: "Narrow".into(), ..Default::default() }, + TableCell { text: "NaN".into(), ..Default::default() }, + TableCell { text: "Line1\\PLine2\\\\{brace}".into(), ..Default::default() }, + ]], + ..Default::default() + }; + let g = table_geometry(&d, &t); + assert_eq!(g.texts[0].wrap_width, 0.0); + assert_eq!(g.texts[1].wrap_width, 0.0); + assert!(g.texts[2].wrap_width > 0.0); + + d.model.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), cadcraft_doc::EntityKind::Table(t))); + let list = crate::build(&d, &cadcraft_doc::Space::Model, &crate::Options::default()); + assert!(!list.verts.is_empty()); + } }