Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge main into M8 tables

Brandon Thomas7a7d7b78a149
diff --cc ROADMAP.md
index 4a03a27c0,e9e374a28..6709397de
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -11,15 -11,16 +11,17 @@@ DesignCraft aims at full Adobe InDesig
- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts, document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document dialog, ⌘K palette, 4 brightness themes.
- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark).
- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.
- - Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection (basic), Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.
- PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`.
- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).
+- Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; `table.*` commands.
- - ~100 commands, all reachable through the JSON control channel; headless CLI rendering to PNG.
+ - Hyperlinks (text or frames → URL / e-mail / page) and bookmarks, exported as PDF link annotations and outline.
+ - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).
+ - Data Merge (CSV or JSON rows, `<<Field>>` placeholders), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.
+ - ~170 commands, all reachable through the JSON control channel; headless CLI rendering to PNG.
- MCP server (`designcraft-cli mcp [--connect PORT]`, docs/mcp.md): headless engine or the running app; commands, batch, document/story inspection, page renders as images, window screenshots, pointer/keyboard/dialog input.
- Web build (`apps/designcraft-web`, trunk): the same UI on WebGPU with a WebGL2 fallback; open/place via the browser file picker or drag-and-drop, save/export as downloads.
- **Next (in order):** table styles / cell styles, text rotation in cells · TOC/index/footnotes · PDF/X-4 output intent, bookmarks, tagged PDF · Links panel + relink · EPUB · column-break / default-tab fixes.
-**Next (in order):** tables · TOC, text variables, footnotes · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks.
++**Next (in order):** table/cell styles, text rotation in cells · TOC, text variables, footnotes · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks.
## Milestones
@@@ -32,11 -33,11 +34,11 @@@
| M4 | Color & effects | started |
| M5 | Graphics & links | started |
| M6 | Files & export (native, IDML, PDF, PNG/JPEG) | in progress (IDML ✅, PDF export) |
- | M7 | Long documents (sections, TOC, index, footnotes, books) | |
- | M8 | Tables | ✅ core (styles, rotation, diagonal lines pending) |
+ | M7 | Long documents (sections, TOC, index, footnotes, books) | started (sections, hyperlinks, bookmarks) |
-| M8 | Tables | |
++| M8 | Tables | ✅ core (table/cell styles, rotation, diagonal lines pending) |
| M9 | Performance (MT composition, tiles) | |
- | M10 | Find/Change, spelling, Preflight | |
- | M11 | Layout power features (liquid/alternate layouts, data merge) | |
- | M12 | Interactive & digital (EPUB, HTML, interactive PDF) | |
+ | M10 | Find/Change, spelling, Preflight | in progress (Find/Change ✅, spelling ✅, Preflight) |
+ | M11 | Layout power features (liquid/alternate layouts, data merge) | started (data merge, step & repeat, snippets) |
+ | M12 | Interactive & digital (EPUB, HTML, interactive PDF) | started (EPUB, PDF links/bookmarks) |
| M13 | Automation (scripts, batch) | |
| M14 | 1.0 polish & packaging | |
diff --cc crates/compose/src/lib.rs
index a492b5926,2d32f955e..00a3be01e
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -1153,10 -1156,9 +1201,10 @@@ fn place(g: &Glyph, x: f64) -> PlacedGl
|| breaker::is_forced(g.ch)
|| g.ch == story::INDENT_HERE
|| g.ch == story::RIGHT_INDENT_TAB
+ || g.ch == story::TABLE_ANCHOR
|| g.ch == shape::SOFT_HYPHEN);
PlacedGlyph {
- face: g.face.clone(),
+ face: g.face,
gid: g.gid,
x: x + g.dx,
y: -g.shift + g.dy,
diff --cc crates/compose/src/tests.rs
index 848806f98,3db8ebf94..73bd778a4
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -570,144 -570,24 +570,166 @@@ fn tabs_without_stops_use_default_half_
assert!((b.x - 36.0).abs() < 0.5, "B at {}", b.x);
}
+// ---------- tables ----------
+
+fn table_doc(frame: Rect, t: designcraft_doc::Table) -> (Document, StoryId, ItemId) {
+ let (mut d, sid, fid) = doc_with("Intro", frame, ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ let end = st.len();
+ st.insert_table(end, t);
+ let end = st.len();
+ st.insert(end, "After");
+ d.check().unwrap();
+ (d, sid, fid)
+}
+
+fn filled(rows: usize, cols: usize, header: usize, width: f64) -> designcraft_doc::Table {
+ let mut t = designcraft_doc::Table::new(77, rows, cols, header, 0, width);
+ for r in 0..t.nrows() {
+ for c in 0..t.ncols() {
+ t.cell_mut(r, c).unwrap().text.insert(0, &format!("R{r}C{c}"));
+ }
+ }
+ t
+}
+
+#[test]
+fn table_rows_fit_their_content() {
+ let mut t = filled(3, 3, 1, 300.0);
+ t.cell_mut(2, 1).unwrap().text.insert(0, &format!("{LOREM} "));
+ t.rows[3].height = 50.0;
+ t.rows[3].mode = designcraft_doc::RowHeightMode::Exactly;
+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 1000.0), t);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ assert_eq!(ft.tables.len(), 1);
+ let tf = &ft.tables[0];
+ assert_eq!(tf.cells.len(), 12);
+ let h = |r: usize| tf.cell(r, 0).unwrap().rect.height();
+ // One line of 12 pt text + 4 + 4 insets.
+ assert!(h(0) > 12.0 && h(0) < 25.0, "{}", h(0));
+ // The long cell makes its row taller; all cells in a row share the height.
+ assert!(h(2) > 5.0 * h(0), "{} vs {}", h(2), h(0));
+ assert!((tf.cell(2, 2).unwrap().rect.height() - h(2)).abs() < 1e-9);
+ assert!((h(3) - 50.0).abs() < 1e-9);
+ // Cell text sits inside the cell insets.
+ let c = tf.cell(1, 1).unwrap();
+ let l = &c.text.frames[0].lines[0];
+ assert!(c.origin.x + l.x0 >= c.rect.x0 + 3.99);
+ assert!(c.origin.y + l.baseline < c.rect.y1);
+ // Text after the table is below it.
+ let len = d.story(sid).unwrap().len();
+ let after = ft.lines.iter().find(|l| l.range.start == len - 5).unwrap();
+ assert!(after.baseline > tf.rect.y1);
+ // Strokes: outer border + inner edges.
+ assert!(tf.strokes.len() >= 4 * 3 + 4);
+}
+
+#[test]
+fn table_columns_scale_to_the_text_column() {
+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 200.0, 1000.0), filled(2, 4, 0, 600.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let tf = &cs.frames[0].tables[0];
+ assert!((tf.rect.width() - 200.0).abs() < 1e-6, "{}", tf.rect.width());
+ assert!((tf.cell(0, 3).unwrap().rect.x1 - 200.0).abs() < 1e-6);
+ // A narrow table keeps its widths.
+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 1000.0), filled(2, 2, 0, 100.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!((cs.frames[0].tables[0].rect.width() - 100.0).abs() < 1e-6);
+}
+
+#[test]
+fn table_rows_break_across_frames_with_header_repeat() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (f1, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 150.0), lid, "", ParaFormat::default()).unwrap();
+ let (f2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 200.0, 300.0, 350.0), lid, "", ParaFormat::default()).unwrap();
+ d.thread(f1, f2).unwrap();
+ d.story_mut(sid).unwrap().insert_table(0, filled(9, 2, 1, 300.0));
+ d.check().unwrap();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset(), "overset at {:?}", cs.overset_at);
+ let (a, b) = (&cs.frames[0].tables, &cs.frames[1].tables);
+ assert_eq!((a.len(), b.len()), (1, 1));
+ // Every body row appears exactly once; the header is repeated in the second frame.
+ let body: Vec<usize> = a[0].cells.iter().chain(b[0].cells.iter()).filter(|c| c.row > 0 && c.col == 0).map(|c| c.row).collect();
+ assert_eq!(body, (1..10).collect::<Vec<_>>());
+ assert!(!a[0].cell(0, 0).unwrap().repeated);
+ assert!(b[0].cell(0, 0).unwrap().repeated);
+ assert!((b[0].rect.y0 - 200.0).abs() < 1e-6, "{}", b[0].rect.y0);
+ assert!(a[0].rect.y1 <= 150.0 + 1e-6);
+ assert!(a[0].first && !a[0].last && b[0].last);
+ // Without header repeat the second fragment starts with a body row.
+ let st = d.story_mut(sid).unwrap();
+ st.table_mut(77).unwrap().options.repeat_header = false;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.frames[1].tables[0].cell(0, 0).is_none());
+ // Too little room: overset.
+ let st = d.story_mut(sid).unwrap();
+ let t = st.table_mut(77).unwrap();
+ t.insert_rows(5, 30);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.is_overset());
+}
+
+#[test]
+fn table_cells_hit_test_and_place_carets() {
+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 300.0, 1000.0), filled(2, 3, 0, 300.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let c = cs.frames[0].tables[0].cell(1, 2).unwrap().clone();
+ let p = Point::new(c.rect.x1 - 2.0, c.rect.center().y);
+ let (t, r, col, b) = hit_cell(&cs, 0, p).unwrap();
+ assert_eq!((t, r, col), (77, 1, 2));
+ assert_eq!(b, "R1C2".len());
+ let (fi, x, bl, _, _) = cell_caret(&cs, 77, 1, 2, 0).unwrap();
+ assert_eq!(fi, 0);
+ assert!(c.rect.contains(Point::new(x + 0.1, bl - 1.0)));
+ // Outside every cell: no cell.
+ assert!(hit_cell(&cs, 0, Point::new(1.0, 1.0)).is_none());
+ // The anchor has a caret position (after the table).
+ let a = d.story(sid).unwrap().table_anchor(77).unwrap();
+ assert!(caret(&cs, a).is_some());
+}
+
+#[test]
+fn table_fills_and_merged_cells() {
+ let mut t = filled(4, 3, 1, 300.0);
+ t.options.alt_rows = Some(designcraft_doc::AltFills { first: 1, next: 1, ..Default::default() });
+ t.cell_mut(0, 0).unwrap().fill = "[Black]".into();
+ t.merge(designcraft_doc::CellRange::new(1, 1, 2, 2)).unwrap();
+ let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 300.0, 1000.0), t);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let tf = &cs.frames[0].tables[0];
+ assert!(tf.cell(0, 0).unwrap().fill.is_some());
+ assert!(tf.cell(0, 1).unwrap().fill.is_none(), "header rows don't alternate");
+ assert!(tf.cell(1, 0).unwrap().fill.is_some());
+ assert!(tf.cell(2, 0).unwrap().fill.is_none());
+ let m = tf.cell(1, 1).unwrap();
+ let both = tf.cell(1, 0).unwrap().rect.height() + tf.cell(2, 0).unwrap().rect.height();
+ assert!((m.rect.height() - both).abs() < 1e-6);
+ assert!(tf.cell(2, 2).is_none());
+ assert_eq!(tf.cells.len(), 15 - 3);
+}
++
+ #[test]
+ fn tab_leaders_fill_the_gap() {
+ let mut doc = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());
+ let lid = doc.default_layer();
+ let pf = designcraft_doc::ParaFormat {
+ para: designcraft_doc::ParaAttrs {
+ tabs: Some(vec![designcraft_doc::TabStop { position: 200.0, align: TabAlign::Right, leader: ".".into(), align_on: String::new() }]),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let (_, sid) =
+ doc.add_text_frame(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Rect::new(0.0, 0.0, 300.0, 100.0), lid, "Intro\t12", pf).unwrap();
+ let cs = crate::compose_story(&doc, sid, &Default::default());
+ let line = &cs.frames[0].lines[0];
+ let dots: Vec<&crate::PlacedGlyph> = line.glyphs.iter().filter(|g| g.len == 0 && g.visible).collect();
+ assert!(dots.len() > 20, "{} leader glyphs", dots.len());
+ let last_dot = dots.iter().map(|g| g.x).fold(0.0, f64::max);
+ let num_x = line.glyphs.iter().find(|g| g.byte == 6).unwrap().x;
+ assert!(last_dot < num_x, "leaders stop before the page number");
+ }
diff --cc crates/engine/src/cmd/mod.rs
index efd5c8451,2584d0bcd..ec7a74537
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@@ -9,9 -11,10 +11,11 @@@ pub mod interchange
mod layout;
mod object;
pub mod preflight;
+ pub mod spelling;
mod style;
+pub mod table;
pub mod text;
+ mod toc;
use designcraft_doc::{ItemId, SpreadRef};
use designcraft_geom::{Point, Rect};
diff --cc crates/render/src/text.rs
index 000000000,5eccc8cf4..98f0b1005
mode 000000,100644..100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@@ -1,0 -1,264 +1,311 @@@
+ //! Composed text → pixels.
+ //!
+ //! Glyph outlines of a frame are transformed into frame space and batched per line and run style
+ //! once, then cached per (composed story allocation, frame id): a composed story is immutable, so
+ //! the cache entry stays valid for as long as the composition cache hands out the same `Arc`.
+ //! Each render only fills the lines that intersect the visible rectangle, and lines smaller than
+ //! the greeking threshold become grey bars without touching any outline.
+
+ use std::collections::HashMap;
+ use std::sync::Arc;
+
+ use designcraft_compose::{ComposedStory, FrameText, Line};
+ use designcraft_doc::ItemId;
+ use designcraft_fonts::FontDb;
+ use designcraft_geom::{Affine, BezPath, Rect, Shape};
+ use vello_cpu::RenderContext;
+ use vello_cpu::kurbo;
+ use vello_cpu::peniko;
+
+ use crate::{Frame, Renderer, color_of, rect_overlaps};
+
+ /// Cached outlines of one composed line.
+ pub(crate) struct LineGlyphs {
+ /// Frame-space bounds of everything drawn for the line (empty lines: `None`).
+ pub bounds: Option<Rect>,
+ /// Glyph outlines batched per run style.
+ pub runs: Vec<(u32, BezPath)>,
+ /// Underline / strikethrough bars.
+ pub decos: Vec<(u32, Rect)>,
+ pub glyphs: usize,
+ }
+
+ pub(crate) struct FrameGlyphs {
+ pub lines: Vec<LineGlyphs>,
+ /// Path elements held (cache budget).
+ pub elements: usize,
+ }
+
+ struct Entry {
+ /// Keeps the composed story alive so its address can't be reused while cached.
+ _story: Arc<ComposedStory>,
+ glyphs: Arc<FrameGlyphs>,
+ stamp: u64,
+ }
+
+ /// Path cache keyed by (composed story address, frame id).
+ #[derive(Default)]
+ pub(crate) struct GlyphCache {
+ map: HashMap<(usize, ItemId), Entry>,
+ elements: usize,
+ clock: u64,
+ }
+
+ /// Roughly 56 bytes per element: ~110 MB of cached outlines.
+ const MAX_ELEMENTS: usize = 2_000_000;
+
+ impl GlyphCache {
+ pub fn tick(&mut self) {
+ self.clock += 1;
+ }
+
+ fn get(&mut self, cs: &Arc<ComposedStory>, ft: &FrameText) -> Arc<FrameGlyphs> {
+ let key = (Arc::as_ptr(cs) as usize, ft.frame);
+ let stamp = self.clock;
+ if let Some(e) = self.map.get_mut(&key) {
+ e.stamp = stamp;
+ return e.glyphs.clone();
+ }
+ let g = Arc::new(build(cs, ft));
+ self.elements += g.elements;
+ self.map.insert(key, Entry { _story: cs.clone(), glyphs: g.clone(), stamp });
+ if self.elements > MAX_ELEMENTS {
+ self.evict();
+ }
+ g
+ }
+
+ /// Drop least recently used entries (never the ones used by the current render) until the
+ /// cache is at half its budget.
+ fn evict(&mut self) {
+ let mut stamps: Vec<(u64, usize, (usize, ItemId))> = self.map.iter().map(|(k, e)| (e.stamp, e.glyphs.elements, *k)).collect();
+ stamps.sort_unstable_by_key(|s| s.0);
+ for (stamp, n, k) in stamps {
+ if self.elements <= MAX_ELEMENTS / 2 || stamp >= self.clock {
+ break;
+ }
+ self.map.remove(&k);
+ self.elements -= n;
+ }
+ }
+
+ pub fn clear(&mut self) {
+ self.map.clear();
+ self.elements = 0;
+ }
+
+ pub fn len(&self) -> usize {
+ self.map.len()
+ }
+ }
+
+ fn transform_el(a: Affine, el: kurbo::PathEl) -> kurbo::PathEl {
+ use kurbo::PathEl::*;
+ match el {
+ MoveTo(p) => MoveTo(a * p),
+ LineTo(p) => LineTo(a * p),
+ QuadTo(p1, p2) => QuadTo(a * p1, a * p2),
+ CurveTo(p1, p2, p3) => CurveTo(a * p1, a * p2, a * p3),
+ ClosePath => ClosePath,
+ }
+ }
+
+ fn union(r: Option<Rect>, b: Rect) -> Option<Rect> {
+ Some(r.map_or(b, |r| r.union(b)))
+ }
+
+ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line) -> LineGlyphs {
+ let mut runs: Vec<(u32, BezPath)> = Vec::new();
+ let mut decos = Vec::new();
+ let mut glyphs = 0;
+ for g in &l.glyphs {
+ if !g.visible {
+ continue;
+ }
+ let style = &cs.styles[g.style as usize];
+ if style.underline || style.strikethrough {
+ let w = style.size / 14.0;
+ if style.underline {
+ decos.push((g.style, Rect::new(g.x, l.baseline + style.size * 0.12, g.x + g.adv, l.baseline + style.size * 0.12 + w)));
+ }
+ if style.strikethrough {
+ decos.push((g.style, Rect::new(g.x, l.baseline - style.size * 0.3, g.x + g.adv, l.baseline - style.size * 0.3 + w)));
+ }
+ }
+ let outline = db.outline(&g.face, g.gid);
+ if outline.elements().is_empty() {
+ continue;
+ }
+ let skew = if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
+ let a = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
+ let bp = match runs.iter_mut().find(|r| r.0 == g.style) {
+ Some(r) => &mut r.1,
+ None => {
+ runs.push((g.style, BezPath::new()));
+ &mut runs.last_mut().expect("pushed").1
+ }
+ };
+ for el in outline.elements() {
+ bp.push(transform_el(a, *el));
+ }
+ glyphs += 1;
+ }
+ let mut bounds = None;
+ for (si, bp) in &runs {
+ let st = &cs.styles[*si as usize];
+ let sw = if st.stroke != designcraft_color::swatch::NONE { st.stroke_weight } else { 0.0 };
+ bounds = union(bounds, bp.bounding_box().inflate(sw, sw));
+ }
+ for (_, r) in &decos {
+ bounds = union(bounds, *r);
+ }
+ LineGlyphs { bounds, runs, decos, glyphs }
+ }
+
+ fn build(cs: &ComposedStory, ft: &FrameText) -> FrameGlyphs {
+ let db = FontDb::global();
+ let lines: Vec<LineGlyphs> = ft.lines.iter().map(|l| build_line(db, cs, l)).collect();
+ let elements = lines.iter().flat_map(|l| &l.runs).map(|(_, bp)| bp.elements().len()).sum();
+ FrameGlyphs { lines, elements }
+ }
+
+ /// Conservative frame-space box of a line from its metrics (no outlines needed).
+ fn line_box(l: &Line) -> Option<Rect> {
+ let first = l.glyphs.first()?;
+ let x0 = l.glyphs.iter().map(|g| g.x).fold(first.x, f64::min);
+ let x1 = l.glyphs.iter().map(|g| g.x + g.adv.max(0.0)).fold(l.end_x, f64::max);
+ let pad = l.ascent.max(1.0);
+ Some(Rect::new(x0 - pad, l.baseline - l.ascent - pad, x1 + pad, l.baseline + l.descent.max(0.0) + pad))
+ }
+
+ impl Renderer {
+ pub(crate) fn draw_text(&mut self, ctx: &mut RenderContext, f: &Frame, cs: &Arc<ComposedStory>, ft: &FrameText, xf: Affine) {
+ let doc = f.doc;
+ let m = f.view * xf;
+ // Visible area in frame space.
+ if xf.determinant().abs() < 1e-12 {
+ return;
+ }
+ let vis = xf.inverse().transform_rect_bbox(f.visible);
+ // Decorations under text (shading) and rules.
+ for d in &ft.decos {
+ if !rect_overlaps(d.rect, vis) {
+ continue;
+ }
+ if let Some(c) = doc.resolve_color(&d.color, d.tint) {
+ ctx.set_transform(m);
+ ctx.set_paint(color_of(&c, 1.0));
+ ctx.fill_rect(&d.rect);
+ }
+ }
++ if !ft.tables.is_empty() {
++ self.draw_tables(ctx, f, ft, xf);
++ }
+ let scale = m.determinant().abs().sqrt();
+ let greek_px = f.opts.greek_below_px;
+ let mut greek = BezPath::new();
+ let mut shown: Vec<usize> = Vec::new();
+ for (i, l) in ft.lines.iter().enumerate() {
+ let Some(b) = line_box(l) else { continue };
+ if !rect_overlaps(b, vis) {
+ continue;
+ }
+ if greek_px > 0.0 && l.ascent * scale < greek_px {
+ if let Some(a) = l.glyphs.first() {
+ let r = kurbo::Rect::new(a.x, l.baseline - l.ascent * 0.5, l.end_x, l.baseline);
+ if r.width() > 0.0 {
+ greek.extend(r.path_elements(0.1));
+ }
+ }
+ continue;
+ }
+ shown.push(i);
+ }
+ ctx.set_transform(m);
+ if !shown.is_empty() {
+ let fg = self.glyphs.get(cs, ft);
+ // Resolve each style's paints once per frame.
+ let mut fills: Vec<Option<Option<peniko::Color>>> = vec![None; cs.styles.len()];
+ let mut fill_of = |si: u32| -> Option<peniko::Color> {
+ *fills[si as usize].get_or_insert_with(|| {
+ let st = &cs.styles[si as usize];
+ doc.resolve_color(&st.fill, st.fill_tint).map(|c| color_of(&c, 1.0))
+ })
+ };
+ for i in shown {
+ let lg = &fg.lines[i];
+ let Some(b) = lg.bounds else { continue };
+ if !rect_overlaps(b, vis) {
+ continue;
+ }
+ self.stats.glyphs += lg.glyphs;
+ for (si, bp) in &lg.runs {
+ if let Some(c) = fill_of(*si) {
+ ctx.set_paint(c);
+ ctx.fill_path(bp);
+ }
+ let st = &cs.styles[*si as usize];
+ if st.stroke != designcraft_color::swatch::NONE
+ && let Some(c) = doc.resolve_color(&st.stroke, st.stroke_tint)
+ {
+ ctx.set_paint(color_of(&c, 1.0));
+ ctx.set_stroke(kurbo::Stroke::new(st.stroke_weight));
+ ctx.stroke_path(bp);
+ }
+ }
+ for (si, r) in &lg.decos {
+ ctx.set_paint(fill_of(*si).unwrap_or(peniko::Color::BLACK));
+ ctx.fill_rect(r);
+ }
+ }
+ }
+ if !greek.elements().is_empty() {
+ ctx.set_paint(color_of(&designcraft_color::Color::gray(0.35), 0.5));
+ ctx.fill_path(&greek);
+ }
+ }
+ }
++
++impl Renderer {
++ /// Table fragments: cell fills, cell text, then cell edges and the border.
++ fn draw_tables(&mut self, ctx: &mut RenderContext, f: &Frame, ft: &FrameText, xf: Affine) {
++ let doc = f.doc;
++ for t in &ft.tables {
++ for c in &t.cells {
++ if let Some((sw, tint)) = &c.fill
++ && let Some(col) = doc.resolve_color(sw, *tint)
++ {
++ ctx.set_transform(f.view * xf);
++ ctx.set_paint(color_of(&col, 1.0));
++ // Overlap neighbours by half a device pixel so adjacent fills show no seams.
++ let h = 0.5 * f.px;
++ ctx.fill_rect(&c.rect.inflate(h, h));
++ }
++ }
++ for c in &t.cells {
++ if let Some(cft) = c.text.frames.first() {
++ self.draw_text(ctx, f, &c.text, cft, xf * Affine::translate(c.origin.to_vec2()));
++ }
++ }
++ ctx.set_transform(f.view * xf);
++ for s in &t.strokes {
++ let Some(col) = doc.resolve_color(&s.stroke.color, s.stroke.tint) else { continue };
++ ctx.set_paint(color_of(&col, 1.0));
++ ctx.set_stroke(cell_stroke(&s.stroke));
++ ctx.stroke_path(&kurbo::Line::new(s.a, s.b).to_path(0.1));
++ }
++ }
++ }
++}
++
++/// Kurbo stroke for a table edge.
++fn cell_stroke(s: &designcraft_doc::CellStroke) -> kurbo::Stroke {
++ let st = kurbo::Stroke::new(s.weight).with_caps(kurbo::Cap::Square);
++ match &s.kind {
++ designcraft_doc::StrokeType::Dashed { pattern } if !pattern.is_empty() => {
++ st.with_caps(kurbo::Cap::Butt).with_dashes(0.0, pattern.iter().copied())
++ }
++ designcraft_doc::StrokeType::Dotted => st.with_dashes(0.0, [0.0, s.weight * 2.0]).with_caps(kurbo::Cap::Round),
++ _ => st,
++ }
++}