DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Tables: cell edge gap colour and tint, all stroke types on cell edges, inner horizontal/vertical edge choice
aiongg20d4178c4342
diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rsindex e348ff295..b6ced0d59 100644--- a/crates/doc/src/styles.rs+++ b/crates/doc/src/styles.rs@@ -163,11 +163,20 @@ pub struct CellStrokeAttrs {pub tint: Option<f32>,#[serde(skip_serializing_if = "Option::is_none")]pub kind: Option<crate::item::StrokeType>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub gap_color: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub gap_tint: Option<f32>,}impl CellStrokeAttrs {pub fn is_empty(&self) -> bool {- self.weight.is_none() && self.color.is_none() && self.tint.is_none() && self.kind.is_none()+ self.weight.is_none()+ && self.color.is_none()+ && self.tint.is_none()+ && self.kind.is_none()+ && self.gap_color.is_none()+ && self.gap_tint.is_none()}pub fn apply_to(&self, stroke: &mut crate::table::CellStroke) {@@ -183,6 +192,12 @@ impl CellStrokeAttrs {if let Some(v) = &self.kind {stroke.kind = v.clone();}+ if let Some(v) = &self.gap_color {+ stroke.gap_color = v.clone();+ }+ if let Some(v) = self.gap_tint {+ stroke.gap_tint = v;+ }}fn merge(&mut self, other: &Self) {@@ -198,10 +213,23 @@ impl CellStrokeAttrs {if other.kind.is_some() {self.kind = other.kind.clone();}+ if other.gap_color.is_some() {+ self.gap_color = other.gap_color.clone();+ }+ if other.gap_tint.is_some() {+ self.gap_tint = other.gap_tint;+ }}fn from_stroke(stroke: &crate::table::CellStroke) -> Self {- Self { weight: Some(stroke.weight), color: Some(stroke.color.clone()), tint: Some(stroke.tint), kind: Some(stroke.kind.clone()) }+ Self {+ weight: Some(stroke.weight),+ color: Some(stroke.color.clone()),+ tint: Some(stroke.tint),+ kind: Some(stroke.kind.clone()),+ gap_color: Some(stroke.gap_color.clone()),+ gap_tint: Some(stroke.gap_tint),+ }}}diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rsindex 7fe385e98..8752075c8 100644--- a/crates/doc/src/table.rs+++ b/crates/doc/src/table.rs@@ -62,11 +62,30 @@ pub struct CellStroke {pub color: String,pub tint: f32,pub kind: StrokeType,+ /// Painted in the gaps of dashed, dotted and striped types.+ #[serde(skip_serializing_if = "is_no_swatch")]+ pub gap_color: String,+ #[serde(skip_serializing_if = "is_full")]+ pub gap_tint: f32,+}++fn is_no_swatch(s: &str) -> bool {+ s == designcraft_color::swatch::NONE+}+fn is_full(t: &f32) -> bool {+ *t == 1.0}impl Default for CellStroke {fn default() -> Self {- CellStroke { weight: 1.0, color: designcraft_color::swatch::BLACK.into(), tint: 1.0, kind: StrokeType::Solid }+ CellStroke {+ weight: 1.0,+ color: designcraft_color::swatch::BLACK.into(),+ tint: 1.0,+ kind: StrokeType::Solid,+ gap_color: designcraft_color::swatch::NONE.into(),+ gap_tint: 1.0,+ }}}diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rsindex 028971e97..01cd5fb46 100644--- a/crates/engine/src/cmd/table.rs+++ b/crates/engine/src/cmd/table.rs@@ -196,10 +196,19 @@ fn table_specs() -> Vec<CommandSpec> {"Cell Options",[],None,- "{fill?: swatch, tint?, insets?: n | [t,l,b,r], vj?: top|center|bottom|justify, text?, stroke?: {weight?, color?, tint?, type?: solid|dashed|dotted, edges?: all|outer|inner|top|left|bottom|right}}",+ "{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj?: top|center|bottom|justify, text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",in_table,set_cell),+ cmd!(+ query "table.getCellStroke",+ "Get Cell Stroke",+ [],+ None,+ "{story?, table?, rows?, cols?, edges?} → {weight, color, tint, type, gapColor, gapTint, fill, fillTint, edges: count} of the chosen edges of the target cells; a value that differs between them is null",+ in_table_or_ids,+ get_cell_stroke+ ),cmd!("table.setRowHeight", "Row Height", [], None, "{height, mode?: atLeast|exactly}", in_table, set_row_height),cmd!("table.setColumnWidth", "Column Width", [], None, "{width}", in_table, set_col_width),cmd!("table.distributeColumns", "Distribute Columns Evenly", ["Table"], None, "{}", in_table, distribute_cols),@@ -217,7 +226,7 @@ fn table_specs() -> Vec<CommandSpec> {"Table Options",[],None,- "{direction?: leftToRight|rightToLeft, border?: {weight?, color?, tint?, type?}, spaceBefore?, spaceAfter?, headerRows?, footerRows?, repeatHeader?, repeatFooter?, altRows?: {first, firstColor, firstTint, next, nextColor, nextTint, skipFirst, skipLast} | null, altCols?: … | null}",+ "{direction?: leftToRight|rightToLeft, border?: {weight?, color?, tint?, type?, gapColor?, gapTint?}, spaceBefore?, spaceAfter?, headerRows?, footerRows?, repeatHeader?, repeatFooter?, altRows?: {first, firstColor, firstTint, next, nextColor, nextTint, skipFirst, skipLast} | null, altCols?: … | null}",in_table,options),@@ -606,29 +615,174 @@ fn unmerge(s: &mut Session, p: &Value) -> Result<Value> {})}-fn parse_stroke(v: &Value, mut base: CellStroke) -> CellStroke {- if let Some(w) = v.get("weight").and_then(Value::as_f64) {- base.weight = w.max(0.0);+/// Cell edges chosen for a stroke edit: the target range's four outer sides (physical left and+/// right) and the lines between its rows and columns.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+struct EdgeSel {+ top: bool,+ left: bool,+ bottom: bool,+ right: bool,+ inner_h: bool,+ inner_v: bool,+}++impl EdgeSel {+ const ALL: EdgeSel = EdgeSel { top: true, left: true, bottom: true, right: true, inner_h: true, inner_v: true };++ fn parse(v: Option<&Value>, cmd: &str) -> Result<EdgeSel> {+ let names: Vec<&Value> = match v {+ None | Some(Value::Null) => return Ok(EdgeSel::ALL),+ Some(Value::Array(a)) => a.iter().collect(),+ Some(v) => vec![v],+ };+ let mut e = EdgeSel::default();+ for n in names {+ match n.as_str() {+ Some("all") => e = EdgeSel::ALL,+ Some("outer") => (e.top, e.left, e.bottom, e.right) = (true, true, true, true),+ Some("inner") => (e.inner_h, e.inner_v) = (true, true),+ Some("top") => e.top = true,+ Some("left") => e.left = true,+ Some("bottom") => e.bottom = true,+ Some("right") => e.right = true,+ Some("innerHorizontal") => e.inner_h = true,+ Some("innerVertical") => e.inner_v = true,+ _ => return Err(bad(cmd, format!("unknown edge {n}; use all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical"))),+ }+ }+ if e == EdgeSel::default() {+ return Err(bad(cmd, "no edges chosen"));+ }+ Ok(e)+ }++ /// Which sides (top, left, bottom, right) of the cell at `(r, c)` with `spans` are chosen+ /// within `rg`. Left and right are physical sides, also in RTL tables.+ fn sides(&self, rg: CellRange, (r, c): (usize, usize), spans: (u32, u32), rtl: bool) -> [bool; 4] {+ let last_row = r.saturating_add((spans.0.max(1) - 1) as usize);+ let last_col = c.saturating_add((spans.1.max(1) - 1) as usize);+ let (start, end) = (c <= rg.c0, last_col >= rg.c1);+ let (left_outer, right_outer) = if rtl { (end, start) } else { (start, end) };+ [+ if r <= rg.r0 { self.top } else { self.inner_h },+ if left_outer { self.left } else { self.inner_v },+ if last_row >= rg.r1 { self.bottom } else { self.inner_h },+ if right_outer { self.right } else { self.inner_v },+ ]}- if let Some(c) = color_param(v, "color") {- base.color = c;+}++/// A finite number in `lo..=hi`, or an error naming `key`.+fn num_in(v: &Value, key: &str, lo: f64, hi: f64, cmd: &str) -> Result<Option<f64>> {+ match v.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(x) => match x.as_f64() {+ Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(Some(n)),+ _ => Err(bad(cmd, format!("{key} must be a number from {lo} to {hi}"))),+ },}- if let Some(t) = v.get("tint").and_then(Value::as_f64) {- base.tint = t.clamp(0.0, 1.0) as f32;+}++/// A swatch of the document (or [None]), or an error naming `key`.+fn swatch_in(doc: &Document, v: &Value, keys: &[&str], cmd: &str) -> Result<Option<String>> {+ let Some((key, x)) = keys.iter().find_map(|k| v.get(*k).filter(|x| !x.is_null()).map(|x| (*k, x))) else { return Ok(None) };+ let name = x.as_str().ok_or_else(|| bad(cmd, format!("{key} must be a swatch name")))?;+ if name != designcraft_color::swatch::NONE && doc.swatch(name).is_none() {+ return Err(bad(cmd, format!("no swatch `{name}`")));}- match str_param(v, "type") {- Some("dashed") => base.kind = StrokeType::Dashed { pattern: vec![base.weight.max(1.0) * 3.0, base.weight.max(1.0) * 2.0] },- Some("dotted") => base.kind = StrokeType::Dotted,- Some("solid") => base.kind = StrokeType::Solid,- _ => {}+ Ok(Some(name.to_string()))+}++/// The cell stroke type names of `type`.+const CELL_STROKE_TYPES: &[&str] =+ &["solid", "dashed", "dotted", "thickThin", "thinThick", "thinThin", "thickThick", "thinThickThin", "thickThinThick", "wavy", "hashed"];++/// The attributes a stroke edit sets. A plain `"dashed"` gets a pattern scaled to the+/// resulting weight of each edge.+struct StrokeEdit {+ attrs: designcraft_doc::CellStrokeAttrs,+ scaled_dashes: bool,+}++impl StrokeEdit {+ fn parse(doc: &Document, v: &Value, cmd: &str) -> Result<StrokeEdit> {+ if !v.is_object() {+ return Err(bad(cmd, "stroke must be an object"));+ }+ let mut attrs = designcraft_doc::CellStrokeAttrs {+ weight: num_in(v, "weight", 0.0, 1000.0, cmd)?,+ color: swatch_in(doc, v, &["color"], cmd)?,+ tint: num_in(v, "tint", 0.0, 1.0, cmd)?.map(|t| t as f32),+ gap_color: swatch_in(doc, v, &["gapColor", "gapSwatch"], cmd)?,+ gap_tint: num_in(v, "gapTint", 0.0, 1.0, cmd)?.map(|t| t as f32),+ kind: None,+ };+ let mut scaled_dashes = false;+ match v.get("type") {+ None | Some(Value::Null) => {}+ Some(Value::String(name)) if name == "dashed" => {+ scaled_dashes = true;+ attrs.kind = Some(StrokeType::Dashed { pattern: Vec::new() });+ }+ Some(Value::String(name)) if CELL_STROKE_TYPES.contains(&name.as_str()) => {+ attrs.kind = Some(serde_json::from_value(json!({"kind": name})).map_err(|e| bad(cmd, e.to_string()))?);+ }+ Some(t @ Value::Object(_)) => {+ 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::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"));+ }+ StrokeType::Style { name } if !doc.stroke_styles.iter().any(|s| s.name == *name) => {+ return Err(bad(cmd, format!("no stroke style `{name}`")));+ }+ _ => {}+ }+ attrs.kind = Some(kind);+ }+ Some(other) => return Err(bad(cmd, format!("unknown stroke type {other}"))),+ }+ Ok(StrokeEdit { attrs, scaled_dashes })+ }++ fn apply(&self, mut base: CellStroke) -> CellStroke {+ self.attrs.apply_to(&mut base);+ if self.scaled_dashes {+ let w = base.weight.max(1.0);+ base.kind = StrokeType::Dashed { pattern: vec![w * 3.0, w * 2.0] };+ }+ base+ }+}++/// 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)],}- base+}++/// 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 }]}fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {- let g = target(s, p, "table.setCell")?;- let fill = color_param(p, "fill");- let tint = p.get("tint").and_then(Value::as_f64).map(|t| t.clamp(0.0, 1.0) as f32);+ const ID: &str = "table.setCell";+ let g = target(s, p, ID)?;+ let doc = &s.doc()?.doc;+ let fill = swatch_in(doc, p, &["fill"], ID)?;+ let tint = num_in(p, "tint", 0.0, 1.0, ID)?.map(|t| t as f32);let insets: Option<[f64; 4]> = match p.get("insets") {Some(Value::Number(n)) => n.as_f64().map(|v| [v.max(0.0); 4]),Some(Value::Array(a)) if a.len() == 4 => {@@ -642,12 +796,15 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {Some("center") => Some(VerticalJustification::Center),Some("bottom") => Some(VerticalJustification::Bottom),Some("justify") => Some(VerticalJustification::Justify),- Some(o) => return Err(bad("table.setCell", format!("unknown vj `{o}`"))),+ Some(o) => return Err(bad(ID, format!("unknown vj `{o}`"))),None => None,};let text = str_param(p, "text").map(str::to_string);- let stroke = p.get("stroke").cloned();- edit_table(s, &g, "table.setCell", |t| {+ let stroke = match p.get("stroke").filter(|v| !v.is_null()) {+ Some(sv) => Some((StrokeEdit::parse(doc, sv, ID)?, EdgeSel::parse(sv.get("edges"), ID)?)),+ None => None,+ };+ edit_table(s, &g, ID, |t| {let owners = t.owners();let nc = t.ncols();let nr = t.nrows();@@ -658,9 +815,13 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {let rg = g.range;for r in rg.r0..=rg.r1 {for c in rg.c0..=rg.c1 {- if owners[r * nc + c] != (r, c) {+ 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();@@ -678,24 +839,12 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {let len = cell.text.len();cell.text.replace(0..len, tx);}- if let Some(sv) = &stroke {- let edges = str_param(sv, "edges").unwrap_or("all");- 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);- let perimeter = [r == 0, if rtl { at_right == nc } else { c == 0 }, at_bottom == nr, if rtl { c == 0 } else { at_right == nc }];- for (i, on) in [- ("top", r == rg.r0),- ("left", if rtl { at_right.saturating_sub(1) == rg.c1 } else { c == rg.c0 }),- ("bottom", at_bottom.saturating_sub(1) == rg.r1),- ("right", if rtl { c == rg.c0 } else { at_right.saturating_sub(1) == rg.c1 }),- ]- .iter()- .enumerate()- .map(|(i, (name, outer))| (i, edges == "all" || edges == *name || (edges == "outer" && *outer) || (edges == "inner" && !*outer)))- {+ 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 = if perimeter[i] && !cell.border_overrides[i] { &borders[i] } else { &cell.strokes[i] };- cell.strokes[i] = parse_stroke(sv, base.clone());+ let base = shown_edge(cell, i, on_perimeter[i], &borders).clone();+ cell.strokes[i] = edit.apply(base);cell.stroke_defined[i] = true;cell.stroke_priorities[i] = priority;cell.border_overrides[i] = true;@@ -706,29 +855,27 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {}// Keep both copies of unmerged shared boundaries consistent. Left/right name// physical sides, also in RTL tables.- if let Some(sv) = &stroke {- let edges = str_param(sv, "edges").unwrap_or("all");- let selected = |side: &str| edges == "all" || edges == "outer" || edges == side;- if selected("top")+ if let Some((_, edges)) = &stroke {+ if edges.top&& let Some(row) = rg.r0.checked_sub(1){for c in rg.c0..=rg.c1 {mirror_cell_edge(t, &owners, (rg.r0, c), 0, (row, c), 2);}}- if selected("bottom") && rg.r1.saturating_add(1) < nr {+ if edges.bottom && rg.r1.saturating_add(1) < nr {for c in rg.c0..=rg.c1 {mirror_cell_edge(t, &owners, (rg.r1, c), 2, (rg.r1 + 1, c), 0);}}- if selected(if rtl { "right" } else { "left" })+ if (if rtl { edges.right } else { edges.left })&& let Some(col) = rg.c0.checked_sub(1){for r in rg.r0..=rg.r1 {mirror_cell_edge(t, &owners, (r, rg.c0), if rtl { 3 } else { 1 }, (r, col), if rtl { 1 } else { 3 });}}- if selected(if rtl { "left" } else { "right" }) && rg.c1.saturating_add(1) < nc {+ if (if rtl { edges.left } else { edges.right }) && rg.c1.saturating_add(1) < nc {for r in rg.r0..=rg.r1 {mirror_cell_edge(t, &owners, (r, rg.c1), if rtl { 1 } else { 3 }, (r, rg.c1 + 1), if rtl { 3 } else { 1 });}@@ -738,6 +885,62 @@ fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {})}+/// The shown stroke attributes of the chosen edges of the target cells, and their fill; values+/// that differ are null.+fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "table.getCellStroke";+ let g = target(s, p, ID)?;+ let edges = EdgeSel::parse(p.get("edges"), ID)?;+ let st = s.doc()?;+ let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;+ 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 {+ None => *slot = Some(v),+ Some(cur) if *cur != v => *cur = Value::Null,+ _ => {}+ }+ }+ 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;+ 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)) {+ continue;+ }+ 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);+ }+ }+ }+ }+ let mut out = serde_json::Map::new();+ for (k, v) in keys.iter().zip(stroke) {+ out.insert((*k).into(), v.unwrap_or(Value::Null));+ }+ 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));+ Ok(Value::Object(out))+}+/// Only saturation needs rebasing. Preserve every distinct priority's order and keep/// zero/negative priorities untouched; the work is bounded by the table's edges.fn next_cell_stroke_priority(t: &mut Table) -> i32 {@@ -907,14 +1110,18 @@ fn parse_alt(v: &Value) -> Option<AltFills> {fn options(s: &mut Session, p: &Value) -> Result<Value> {let g = target(s, p, "table.options")?;+ let border = match p.get("border").filter(|v| !v.is_null()) {+ Some(b) => Some(StrokeEdit::parse(&s.doc()?.doc, b, "table.options")?),+ None => None,+ };let p = p.clone();edit_table(s, &g, "table.options", |t| {let o = &mut t.options;if let Some(v) = p.get("direction") {o.direction = serde_json::from_value(v.clone()).map_err(|e| bad("table.options", e.to_string()))?;}- if let Some(b) = p.get("border") {- o.border = parse_stroke(b, o.border.clone());+ if let Some(b) = &border {+ o.border = b.apply(o.border.clone());o.borders = Default::default();}o.space_before = f64_or(&p, "spaceBefore", o.space_before);diff --git a/crates/engine/src/tests_table.rs b/crates/engine/src/tests_table.rsindex 45861347d..04620a402 100644--- a/crates/engine/src/tests_table.rs+++ b/crates/engine/src/tests_table.rs@@ -399,3 +399,41 @@ fn editing_beside_a_merged_cell_only_changes_the_selected_edge_segment() {}}}++#[test]+fn cell_stroke_gap_colour_on_inner_horizontal_edges_of_a_selection_undoes_and_saves() {+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ s.execute("table.select", &json!({"what": "table"})).unwrap();+ let before = table_for(&s, sid, tid).clone();+ let cyan = "C=100 M=0 Y=0 K=0";+ let stroke = json!({"weight": 3, "type": "dashed", "gapColor": cyan, "gapTint": 0.5, "edges": ["innerHorizontal"]});+ s.execute("table.setCell", &json!({ "stroke": stroke })).unwrap();+ let t = table_for(&s, sid, tid).clone();+ let edge = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].clone();+ for (r, c, side) in [(0, 0, 2), (0, 1, 2), (1, 0, 0), (1, 1, 0)] {+ let e = edge(r, c, side);+ assert_eq!((e.weight, e.gap_color.as_str(), e.gap_tint), (3.0, cyan, 0.5), "inner horizontal {r},{c} side {side}");+ assert!(matches!(e.kind, doc::StrokeType::Dashed { .. }));+ }+ for (r, c, side) in [(0, 0, 0), (0, 0, 1), (0, 0, 3), (1, 1, 2), (1, 1, 1), (0, 1, 3)] {+ assert_eq!(&edge(r, c, side), &before.cell(r, c).unwrap().strokes[side], "{r},{c} side {side} keeps its stroke");+ }+ // 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)));+ let all = s.execute("table.getCellStroke", &json!({})).unwrap();+ assert!(all["weight"].is_null() && all["gapColor"].is_null());+ // Bad values are errors and change nothing.+ for bad in+ [json!({"gapTint": 2}), json!({"gapColor": "No Such Swatch"}), json!({"weight": -1}), json!({"type": "zigzag"}), json!({"edges": "middle"})]+ {+ assert!(s.execute("table.setCell", &json!({ "stroke": bad })).is_err(), "{bad}");+ assert_eq!(table_for(&s, sid, tid), &t);+ }+ let bytes = crate::cmd::file_bytes(&s.doc().unwrap().doc);+ let back = crate::cmd::file_from(&bytes).unwrap();+ assert_eq!(back.story(doc::StoryId(sid)).unwrap().tables.get(&tid).unwrap().as_ref(), &t);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(table_for(&s, sid, tid), &before);+}diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex 9d73562b9..8afcf714f 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -2192,6 +2192,10 @@ impl<'a> Ex<'a> {el.set(&format!("{prefix}StrokeColor"), self.sw(&s.color));el.set(&format!("{prefix}StrokeTint"), pct(s.tint as f64));el.set(&format!("{prefix}StrokeType"), names::stroke_type_out(&s.kind));+ if s.gap_color != designcraft_color::swatch::NONE || s.gap_tint != 1.0 {+ el.set(&format!("{prefix}StrokeGapColor"), self.sw(&s.gap_color));+ el.set(&format!("{prefix}StrokeGapTint"), pct(s.gap_tint as f64));+ }}fn partial_cell_stroke_attrs(&self, el: &mut El, prefix: &str, attrs: &designcraft_doc::CellStrokeAttrs) {@@ -2207,6 +2211,12 @@ impl<'a> Ex<'a> {if let Some(value) = &attrs.kind {el.set(&format!("{prefix}StrokeType"), names::stroke_type_out(value));}+ if let Some(value) = &attrs.gap_color {+ el.set(&format!("{prefix}StrokeGapColor"), self.sw(value));+ }+ if let Some(value) = attrs.gap_tint {+ el.set(&format!("{prefix}StrokeGapTint"), pct(value as f64));+ }}fn partial_alt_fill_attrs(&self, el: &mut El, kind: &str, attrs: &designcraft_doc::AltFillsAttrs) {diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex d85d9ee02..1ba4decf7 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -26,7 +26,15 @@ fn uniform_cell_stroke(edges: &[designcraft_doc::CellStrokeAttrs; 4]) -> Option<if edges.iter().any(|edge| edge != first) {return None;}- Some(designcraft_doc::CellStroke { weight: first.weight?, color: first.color.clone()?, tint: first.tint?, kind: first.kind.clone()? })+ let mut stroke = designcraft_doc::CellStroke {+ weight: first.weight?,+ color: first.color.clone()?,+ tint: first.tint?,+ kind: first.kind.clone()?,+ ..Default::default()+ };+ first.apply_to(&mut stroke);+ Some(stroke)}/// Import an IDML package. Linked images are read from disk when available (not on wasm).@@ -1427,6 +1435,8 @@ impl<'r> Importer<'r> {color: el.prop(&format!("{prefix}StrokeColor")).map(|v| self.swatch_ref(&v)),tint: tint(el.num(&format!("{prefix}StrokeTint"))),kind: el.prop(&format!("{prefix}StrokeType")).map(|v| names::stroke_type_in(&v)),+ gap_color: el.prop(&format!("{prefix}StrokeGapColor")).map(|v| self.swatch_ref(&v)),+ gap_tint: tint(el.num(&format!("{prefix}StrokeGapTint"))),}}diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 7b747587a..3d52def24 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -1399,3 +1399,32 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {check(&d);check(&import_idml(&export_idml(&d)).unwrap());}++#[test]+fn cell_edge_gap_colours_and_tints_import_and_round_trip_per_edge() {+ let styles = CASCADE_STYLES.replace(+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed""#,+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed" TopEdgeStrokeGapColor="Color/Paper" TopEdgeStrokeGapTint="60" BottomEdgeStrokeGapColor="Color/Brand""#,+ );+ let story = CASCADE_STORY.replace(+ r#"<Cell Name="1:1">"#,+ r#"<Cell Name="1:1" LeftEdgeStrokeType="StrokeStyle/$ID/Dotted" LeftEdgeStrokeGapColor="Color/Brand" LeftEdgeStrokeGapTint="30" RightEdgeStrokeGapColor="Color/Paper">"#,+ );+ let gaps = |d: &Document| {+ let base = d.styles.cell.iter().find(|s| s.name == "Base").unwrap().strokes.clone();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let cell = table.cell(1, 1).unwrap().strokes.clone();+ (base.map(|e| (e.gap_color, e.gap_tint)), cell.map(|e| (e.gap_color, e.gap_tint)))+ };+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ d.check().unwrap();+ let (style, cell) = gaps(&d);+ assert_eq!(style[0], (Some("[Paper]".to_string()), Some(0.6)));+ assert_eq!(style[2], (Some("Brand".to_string()), None));+ assert_eq!((style[1].clone(), style[3].clone()), ((None, None), (None, None)));+ assert_eq!(cell[1], ("Brand".to_string(), 0.3), "left");+ assert_eq!(cell[3], ("[Paper]".to_string(), 1.0), "right");+ assert_eq!(cell[0].0, "[Paper]", "the Base style's top gap colour reaches the cell");+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(gaps(&back), (style, cell));+}diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rsindex bf59efded..bcc75b28e 100644--- a/crates/pdf/src/text.rs+++ b/crates/pdf/src/text.rs@@ -212,7 +212,37 @@ impl Exporter<'_> {for seg in &t.strokes {let st = &seg.stroke;let Some(col) = self.swatch_color(&st.color, st.tint) else { continue };- let (cap, dash) = match &st.kind {+ let kind = self.doc.stroke_kind(&st.kind);+ let mut bp = BezPath::new();+ bp.move_to(seg.a);+ bp.line_to(seg.b);+ let Some(p) = to_path(&bp) 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+ && let Some(gap) = self.swatch_color(&st.gap_color, st.gap_tint)+ {+ s.set_fill(None);+ s.set_stroke(Some(Stroke {+ paint: gap.into(),+ width: st.weight as f32,+ line_cap: krilla::paint::LineCap::Butt,+ ..Default::default()+ }));+ s.draw_path(&p);+ 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)+ && let Some(op) = to_path(&o)+ {+ s.set_stroke(None);+ s.set_fill(Some(solid_fill(col, 1.0)));+ s.draw_path(&op);+ s.set_fill(None);+ continue;+ }+ let (cap, dash) = match &kind {designcraft_doc::StrokeType::Dashed { pattern } if pattern.iter().any(|v| *v > 0.0) => {let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();if pat.len() % 2 == 1 {@@ -225,10 +255,6 @@ impl Exporter<'_> {}_ => (krilla::paint::LineCap::Square, None),};- let mut bp = BezPath::new();- bp.move_to(seg.a);- bp.line_to(seg.b);- let Some(p) = to_path(&bp) else { continue };s.set_fill(None);s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() }));s.draw_path(&p);diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex c1b288def..a9a7b09b2 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -1483,6 +1483,36 @@ mod tests {assert!(p[0] > 240 && p[1] < 200, "pink on screen: {p:?}");}+ #[test]+ fn table_edges_paint_gap_colour_between_dashes_and_stripes() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap();+ let mut t = designcraft_doc::Table::new(1, 1, 1, 0, 0, 200.0);+ t.rows[0].height = 60.0;+ t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly;+ let gap = |kind| designcraft_doc::CellStroke { weight: 8.0, kind, gap_color: "C=100 M=0 Y=0 K=0".into(), ..Default::default() };+ let cell = t.cell_mut(0, 0).unwrap();+ cell.strokes[0] = gap(designcraft_doc::StrokeType::Dashed { pattern: vec![12.0, 6.0] });+ cell.strokes[2] = gap(designcraft_doc::StrokeType::ThickThin);+ cell.border_overrides = [true; 4];+ cell.stroke_defined = [true; 4];+ d.story_mut(sid).unwrap().insert_table(0, t);+ let cache = Cache::new();+ let rect = cache.get(&d, sid, None).frames[0].tables[0].cell(0, 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 && p[2] < 80;+ let cyan = |p: [u8; 4]| p[0] < 80 && p[2] > 150;+ let y = rect.y0.round() as u32;+ let (dash, space) = (img.pixel((rect.x0 + 6.0) as u32, y), img.pixel((rect.x0 + 15.0) as u32, y));+ assert!(ink(dash), "dash {dash:?}");+ assert!(cyan(space), "gap {space:?}");+ let column: Vec<_> = (rect.y1 as u32 - 5..=rect.y1 as u32 + 5).map(|y| img.pixel(rect.center().x as u32, y)).collect();+ assert!(column.iter().any(|p| ink(*p)) && column.iter().any(|p| cyan(*p)), "stripes and gap: {column:?}");+ }+#[test]fn renders_tables() {let mut d = Document::new(&NewDocument::default());diff --git a/crates/render/src/text.rs b/crates/render/src/text.rsindex 734ec275e..7c4420727 100644--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@ -447,22 +447,37 @@ impl Renderer {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 };+ let kind = doc.stroke_kind(&s.stroke.kind);+ let line = kurbo::Line::new(s.a, s.b).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.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));+ // Stripes, wavy and hash types are fills along the edge.+ if let Some(o) = kind.outline(&line, s.stroke.weight, 0.05 * f.px) {+ ctx.fill_path(&o);+ continue;+ }+ ctx.set_stroke(cell_stroke(&kind, s.stroke.weight));+ ctx.stroke_path(&line);}}}}-/// 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 {+/// Kurbo stroke for a table edge of a resolved stroke type.+fn cell_stroke(kind: &designcraft_doc::StrokeType, weight: f64) -> kurbo::Stroke {+ let st = kurbo::Stroke::new(weight).with_caps(kurbo::Cap::Square);+ match 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),+ designcraft_doc::StrokeType::Dotted => st.with_dashes(0.0, [0.0, weight * 2.0]).with_caps(kurbo::Cap::Round),_ => st,}}