Skip to content

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

Tables: cell stroke edits and queries start from the drawn edge; bounded dash patterns; closed table corners

aionggac4b83fa3930
diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs
index c70f477be..1676e2249 100644
--- a/crates/compose/src/table.rs
+++ b/crates/compose/src/table.rs
@@ -60,6 +60,23 @@ pub struct TableFrag {
}
impl TableFrag {
+ /// The ends of `s`, each moved outwards by half the weight where it is a corner of the
+ /// fragment. Edge types drawn as butt-ended fills (stripes, wavy, hash, the gap colour)
+ /// then close the table's corners as square-capped solid edges do.
+ pub fn corner_capped(&self, s: &StrokeSeg) -> (Point, Point) {
+ let d = s.b - s.a;
+ let len = d.hypot();
+ let half = s.stroke.weight / 2.0;
+ if !(len > 0.0 && half.is_finite() && half > 0.0) {
+ return (s.a, s.b);
+ }
+ let r = self.rect;
+ let near = |v: f64, edge: f64| (v - edge).abs() < 1e-6;
+ let corner = |p: Point| (near(p.x, r.x0) || near(p.x, r.x1)) && (near(p.y, r.y0) || near(p.y, r.y1));
+ let out = d * (half / len);
+ (if corner(s.a) { s.a - out } else { s.a }, if corner(s.b) { s.b + out } else { s.b })
+ }
+
pub(crate) fn shift(&mut self, dy: f64) {
if dy == 0.0 {
return;
@@ -504,6 +521,80 @@ fn boundary_stroke<'a>(
}
}
+/// The table's alternating row and column strokes, as drawn on body edges no cell supplies.
+/// Uniform active groups do not depend on which shared edge starts the pattern. Nonuniform
+/// and skipped patterns stay intact in the model until their phase is verified.
+fn table_patterns(table: &Table) -> (Option<&CellStroke>, Option<&CellStroke>) {
+ fn uniform(p: &Option<designcraft_doc::AltStrokes>) -> Option<&CellStroke> {
+ p.as_ref().filter(|p| p.skip_first == 0 && p.skip_last == 0).and_then(|p| p.uniform_stroke())
+ }
+ (uniform(&table.options.row_strokes), uniform(&table.options.column_strokes))
+}
+
+/// One stretch of a cell side, against one neighbouring cell or the outside of the table.
+#[derive(Clone, Copy, Debug)]
+pub struct SideStroke<'a> {
+ /// The neighbouring owner cell; `None` on the table's perimeter.
+ pub neighbor: Option<(usize, usize)>,
+ /// The grid line it lies on: a row boundary (0 = top) for top and bottom sides, a logical
+ /// column boundary (0 = start) for left and right sides.
+ pub boundary: usize,
+ /// The stroke drawn there.
+ pub stroke: &'a CellStroke,
+}
+
+/// The strokes drawn along side `side` (top, left, bottom, right; physical) of the owner cell
+/// at `(r, c)`, one per neighbouring cell, resolved as rendering resolves them: the winning
+/// copy of a shared edge, the table's row or column pattern where neither cell supplies the
+/// edge, and the table border on unoverridden perimeter edges. `owners` is [`Table::owners`].
+pub fn cell_side_strokes<'a>(table: &'a Table, owners: &[(usize, usize)], (r, c): (usize, usize), side: usize) -> Vec<SideStroke<'a>> {
+ let Some(cell) = table.cell(r, c) else { return Vec::new() };
+ let (nr, nc) = (table.nrows(), table.ncols());
+ let rtl = table.options.direction == designcraft_doc::TextDirection::RightToLeft;
+ let end_row = r.saturating_add(cell.row_span.max(1) as usize).min(nr);
+ let end_col = c.saturating_add(cell.col_span.max(1) as usize).min(nc);
+ let owner = |rr: usize, cc: usize| {
+ if rr >= nr || cc >= nc {
+ return None;
+ }
+ let &(orr, occ) = owners.get(rr.checked_mul(nc)?.checked_add(cc)?)?;
+ Some(((orr, occ), table.cell(orr, occ)?))
+ };
+ let me = Some(((r, c), cell));
+ let (row_pattern, column_pattern) = table_patterns(table);
+ let body = table.body_rows();
+ let mut out = Vec::new();
+ match side {
+ 0 | 2 => {
+ let boundary = if side == 0 { r } else { end_row };
+ let above = boundary.checked_sub(1);
+ let pattern = if above.is_some_and(|a| body.contains(&a)) && body.contains(&boundary) { row_pattern } else { None };
+ for cc in c..end_col {
+ let other = if side == 0 { above.and_then(|a| owner(a, cc)) } else { owner(boundary, cc) };
+ let (a, b) = if side == 0 { (other, me) } else { (me, other) };
+ if let Some((stroke, _, _)) = boundary_stroke(table, a, b, 2, 0, pattern) {
+ out.push(SideStroke { neighbor: other.map(|o| o.0), boundary, stroke });
+ }
+ }
+ }
+ 1 | 3 => {
+ // Physical left is the logical start in left-to-right tables.
+ let start = (side == 1) != rtl;
+ let (boundary, other_col) = if start { (c, c.checked_sub(1)) } else { (end_col, Some(end_col)) };
+ for rr in r..end_row {
+ let other = other_col.and_then(|oc| owner(rr, oc));
+ let (left, right) = if side == 1 { (other, me) } else { (me, other) };
+ let pattern = if body.contains(&rr) { column_pattern } else { None };
+ if let Some((stroke, _, _)) = boundary_stroke(table, left, right, 3, 1, pattern) {
+ out.push(SideStroke { neighbor: other.map(|o| o.0), boundary, stroke });
+ }
+ }
+ }
+ _ => {}
+ }
+ out
+}
+
/// Keep an unchanged winning cell edge continuous across different losing neighbors. In
/// particular, splitting a merged dashed edge would restart its dash phase at every cell.
fn push_boundary_stroke(
@@ -549,10 +640,7 @@ fn fragment_strokes(
Some(((r, c), table.cell(r, c)?))
};
let x = |c: usize| colx.get(c).map(|&offset| if rtl { right - offset } else { x0 + offset });
- // Uniform active groups do not depend on which shared edge starts the pattern. Keep
- // nonuniform and skipped patterns intact in the model until their phase is verified.
- let row_stroke = table.options.row_strokes.as_ref().filter(|p| p.skip_first == 0 && p.skip_last == 0).and_then(|p| p.uniform_stroke());
- let column_stroke = table.options.column_strokes.as_ref().filter(|p| p.skip_first == 0 && p.skip_last == 0).and_then(|p| p.uniform_stroke());
+ let (row_stroke, column_stroke) = table_patterns(table);
let body = table.body_rows();
let mut strokes = Vec::new();
for boundary in 0..=rows.len() {
diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs
index 5cfe05fe2..8cb1f229b 100644
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@ -70,6 +70,27 @@ pub enum Join {
Bevel,
}
+/// The shortest non-zero dash or gap a command accepts, in points.
+pub const MIN_DASH: f64 = 0.1;
+/// The longest dash or gap a command accepts, in points.
+pub const MAX_DASH: f64 = 10_000.0;
+/// The most lengths a dash pattern holds.
+pub const MAX_DASH_ENTRIES: usize = 64;
+/// The most pattern repeats a renderer expands along one path; finer patterns draw solid.
+pub const MAX_DASH_PERIODS: f64 = 20_000.0;
+
+/// An upper bound of the length of `bp`: the length of its control polygon.
+pub fn path_length_bound(bp: &designcraft_geom::BezPath) -> f64 {
+ use designcraft_geom::PathSeg;
+ bp.segments()
+ .map(|s| match s {
+ PathSeg::Line(l) => l.p0.distance(l.p1),
+ PathSeg::Quad(q) => q.p0.distance(q.p1) + q.p1.distance(q.p2),
+ PathSeg::Cubic(c) => c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3),
+ })
+ .sum()
+}
+
/// Stroke types (Stroke panel → Type). Dash/gap arrays are in points.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
@@ -117,6 +138,28 @@ impl StrokeType {
}
}
+ /// Whether `pattern` is a dash pattern commands accept: 1 to [`MAX_DASH_ENTRIES`] lengths,
+ /// each 0 or from [`MIN_DASH`] to [`MAX_DASH`] points, not all 0.
+ pub fn valid_dash_pattern(pattern: &[f64]) -> bool {
+ !pattern.is_empty()
+ && pattern.len() <= MAX_DASH_ENTRIES
+ && pattern.iter().all(|x| *x == 0.0 || (MIN_DASH..=MAX_DASH).contains(x))
+ && pattern.iter().any(|x| *x > 0.0)
+ }
+
+ /// Whether a renderer may expand `pattern` along a path at most `length` points long: at
+ /// most [`MAX_DASH_ENTRIES`] finite, non-negative lengths that repeat at most
+ /// [`MAX_DASH_PERIODS`] times. Otherwise the stroke draws solid, so a degenerate pattern
+ /// from a file can't stall rendering.
+ pub fn expandable_dashes(pattern: &[f64], length: f64) -> bool {
+ let period: f64 = pattern.iter().sum();
+ pattern.len() <= MAX_DASH_ENTRIES
+ && pattern.iter().all(|x| x.is_finite() && *x >= 0.0)
+ && period > 0.0
+ && length.is_finite()
+ && length / period <= MAX_DASH_PERIODS
+ }
+
/// The bands of a striped type (start, width as fractions of the weight).
pub fn bands(&self) -> Option<Vec<(f64, f64)>> {
Some(match self {
diff --git a/crates/engine/src/cmd/strokes.rs b/crates/engine/src/cmd/strokes.rs
index e31d407a8..95b9c53f7 100644
--- a/crates/engine/src/cmd/strokes.rs
+++ b/crates/engine/src/cmd/strokes.rs
@@ -42,8 +42,8 @@ pub fn specs() -> Vec<CommandSpec> {
}
"dash" => {
let pattern = p.get("pattern").map(nums).unwrap_or_else(|| vec![12.0, 4.0]);
- if pattern.is_empty() || pattern.iter().all(|v| *v <= 0.0) {
- return Err(bad(ID, "a dash `pattern` needs a positive length"));
+ if !StrokeType::valid_dash_pattern(&pattern) {
+ return Err(bad(ID, "a dash `pattern` needs 1 to 64 lengths, each 0 or 0.1 to 10000 pt, not all 0"));
}
StrokeType::Dashed { pattern }
}
diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs
index 902215366..e8c22c136 100644
--- a/crates/engine/src/cmd/table.rs
+++ b/crates/engine/src/cmd/table.rs
@@ -732,8 +732,8 @@ impl StrokeEdit {
let kind: StrokeType = serde_json::from_value(t.clone()).map_err(|e| bad(cmd, format!("bad stroke type: {e}")))?;
let finite = |v: &[f64]| v.len() <= 64 && v.iter().all(|x| x.is_finite() && *x >= 0.0);
match &kind {
- StrokeType::Dashed { pattern } if !finite(pattern) || pattern.iter().all(|x| *x == 0.0) => {
- return Err(bad(cmd, "a dash pattern needs up to 64 non-negative lengths, not all zero"));
+ StrokeType::Dashed { pattern } if !StrokeType::valid_dash_pattern(pattern) => {
+ return Err(bad(cmd, "a dash pattern needs 1 to 64 lengths, each 0 or 0.1 to 10000 pt, not all 0"));
}
StrokeType::Stripes { bands } if bands.len() > 64 || !bands.iter().all(|(a, b)| finite(&[*a, *b])) => {
return Err(bad(cmd, "stripes need up to 64 bands of non-negative numbers"));
@@ -760,21 +760,11 @@ impl StrokeEdit {
}
}
-/// The stroke an edge shows: the table border on an unoverridden perimeter edge, else the cell's.
-fn shown_edge<'a>(cell: &'a designcraft_doc::Cell, side: usize, perimeter: bool, borders: &'a [CellStroke; 4]) -> &'a CellStroke {
- match borders.get(side) {
- Some(border) if perimeter && !cell.border_overrides.get(side).copied().unwrap_or(false) => border,
- _ => &cell.strokes[side.min(3)],
- }
-}
-
-/// Whether each side (top, left, bottom, right; physical) of the cell is on the table's perimeter.
-fn perimeter(t: &Table, (r, c): (usize, usize), cell: &designcraft_doc::Cell) -> [bool; 4] {
- let (nr, nc) = (t.nrows(), t.ncols());
- let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;
- let at_bottom = r.saturating_add(cell.row_span.max(1) as usize);
- let at_right = c.saturating_add(cell.col_span.max(1) as usize);
- [r == 0, if rtl { at_right >= nc } else { c == 0 }, at_bottom >= nr, if rtl { c == 0 } else { at_right >= nc }]
+/// The stroke drawn on side `side` of the owner cell at `(r, c)` (where that side meets its
+/// first neighbour), as rendering resolves it; the cell's own copy if the side has no stretch.
+fn drawn_side(t: &Table, owners: &[(usize, usize)], (r, c): (usize, usize), side: usize) -> Option<CellStroke> {
+ let drawn = compose::table::cell_side_strokes(t, owners, (r, c), side).first().map(|s| s.stroke.clone());
+ drawn.or_else(|| t.cell(r, c).and_then(|cell| cell.strokes.get(side).cloned()))
}
fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
@@ -809,19 +799,32 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
let nc = t.ncols();
let nr = t.nrows();
let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;
- let borders: [CellStroke; 4] = std::array::from_fn(|side| t.options.border_for(side).clone());
// Local edits outrank previously imported edges, including explicit zero/None.
let priority = if stroke.is_some() { next_cell_stroke_priority(t) } else { 0 };
let rg = g.range;
+ // Each chosen edge starts from the stroke drawn there, which both copies of a shared
+ // edge then take, so the edit changes only the attributes it names.
+ let mut bases = std::collections::HashMap::new();
+ if let Some((_, edges)) = &stroke {
+ for r in rg.r0..=rg.r1 {
+ for c in rg.c0..=rg.c1 {
+ if owners.get(r * nc + c) != Some(&(r, c)) {
+ continue;
+ }
+ let Some(cell) = t.cell(r, c) else { continue };
+ for (i, on) in edges.sides(rg, (r, c), (cell.row_span, cell.col_span), rtl).into_iter().enumerate() {
+ if let Some(base) = drawn_side(t, &owners, (r, c), i).filter(|_| on) {
+ bases.insert((r, c, i), base);
+ }
+ }
+ }
+ }
+ }
for r in rg.r0..=rg.r1 {
for c in rg.c0..=rg.c1 {
if owners.get(r * nc + c) != Some(&(r, c)) {
continue;
}
- let on_perimeter = match t.cell(r, c) {
- Some(cell) => perimeter(t, (r, c), cell),
- None => continue,
- };
let Some(cell) = t.cell_mut(r, c) else { continue };
if let Some(f) = &fill {
cell.fill = f.clone();
@@ -839,11 +842,9 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
let len = cell.text.len();
cell.text.replace(0..len, tx);
}
- if let Some((edit, edges)) = &stroke {
- let chosen = edges.sides(rg, (r, c), (cell.row_span, cell.col_span), rtl);
- for (i, on) in chosen.into_iter().enumerate() {
- if on {
- let base = shown_edge(cell, i, on_perimeter[i], &borders).clone();
+ if let Some((edit, _)) = &stroke {
+ for i in 0..4 {
+ if let Some(base) = bases.remove(&(r, c, i)) {
cell.strokes[i] = edit.apply(base);
cell.stroke_defined[i] = true;
cell.stroke_priorities[i] = priority;
@@ -896,7 +897,6 @@ fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {
let owners = t.owners();
let nc = t.ncols();
let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;
- let borders: [CellStroke; 4] = std::array::from_fn(|side| t.options.border_for(side).clone());
// One value per key, or null once two edges (cells) disagree.
fn merge(slot: &mut Option<Value>, v: Value) {
match slot {
@@ -908,7 +908,8 @@ fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {
let keys = ["weight", "color", "tint", "type", "gapColor", "gapTint"];
let mut stroke: [Option<Value>; 6] = Default::default();
let (mut fill, mut fill_tint) = (None, None);
- let mut count = 0usize;
+ // Each drawn edge once: a shared edge is a side of both its cells.
+ let mut seen = std::collections::HashSet::new();
for r in g.range.r0..=g.range.r1 {
for c in g.range.c0..=g.range.c1 {
if owners.get(r * nc + c) != Some(&(r, c)) {
@@ -917,16 +918,20 @@ fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {
let Some(cell) = t.cell(r, c) else { continue };
merge(&mut fill, json!(cell.fill));
merge(&mut fill_tint, json!(cell.fill_tint));
- let on_perimeter = perimeter(t, (r, c), cell);
for (i, on) in edges.sides(g.range, (r, c), (cell.row_span, cell.col_span), rtl).into_iter().enumerate() {
if !on {
continue;
}
- count += 1;
- let e = shown_edge(cell, i, on_perimeter[i], &borders);
- let values = [json!(e.weight), json!(e.color), json!(e.tint), json!(e.kind), json!(e.gap_color), json!(e.gap_tint)];
- for (slot, v) in stroke.iter_mut().zip(values) {
- merge(slot, v);
+ for side in compose::table::cell_side_strokes(t, &owners, (r, c), i) {
+ let (x, y) = (Some((r, c)), side.neighbor);
+ if !seen.insert((i % 2, side.boundary, x.min(y), x.max(y))) {
+ continue;
+ }
+ let e = side.stroke;
+ let values = [json!(e.weight), json!(e.color), json!(e.tint), json!(e.kind), json!(e.gap_color), json!(e.gap_tint)];
+ for (slot, v) in stroke.iter_mut().zip(values) {
+ merge(slot, v);
+ }
}
}
}
@@ -937,7 +942,7 @@ fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {
}
out.insert("fill".into(), fill.unwrap_or(Value::Null));
out.insert("fillTint".into(), fill_tint.unwrap_or(Value::Null));
- out.insert("edges".into(), json!(count));
+ out.insert("edges".into(), json!(seen.len()));
Ok(Value::Object(out))
}
diff --git a/crates/engine/src/tests_table.rs b/crates/engine/src/tests_table.rs
index 83b4f9c97..80c0438dd 100644
--- a/crates/engine/src/tests_table.rs
+++ b/crates/engine/src/tests_table.rs
@@ -421,7 +421,7 @@ fn cell_stroke_gap_colour_on_inner_horizontal_edges_of_a_selection_undoes_and_sa
}
// The query reports the chosen edges, and mixed values as null.
let inner = s.execute("table.getCellStroke", &json!({"edges": "innerHorizontal"})).unwrap();
- assert_eq!((inner["weight"].as_f64(), inner["gapColor"].as_str(), inner["edges"].as_u64()), (Some(3.0), Some(cyan), Some(4)));
+ assert_eq!((inner["weight"].as_f64(), inner["gapColor"].as_str(), inner["edges"].as_u64()), (Some(3.0), Some(cyan), Some(2)));
let all = s.execute("table.getCellStroke", &json!({})).unwrap();
assert!(all["weight"].is_null() && all["gapColor"].is_null());
// Bad values are errors and change nothing.
@@ -438,6 +438,72 @@ fn cell_stroke_gap_colour_on_inner_horizontal_edges_of_a_selection_undoes_and_sa
assert_eq!(table_for(&s, sid, tid), &before);
}
+#[test]
+fn shared_edge_edits_and_queries_start_from_the_drawn_stroke() {
+ let cyan = "C=100 M=0 Y=0 K=0";
+ let thin = doc::CellStroke { weight: 0.25, color: cyan.into(), ..Default::default() };
+ // The higher-priority copy of a shared edge is drawn: 2 pt cyan over 0.5 pt black.
+ let (mut s, sid, _) = session_with_frame();
+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 1})).unwrap()["table"].as_u64().unwrap();
+ s.edit(|d, _| {
+ let t = d.story_mut(doc::StoryId(sid)).unwrap().table_mut(tid).unwrap();
+ let upper = t.cell_mut(0, 0).unwrap();
+ upper.strokes[2] = doc::CellStroke { weight: 2.0, color: cyan.into(), ..Default::default() };
+ (upper.stroke_defined[2], upper.stroke_priorities[2]) = (true, 5);
+ let lower = t.cell_mut(1, 0).unwrap();
+ lower.strokes[0] = doc::CellStroke { weight: 0.5, ..Default::default() };
+ (lower.stroke_defined[0], lower.stroke_priorities[0]) = (true, 1);
+ Ok(())
+ })
+ .unwrap();
+ let q = s.execute("table.getCellStroke", &json!({"table": tid, "edges": "innerHorizontal"})).unwrap();
+ assert_eq!((q["weight"].as_f64(), q["color"].as_str(), q["edges"].as_u64()), (Some(2.0), Some(cyan), Some(1)));
+ s.execute("table.setCell", &json!({"table": tid, "stroke": {"color": "[Paper]", "edges": "innerHorizontal"}})).unwrap();
+ let t = table_for(&s, sid, tid);
+ for e in [&t.cell(0, 0).unwrap().strokes[2], &t.cell(1, 0).unwrap().strokes[0]] {
+ assert_eq!((e.weight, e.color.as_str()), (2.0, "[Paper]"));
+ }
+ let composed = s.cache.get(&s.doc().unwrap().doc, doc::StoryId(sid), None);
+ let frag = composed.frames.iter().flat_map(|f| &f.tables).next().unwrap();
+ assert!(frag.strokes.iter().any(|x| x.stroke.weight == 2.0 && x.stroke.color == "[Paper]"));
+ assert!(!frag.strokes.iter().any(|x| x.stroke.weight == 0.5), "the edge stays 2 pt");
+
+ // An interior edge no cell supplies is drawn from the table's row pattern.
+ let (mut s, sid, _) = session_with_frame();
+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ s.edit(|d, _| {
+ let t = d.story_mut(doc::StoryId(sid)).unwrap().table_mut(tid).unwrap();
+ t.options.row_strokes = Some(doc::AltStrokes { first: 1, next: 0, first_stroke: thin.clone(), ..Default::default() });
+ for cell in &mut t.cells {
+ (cell.stroke_defined, cell.border_overrides, cell.stroke_priorities) = ([false; 4], [false; 4], [0; 4]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ let q = s.execute("table.getCellStroke", &json!({"table": tid, "edges": "innerHorizontal"})).unwrap();
+ assert_eq!((q["weight"].as_f64(), q["color"].as_str(), q["edges"].as_u64()), (Some(0.25), Some(cyan), Some(2)));
+ s.execute("table.setCell", &json!({"table": tid, "stroke": {"color": "[Paper]", "edges": "innerHorizontal"}})).unwrap();
+ let t = table_for(&s, sid, tid);
+ for (r, c, side) in [(0, 0, 2), (0, 1, 2), (1, 0, 0), (1, 1, 0)] {
+ let e = &t.cell(r, c).unwrap().strokes[side];
+ assert_eq!((e.weight, e.color.as_str()), (0.25, "[Paper]"), "{r},{c} side {side}");
+ }
+}
+
+#[test]
+fn degenerate_dash_patterns_are_rejected() {
+ let (mut s, sid, _) = session_with_frame();
+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ let before = table_for(&s, sid, tid).clone();
+ for pattern in [json!([1e-6, 1e-6]), json!([0.05, 3]), json!([]), json!([0, 0]), json!(vec![1.0; 65]), json!([20000, 1])] {
+ let stroke = json!({"table": tid, "stroke": {"type": {"kind": "dashed", "pattern": pattern}}});
+ assert!(s.execute("table.setCell", &stroke).is_err(), "{pattern}");
+ assert_eq!(table_for(&s, sid, tid), &before);
+ assert!(s.execute("strokeStyle.new", &json!({"name": "Fine", "type": "dash", "pattern": pattern})).is_err(), "{pattern}");
+ }
+ s.execute("table.setCell", &json!({"table": tid, "stroke": {"type": {"kind": "dashed", "pattern": [0.1, 0, 3]}}})).unwrap();
+}
+
#[test]
fn cell_and_table_style_strokes_take_type_and_gap_colour_with_validation() {
let (mut s, sid, _) = session_with_frame();
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index d92fc242b..9735d5d96 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -1089,15 +1089,17 @@ impl Exporter<'_> {
s.set_fill(None);
return;
}
+ // Viewers expand dashes too: a degenerate pattern draws solid, as on screen.
+ let length = designcraft_doc::path_length_bound(bp);
let dash = match &kind {
- StrokeType::Dashed { pattern } if pattern.iter().any(|v| *v > 0.0) => {
+ StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => {
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
if pat.len() % 2 == 1 {
pat.extend(pat.clone());
}
Some(StrokeDash { array: pat, offset: 0.0 })
}
- StrokeType::Dotted => {
+ StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], length) => {
cap = krilla::paint::LineCap::Round;
Some(StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 })
}
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index bcc75b28e..66a865d4f 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -217,6 +217,12 @@ impl Exporter<'_> {
bp.move_to(seg.a);
bp.line_to(seg.b);
let Some(p) = to_path(&bp) else { continue };
+ // Butt-ended fills close the table's corners the way square caps do.
+ let (ca, cb) = t.corner_capped(seg);
+ let mut capped = BezPath::new();
+ capped.move_to(ca);
+ capped.line_to(cb);
+ let Some(cp) = to_path(&capped) else { continue };
// Gap colour under dashes, dots and stripes: the whole edge, solid.
if !matches!(kind, designcraft_doc::StrokeType::Solid)
&& st.gap_color != designcraft_color::swatch::NONE
@@ -229,11 +235,11 @@ impl Exporter<'_> {
line_cap: krilla::paint::LineCap::Butt,
..Default::default()
}));
- s.draw_path(&p);
+ s.draw_path(&cp);
s.set_stroke(None);
}
// Stripes, wavy and hash types are fills along the edge.
- if let Some(o) = kind.outline(&bp, st.weight, 0.05)
+ if let Some(o) = kind.outline(&capped, st.weight, 0.05)
&& let Some(op) = to_path(&o)
{
s.set_stroke(None);
@@ -243,14 +249,18 @@ impl Exporter<'_> {
continue;
}
let (cap, dash) = match &kind {
- designcraft_doc::StrokeType::Dashed { pattern } if pattern.iter().any(|v| *v > 0.0) => {
+ designcraft_doc::StrokeType::Dashed { pattern }
+ if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) =>
+ {
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
if pat.len() % 2 == 1 {
pat.extend(pat.clone());
}
(krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 }))
}
- designcraft_doc::StrokeType::Dotted => {
+ designcraft_doc::StrokeType::Dotted
+ if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) =>
+ {
(krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }))
}
_ => (krilla::paint::LineCap::Square, None),
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index a9a7b09b2..b6cf6ebc3 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -637,9 +637,14 @@ impl Renderer {
})
.with_miter_limit(st.miter_limit);
let kind = f.doc.stroke_kind(&st.kind);
+ let length = designcraft_doc::path_length_bound(bp);
match &kind {
- StrokeType::Dashed { pattern } if !pattern.is_empty() => stroke = stroke.with_dashes(0.0, pattern.iter().copied()),
- StrokeType::Dotted => stroke = stroke.with_dashes(0.0, [0.0, st.weight * 2.0]).with_caps(kurbo::Cap::Round),
+ StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => {
+ stroke = stroke.with_dashes(0.0, pattern.iter().copied())
+ }
+ StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], length) => {
+ stroke = stroke.with_dashes(0.0, [0.0, st.weight * 2.0]).with_caps(kurbo::Cap::Round)
+ }
_ => {}
}
ctx.set_transform(f.view * xf);
@@ -1513,6 +1518,49 @@ mod tests {
assert!(column.iter().any(|p| ink(*p)) && column.iter().any(|p| cyan(*p)), "stripes and gap: {column:?}");
}
+ #[test]
+ fn degenerate_dash_patterns_draw_solid_and_fill_types_close_table_corners() {
+ let fine = designcraft_doc::StrokeType::Dashed { pattern: vec![1e-6, 1e-6] };
+ // Expanding these would take ~10^8 dashes per edge.
+ assert!(text::cell_stroke(&fine, 4.0, 200.0).dash_pattern.is_empty());
+ assert!(text::cell_stroke(&designcraft_doc::StrokeType::Dotted, 1e-6, 200.0).dash_pattern.is_empty());
+ assert!(!text::cell_stroke(&designcraft_doc::StrokeType::Dashed { pattern: vec![3.0, 2.0] }, 1.0, 200.0).dash_pattern.is_empty());
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap();
+ d.item_mut(fid).unwrap().stroke = designcraft_doc::Stroke { weight: 2.0, kind: fine.clone(), ..Default::default() };
+ let mut t = designcraft_doc::Table::new(1, 2, 2, 0, 0, 200.0);
+ for r in 0..2 {
+ t.rows[r].height = 60.0;
+ t.rows[r].mode = designcraft_doc::RowHeightMode::Exactly;
+ }
+ let stroke = |kind| designcraft_doc::CellStroke { weight: 8.0, kind, gap_color: "C=100 M=0 Y=0 K=0".into(), ..Default::default() };
+ for cell in &mut t.cells {
+ cell.strokes = std::array::from_fn(|_| stroke(designcraft_doc::StrokeType::ThickThin));
+ cell.border_overrides = [true; 4];
+ cell.stroke_defined = [true; 4];
+ }
+ if let Some(cell) = t.cell_mut(1, 0) {
+ cell.strokes[2] = stroke(fine);
+ }
+ d.story_mut(sid).unwrap().insert_table(0, t);
+ let cache = Cache::new();
+ let frag = cache.get(&d, sid, None).frames[0].tables[0].clone();
+ let (top, bottom) = (frag.cell(0, 0).unwrap().rect, frag.cell(1, 0).unwrap().rect);
+ let mut r = Renderer::new();
+ r.threads = 0;
+ let img = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();
+ let ink = |p: [u8; 4]| p[0] < 80;
+ let solid: Vec<_> = (2..10).map(|i| img.pixel((bottom.x0 + 20.0 + i as f64 * 0.5) as u32, bottom.y1.round() as u32)).collect();
+ assert!(solid.iter().all(|p| ink(*p)), "the degenerate dashed edge draws solid: {solid:?}");
+ // Outside the table's top-left corner, inside both edges' reach.
+ let corner = img.pixel((top.x0 - 3.0) as u32, (top.y0 - 3.0) as u32);
+ assert!(ink(corner), "corner closed: {corner:?}");
+ let edge = frag.strokes.iter().find(|s| s.a == designcraft_geom::Point::new(top.x0, top.y0) && s.a.y == s.b.y).unwrap();
+ let (a, b) = frag.corner_capped(edge);
+ assert_eq!((a, b), (designcraft_geom::Point::new(top.x0 - 4.0, top.y0), edge.b), "only table corners extend");
+ }
+
#[test]
fn renders_tables() {
let mut d = Document::new(&NewDocument::default());
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index 7c4420727..f9667ebaf 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -449,35 +449,41 @@ impl Renderer {
let Some(col) = doc.resolve_color(&s.stroke.color, s.stroke.tint) else { continue };
let kind = doc.stroke_kind(&s.stroke.kind);
let line = kurbo::Line::new(s.a, s.b).to_path(0.1);
+ // Butt-ended fills close the table's corners the way square caps do.
+ let (ca, cb) = t.corner_capped(s);
+ let capped = kurbo::Line::new(ca, cb).to_path(0.1);
// Gap colour under dashes, dots and stripes: the whole edge, solid.
if !matches!(kind, designcraft_doc::StrokeType::Solid)
&& let Some(gap) = doc.resolve_color(&s.stroke.gap_color, s.stroke.gap_tint)
{
ctx.set_paint(color_of(&gap, 1.0));
ctx.set_stroke(kurbo::Stroke::new(s.stroke.weight).with_caps(kurbo::Cap::Butt));
- ctx.stroke_path(&line);
+ ctx.stroke_path(&capped);
}
ctx.set_paint(color_of(&col, 1.0));
// Stripes, wavy and hash types are fills along the edge.
- if let Some(o) = kind.outline(&line, s.stroke.weight, 0.05 * f.px) {
+ if let Some(o) = kind.outline(&capped, s.stroke.weight, 0.05 * f.px) {
ctx.fill_path(&o);
continue;
}
- ctx.set_stroke(cell_stroke(&kind, s.stroke.weight));
+ ctx.set_stroke(cell_stroke(&kind, s.stroke.weight, s.a.distance(s.b)));
ctx.stroke_path(&line);
}
}
}
}
-/// Kurbo stroke for a table edge of a resolved stroke type.
-fn cell_stroke(kind: &designcraft_doc::StrokeType, weight: f64) -> kurbo::Stroke {
+/// Kurbo stroke for a table edge `length` points long of a resolved stroke type.
+pub(crate) fn cell_stroke(kind: &designcraft_doc::StrokeType, weight: f64, length: f64) -> kurbo::Stroke {
+ use designcraft_doc::StrokeType;
let st = kurbo::Stroke::new(weight).with_caps(kurbo::Cap::Square);
match kind {
- designcraft_doc::StrokeType::Dashed { pattern } if !pattern.is_empty() => {
+ StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => {
st.with_caps(kurbo::Cap::Butt).with_dashes(0.0, pattern.iter().copied())
}
- designcraft_doc::StrokeType::Dotted => st.with_dashes(0.0, [0.0, weight * 2.0]).with_caps(kurbo::Cap::Round),
+ StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, weight * 2.0], length) => {
+ st.with_dashes(0.0, [0.0, weight * 2.0]).with_caps(kurbo::Cap::Round)
+ }
_ => st,
}
}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 18e9e4b4d..89b84a2d7 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -1431,8 +1431,10 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
}
for l in &mut layers {
let mut on = l["visible"].as_bool().unwrap_or(true);
- if ui.checkbox(&mut on, l["name"].as_str().unwrap_or("")).changed() {
- l["visible"] = json!(on);
+ if ui.checkbox(&mut on, l["name"].as_str().unwrap_or("")).changed()
+ && let Some(o) = l.as_object_mut()
+ {
+ o.insert("visible".into(), json!(on));
}
}
d.fields.insert("layers".into(), json!(layers));
@@ -1769,18 +1771,7 @@ fn cell_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Cell Stroke")).font(semibold(12.0)));
let mut edges = cell_stroke::edges_from(d.fields.get("edges").unwrap_or(&Value::Null));
if cell_stroke::edge_proxy(ui, "cell_options", &mut edges, &lang) {
- d.fields.insert("edges".into(), cell_stroke::edges_param(&edges));
- // Fields the user hasn't changed follow the chosen edges.
- let cur = cell_stroke::current(app, &edges);
- let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
- let mut next = seed.clone();
- for (k, stroke) in CELL_OPTION_KEYS {
- if stroke && d.fields.get(k) == seed.get(k) {
- d.fields.insert(k.into(), cur[k].clone());
- next[k] = cur[k].clone();
- }
- }
- d.fields.insert("seed".into(), next);
+ cell_options_edges_changed(app, d, &edges);
}
ui.add_space(6.0);
let values = Value::Object(d.fields.clone());
@@ -1807,6 +1798,28 @@ fn cell_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
});
}
+/// Cell Options with a new edge choice: the stroke fields the user hasn't changed show the
+/// chosen edges' values, and every stroke field's seed becomes those values, so OK applies
+/// exactly the fields that differ from what the chosen edges show.
+fn cell_options_edges_changed(app: &mut DesignApp, d: &mut Dialog, edges: &crate::panels::cell_stroke::Edges) {
+ d.fields.insert("edges".into(), crate::panels::cell_stroke::edges_param(edges));
+ let cur = crate::panels::cell_stroke::current(app, edges);
+ let mut seed = d.fields.get("seed").and_then(Value::as_object).cloned().unwrap_or_default();
+ for (k, stroke) in CELL_OPTION_KEYS {
+ if !stroke {
+ continue;
+ }
+ let v = cur.get(k).cloned().unwrap_or(Value::Null);
+ // Null shows mixed values; the user can't type it.
+ let field = d.fields.get(k).filter(|f| !f.is_null());
+ if field.is_none() || field == seed.get(k) {
+ d.fields.insert(k.into(), v.clone());
+ }
+ seed.insert(k.into(), v);
+ }
+ d.fields.insert("seed".into(), Value::Object(seed));
+}
+
/// Apply the Cell Options fields that differ from the cells' values, as one `table.setCell`.
fn confirm_cell_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {
let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
@@ -3872,6 +3885,33 @@ mod tests {
assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");
}
+ #[test]
+ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ app.run("table.select", json!({"what": "table"})).unwrap();
+ app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap();
+ app.run("app.cellOptionsDialog", json!({})).unwrap();
+ let mut d = app.ui.dialog.take().unwrap();
+ d.fields.insert("seed".into(), json!(5));
+ let outer = [true, true, true, true, false, false];
+ cell_options_edges_changed(&mut app, &mut d, &outer);
+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0)));
+ // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen
+ // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it.
+ d.fields.insert("weight".into(), json!(5.0));
+ cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);
+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0)));
+ d.fields.insert("weight".into(), json!(1.0));
+ app.ui.dialog = Some(d);
+ confirm(&mut app).unwrap();
+ let st = app.session.active().unwrap();
+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
+ assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);
+ }
+
fn dialog_context(language: &str) -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx, language);
diff --git a/crates/ui-egui/src/panels/cell_stroke.rs b/crates/ui-egui/src/panels/cell_stroke.rs
index d8b412ea2..750e180a8 100644
--- a/crates/ui-egui/src/panels/cell_stroke.rs
+++ b/crates/ui-egui/src/panels/cell_stroke.rs
@@ -76,6 +76,36 @@ fn line_at(r: Rect, p: Pos2) -> Option<usize> {
.map(|(i, _)| i)
}
+/// A click on the proxy.
+struct ProxyClick {
+ /// The choice before the first click of this click sequence.
+ start: Edges,
+ /// The line clicked, and the line of the click before.
+ hit: Option<usize>,
+ last: Option<usize>,
+ double: bool,
+ triple: bool,
+}
+
+/// Apply a proxy click to `edges`. Returns whether the choice changed.
+fn proxy_click(edges: &mut Edges, click: ProxyClick) -> bool {
+ if click.triple {
+ let all = click.start.iter().all(|on| *on);
+ *edges = [!all; 6];
+ return true;
+ }
+ let Some(h) = click.hit else { return false };
+ if click.double && click.last == Some(h) {
+ let outer = h < 4;
+ for (i, on) in edges.iter_mut().enumerate() {
+ *on = (i < 4) == outer;
+ }
+ } else if let Some(on) = edges.get_mut(h) {
+ *on = !*on;
+ }
+ true
+}
+
/// The edge proxy. Returns whether the choice changed.
pub fn edge_proxy(ui: &mut Ui, id: &str, edges: &mut Edges, lang: &str) -> bool {
let t = Tokens::get(ui.ctx());
@@ -89,24 +119,17 @@ pub fn edge_proxy(ui: &mut Ui, id: &str, edges: &mut Edges, lang: &str) -> bool
let hit = resp.interact_pointer_pos().or_else(|| resp.hover_pos()).and_then(|p| line_at(r, p));
let mut changed = false;
if resp.clicked() {
- // A double-click counts only on the line of the click before it.
+ let (double, triple) = (resp.double_clicked(), resp.triple_clicked());
+ // A double-click counts only on the line of the click before it; a triple-click
+ // decides from the choice before the sequence's first click.
let last_key = ui.id().with((id, "proxy_last"));
+ let start_key = ui.id().with((id, "proxy_start"));
let last: Option<usize> = ui.data(|d| d.get_temp(last_key)).flatten();
- if resp.triple_clicked() {
- let all = edges.iter().all(|on| *on);
- *edges = [!all; 6];
- changed = true;
- } else if let Some(h) = hit {
- if resp.double_clicked() && last == Some(h) {
- let outer = h < 4;
- for (i, on) in edges.iter_mut().enumerate() {
- *on = (i < 4) == outer;
- }
- } else if let Some(on) = edges.get_mut(h) {
- *on = !*on;
- }
- changed = true;
+ if !double && !triple {
+ ui.data_mut(|d| d.insert_temp(start_key, *edges));
}
+ let start: Edges = ui.data(|d| d.get_temp(start_key)).unwrap_or(*edges);
+ changed = proxy_click(edges, ProxyClick { start, hit, last, double, triple });
ui.data_mut(|d| d.insert_temp(last_key, hit));
}
let p = ui.painter();
@@ -238,6 +261,18 @@ mod tests {
use super::*;
+ #[test]
+ fn proxy_triple_click_clears_all_lines_when_all_were_chosen_and_chooses_all_otherwise() {
+ for (before, after) in [([true; 6], [false; 6]), ([true, false, true, false, false, false], [true; 6]), ([false; 6], [true; 6])] {
+ let mut edges = before;
+ let click = |hit, double, triple| ProxyClick { start: before, hit, last: Some(0), double, triple };
+ proxy_click(&mut edges, click(Some(0), false, false));
+ proxy_click(&mut edges, click(Some(0), true, false));
+ proxy_click(&mut edges, click(Some(0), false, true));
+ assert_eq!(edges, after, "triple-click from {before:?}");
+ }
+ }
+
#[test]
fn stroke_panel_proxy_limits_a_weight_change_to_the_chosen_cell_edges() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());