fix(render,table): share resolved MTEXT sizing inputs between table renderer and paste

This commit is contained in:
vantruong-dang
2026-11-30 11:55:54 +07:00
parent 465234b4f9
commit 19399e1ca8
3 changed files with 77 additions and 37 deletions
+50 -25
View File
@@ -85,7 +85,7 @@ 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<String>], text_height: Option<f64>) -> Table {
fn build_table(doc: &cadcraft_doc::Drawing, st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> 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 });
// Why: `cadcraft_render::table::layout` scales the resolved `Data` cell style's text height
@@ -123,12 +123,11 @@ fn build_table(st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Opt
if cell.text.is_empty() {
continue;
}
// Why: size each row to the exact wrapped line count from `layout_mtext_with` (without an
// arbitrary line cap, as input size is already bounded by `MAX_TSV_BYTES`/`MAX_PASTE_CELLS`)
// so cells wrapping past 50 lines match the renderer and do not spill into the next row.
// 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_fonts::MTextParams { width: wrap_w, ..cadcraft_fonts::MTextParams::new(Vec2::ZERO, cell_th) };
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);
}
@@ -164,7 +163,7 @@ pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result<Value> {
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 }))
@@ -229,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 }))
}
@@ -356,29 +363,49 @@ mod tests {
let EntityKind::Table(t_base) = &base.doc().unwrap().entity(h_base).unwrap().kind else { panic!("expected table") };
let mut custom = Session::new();
custom.doc_mut().unwrap().table_styles.iter_mut().find(|ts| ts.name.eq_ignore_ascii_case("Standard")).unwrap().set_cell_style(CellStyle {
name: CellStyle::DATA.into(),
text_height: 5.0,
margin_h: 4.0,
margin_v: 3.0,
..CellStyle::default()
});
{
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 EntityKind::Table(t_custom) = &custom.doc().unwrap().entity(h_custom).unwrap().kind else { panic!("expected table") };
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(custom.doc().unwrap(), t_custom);
let g = cadcraft_render::table_geometry(doc, t_custom);
let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap();
let laid = cadcraft_fonts::layout_mtext_with(
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 { width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(Vec2::ZERO, tx.height) },
&cadcraft_fonts::MTextParams { attach: tx.attach, width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) },
);
assert!(laid.lines.len() > 1);
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]
@@ -387,14 +414,12 @@ mod tests {
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 EntityKind::Table(t) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("expected table") };
let doc = s.doc().unwrap();
let EntityKind::Table(t) = &doc.entity(h).unwrap().kind else { panic!("expected table") };
let g = cadcraft_render::table_geometry(s.doc().unwrap(), t);
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_fonts::layout_mtext_with(
&tx.text,
&cadcraft_fonts::MTextParams { width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(Vec2::ZERO, tx.height) },
);
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);
+4 -1
View File
@@ -422,7 +422,10 @@ fn image_clip(i: &cadcraft_doc::Image, place: impl Fn(Vec2) -> Vec2) -> Option<V
}
mod table;
pub use table::{MAX_LAYOUT_CELLS, TableFill, TableGeom, TableLine, TableText, table_covered, table_geometry, table_style_of};
pub use table::{
MAX_LAYOUT_CELLS, TableFill, TableGeom, TableLine, TableText, layout_table_text, table_covered, table_geometry, table_style_of,
table_text_mtext_params,
};
mod blocks;
mod dim_draw;
+23 -11
View File
@@ -392,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);
@@ -413,19 +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,
width: tx.wrap_width,
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);
}