diff --git a/ROADMAP.md b/ROADMAP.md index ba858225..3a545452 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -136,7 +136,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two straight sides meet at an anchor. Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Design, Column and Marker artwork remain open. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. - **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked. - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. @@ -193,7 +193,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (artboard panel/tool, Trim View, middle-button pan, print tiling and the status bar's artboard navigator done; multiple windows, presentation polish) | 🟡 | 15–25 | -| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (13 presets, 18 ms/1k² image; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, regenerate in place) done; graph Design/Column/Marker designs pending | 6–10 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (13 presets, 18 ms/1k² image; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; graph Design/Column/Marker designs pending | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed), workspaces, a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8); an experimental, unsupported Windows 7 x64 portable OpenGL build (not verified by maintainers); accessibility and broader Windows/Linux packaging/QA pending | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance) | ⬜ | 60–90 | @@ -226,7 +226,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 | -| Image Trace, graphs, image tools | 3 | 72% | graph Design/Column/Marker, Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | +| Image Trace, graphs, image tools | 3 | 72% | graph Design/Column/Marker artwork (a series' fill and stroke persist through regenerate and save), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812) | 2–4 | diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 96bcf6b1..0ef760f9 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -64,12 +64,29 @@ impl GraphKind { } } +/// The fill and stroke captured from one series' generated marks. An absent paint keeps whatever +/// the generator draws for that part (greyscale for a series fill, the part's own stroke otherwise). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct SeriesPaint { + #[serde(skip_serializing_if = "Option::is_none")] + pub fill: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub stroke: Option, + /// Stroke weight in points, kept with [`Self::stroke`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub stroke_width: Option, +} + /// Graph data and options. `rows` are categories (one per row of the Graph Data window), each /// holding one value per series; `series` are the legend labels (the first row of the window). /// Scatter graphs read each series as (y, x) column pairs, like Illustrator. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct GraphSpec { + /// Paint taken from the series' marks (Group Selection). One entry per series index; missing + /// entries keep the generator's own fill and stroke. + pub series_paints: Vec, pub kind: GraphKind, /// The plot rectangle (the area the graph tool dragged), document points. pub rect: Rect, @@ -97,6 +114,7 @@ pub struct GraphSpec { impl Default for GraphSpec { fn default() -> Self { Self { + series_paints: vec![], kind: GraphKind::Column, rect: Rect::new(0.0, 0.0, 200.0, 150.0), series: vec![], diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f98873c1..a574feb0 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -65,7 +65,7 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use corners::LiveCorners; -pub use graph::{GraphKind, GraphSpec}; +pub use graph::{GraphKind, GraphSpec, SeriesPaint}; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; pub use live::{BlendOrientation, BlendSpacing, BlendSpec, EnvelopeKind, GradientMesh, MeshPoint}; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 508a0e28..48d7fc7b 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -528,6 +528,10 @@ pub struct Node { /// Graph object: the group's children are generated from this spec (Object → Graph). #[serde(default, skip_serializing_if = "Option::is_none")] pub graph: Option>, + /// Index of the graph series this generated group belongs to. Axes, the legend and other + /// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub series_index: Option, /// Editable Shaper composition; the original art is retained in its source child. #[serde(default, skip_serializing_if = "Option::is_none")] pub shaper: Option>, @@ -595,6 +599,7 @@ impl Node { trace: None, wrap: None, graph: None, + series_index: None, shaper: None, kind, graphic_style: None, diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index a83cdde4..ff48b838 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -318,7 +318,22 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { /// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters). +/// Nothing targeted is not an edit. pub(crate) fn edit_items( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + cmd: &str, + label: &str, + fill: bool, + f: impl FnMut(&mut Node, Option) -> Result<()>, +) -> Result<()> { + edit_items_then(s, ids, item, cmd, label, fill, f, |_, _| Ok(())) +} + +/// [`edit_items`], then `after` on the ids `f` changed, inside the same undo step. +#[allow(clippy::too_many_arguments)] +pub(crate) fn edit_items_then( s: &mut Session, ids: &[NodeId], item: ItemTarget, @@ -326,17 +341,20 @@ pub(crate) fn edit_items( label: &str, fill: bool, mut f: impl FnMut(&mut Node, Option) -> Result<()>, + mut after: impl FnMut(&mut vectorcraft_doc::Document, &[NodeId]) -> Result<()>, ) -> Result<()> { if ids.is_empty() { return Ok(()); } s.edit(label, |d, _| { + let mut changed = Vec::new(); for id in ids { let Some(n) = d.node_mut(*id) else { continue }; let index = item.resolve(&n.appearance, fill, cmd)?; f(n, index)?; + changed.push(*id); } - Ok(()) + after(d, &changed) }) } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index c7ad8e23..9a69d357 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -131,11 +131,26 @@ fn fmt_value(v: f64) -> String { // ---------- generation ---------- -/// Series colours: black, then greys (Illustrator's graphs start in greyscale too). -fn series_paint(i: usize) -> Paint { +/// Series colours: black, then greys (graphs start in greyscale). +fn default_series_color(i: usize) -> Color { const LEVELS: [f32; 8] = [0.0, 0.55, 0.8, 0.3, 0.68, 0.15, 0.9, 0.42]; let l = LEVELS[i % LEVELS.len()]; - Paint::solid(Color::rgb(l, l, l)) + Color::rgb(l, l, l) +} + +fn default_series_paint(i: usize) -> Paint { + Paint::solid(default_series_color(i)) +} + +/// Fill and stroke for one generated mark of series `i`. A stored fill is used only where the +/// generator paints with the series colour (`series_fill`). A stored stroke replaces that part's +/// own stroke, so a column's stroke stays a stroke and a line's markers do not repaint its line. +fn series_marks(g: &GraphSpec, i: usize, series_fill: bool, stroke: Paint, width: f64) -> (Paint, Paint, f64) { + let slot = g.series_paints.get(i); + let fill = if series_fill { slot.and_then(|p| p.fill.clone()).unwrap_or_else(|| default_series_paint(i)) } else { Paint::None }; + let stroke = slot.and_then(|p| p.stroke.clone()).unwrap_or(stroke); + let width = if slot.is_some_and(|p| p.stroke.is_some()) { slot.and_then(|p| p.stroke_width).unwrap_or(width) } else { width }; + (fill, stroke, width) } const LABEL_SIZE: f64 = 9.0; @@ -177,6 +192,14 @@ impl Gen<'_> { g.name = Some(name.into()); Arc::new(g) } + /// A series group. Empty series are omitted by the caller; the index is stored on the group + /// so later paint edits find the series without counting siblings. + fn series(&mut self, name: &str, index: usize, children: Vec>) -> Arc { + let mut g = Node::group(self.d.alloc_id(), children); + g.name = Some(name.into()); + g.series_index = u32::try_from(index).ok(); + Arc::new(g) + } } fn polyline(pts: &[Point], closed: bool) -> PathData { @@ -200,6 +223,7 @@ fn marker(p: Point, s: f64) -> PathData { /// Build the graph's children. fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { + let mark = |i: usize, series_fill: bool, stroke: Paint, width: f64| series_marks(g, i, series_fill, stroke, width); let mut b = Gen { d, out: vec![] }; let r = g.rect; let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).max(1); @@ -231,7 +255,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { bp.line_to(centre + vectorcraft_geom::Vec2::new(a0.cos(), a0.sin()) * rad); arc.to_cubic_beziers(0.1, |p1, p2, p| bp.curve_to(p1, p2, p)); bp.close_path(); - let n = b.path(PathData::from_bezpath(&bp), series_paint(s), Paint::solid(Color::WHITE), 0.5); + let (fill, stroke, w) = mark(s, true, Paint::solid(Color::WHITE), 0.5); + let n = b.path(PathData::from_bezpath(&bp), fill, stroke, w); items.push(n); a0 += sweep; } @@ -268,9 +293,11 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { b.out.push(ax); for (s, items) in series.iter_mut().enumerate() { let pts: Vec = (0..ncat).map(|c| at(c, val(c, s))).collect(); - items.push(b.path(polyline(&pts, true), Paint::None, series_paint(s), 1.0)); + let (fill, stroke, w) = mark(s, false, default_series_paint(s), 1.0); + items.push(b.path(polyline(&pts, true), fill, stroke, w)); for p in pts { - items.push(b.path(marker(p, 4.0), series_paint(s), Paint::None, 0.0)); + let (fill, stroke, w) = mark(s, true, Paint::None, 0.0); + items.push(b.path(marker(p, 4.0), fill, stroke, w)); } } } @@ -359,11 +386,13 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { let pts: Vec = (0..ncat).map(|c| Point::new(r.x0 + (val(c, s + 1) - xl) / (xh - xl) * r.width(), vpos(val(c, s)))).collect(); if g.connect_points && pts.len() > 1 { - series[si].push(b.path(polyline(&pts, false), Paint::None, series_paint(si), 1.0)); + let (fill, stroke, w) = mark(si, false, default_series_paint(si), 1.0); + series[si].push(b.path(polyline(&pts, false), fill, stroke, w)); } if g.mark_points { for p in &pts { - series[si].push(b.path(marker(*p, 5.0), series_paint(si), Paint::None, 0.0)); + let (fill, stroke, w) = mark(si, true, Paint::None, 0.0); + series[si].push(b.path(marker(*p, 5.0), fill, stroke, w)); } } } @@ -385,7 +414,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { } else { Rect::new(a, v0.min(v1), a + bar, v0.max(v1)) }; - items.push(b.path(shapes::rectangle(rect), series_paint(s), Paint::None, 0.0)); + let (fill, stroke, w) = mark(s, true, Paint::None, 0.0); + items.push(b.path(shapes::rectangle(rect), fill, stroke, w)); } } } @@ -405,7 +435,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { } else { Rect::new(a, v0.min(v1), a + bar, v0.max(v1)) }; - items.push(b.path(shapes::rectangle(rect), series_paint(s), Paint::solid(Color::WHITE), 0.25)); + let (fill, stroke, w) = mark(s, true, Paint::solid(Color::WHITE), 0.25); + items.push(b.path(shapes::rectangle(rect), fill, stroke, w)); } } } @@ -413,11 +444,13 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { for (s, items) in series.iter_mut().enumerate() { let pts: Vec = (0..ncat).map(|c| Point::new(cat_mid(c), vpos(val(c, s)))).collect(); if g.connect_points && pts.len() > 1 { - items.push(b.path(polyline(&pts, false), Paint::None, series_paint(s), 1.0)); + let (fill, stroke, w) = mark(s, false, default_series_paint(s), 1.0); + items.push(b.path(polyline(&pts, false), fill, stroke, w)); } if g.mark_points { for p in &pts { - items.push(b.path(marker(*p, 5.0), series_paint(s), Paint::None, 0.0)); + let (fill, stroke, w) = mark(s, true, Paint::None, 0.0); + items.push(b.path(marker(*p, 5.0), fill, stroke, w)); } } } @@ -429,7 +462,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { let above: Vec = (0..ncat).map(|c| below[c] + val(c, s)).collect(); let mut pts: Vec = (0..ncat).map(|c| Point::new(cat_mid(c), vpos(above[c]))).collect(); pts.extend((0..ncat).rev().map(|c| Point::new(cat_mid(c), vpos(below[c])))); - items.push(b.path(polyline(&pts, true), series_paint(s), Paint::solid(Color::WHITE), 0.25)); + let (fill, stroke, w) = mark(s, true, Paint::solid(Color::WHITE), 0.25); + items.push(b.path(polyline(&pts, true), fill, stroke, w)); below = above; } } @@ -448,16 +482,18 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec> { continue; } let y = r.y0 + s as f64 * (LABEL_SIZE * 1.8); - items.push(b.path(shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), series_paint(s), Paint::None, 0.0)); + let (fill, stroke, w) = mark(s, true, Paint::None, 0.0); + items.push(b.path(shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), fill, stroke, w)); labels.push(b.text(Point::new(x + 12.0, y + 7.5), &label, Justify::Left)); } } for (s, items) in series.into_iter().enumerate() { - if !items.is_empty() { - let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1)); - let grp = b.group(&name, items); - b.out.push(grp); + if items.is_empty() { + continue; } + let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1)); + let grp = b.series(&name, s, items); + b.out.push(grp); } if !labels.is_empty() { let grp = b.group("Legend", labels); @@ -540,6 +576,82 @@ fn spec_of(s: &Session, id: NodeId) -> Result { s.doc()?.doc.node(id).and_then(|n| n.graph.as_deref().cloned()).ok_or(EngineError::NoNode(id)) } +/// The generated series group containing `id`: the graph, the group, and the series index stored +/// on that group. Axes, the legend and a series that was not generated are not series groups. +fn series_group(doc: &Document, id: NodeId) -> Option<(NodeId, NodeId, usize)> { + let mut child = id; + let mut parent = doc.parent_of(child); + while let Some(parent_id) = parent { + let node = doc.node(parent_id)?; + if node.graph.is_some() { + let group = node.children()?.iter().find(|n| n.id == child)?; + let index = usize::try_from(group.series_index?).ok()?; + return Some((parent_id, child, index)); + } + child = parent_id; + parent = doc.parent_of(child); + } + None +} + +/// Group Selection on a graph series targets its constituent marks and legend swatch, not a +/// group-level appearance which the generated art does not inherit. +pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec { + fn paths(node: &vectorcraft_doc::Node, out: &mut Vec) { + if matches!(node.kind, NodeKind::Path { .. }) { + out.push(node.id); + } else if let Some(children) = node.children() { + for child in children { + paths(child, out); + } + } + } + + let mut out = Vec::new(); + for id in ids { + if let Some((_, group, _)) = series_group(doc, *id) + && group == *id + && let Some(node) = doc.node(group) + { + paths(node, &mut out); + } else { + out.push(*id); + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// Copy the paint just applied to generated series art into that series' fill or stroke. Called +/// inside the same document edit, so the visible paint and future regeneration undo together. +/// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour. +pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bool) { + let captures: Vec<_> = ids + .iter() + .filter_map(|id| { + let (graph, _, index) = series_group(doc, *id)?; + let node = doc.node(*id)?; + let paint = node.appearance.paint_at(None, fill)?.clone(); + let width = (!fill).then(|| node.appearance.stroke_width()); + Some((graph, index, paint, width)) + }) + .collect(); + for (graph, index, paint, width) in captures { + let Some(spec) = doc.node_mut(graph).and_then(|n| n.graph.as_deref_mut()) else { continue }; + if spec.series_paints.len() <= index { + spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default()); + } + let Some(slot) = spec.series_paints.get_mut(index) else { continue }; + if fill { + slot.fill = Some(paint); + } else { + slot.stroke = Some(paint); + slot.stroke_width = width; + } + } +} + fn set_data(s: &mut Session, p: &Value) -> Result { let id = target(s, p, "graph.setData")?; let mut spec = spec_of(s, id)?; @@ -592,7 +704,8 @@ fn set_type(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { use serde_json::json; - use vectorcraft_doc::NodeKind; + use vectorcraft_color::Paint; + use vectorcraft_doc::{GraphKind, GraphSpec, NodeKind}; use crate::{NodeId, Session}; @@ -609,6 +722,11 @@ mod tests { n.children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).unwrap_or_else(|| panic!("no {name}")) } + /// The generated group stored for series `index`, not a sibling that happens to share its name. + fn series(n: &vectorcraft_doc::Node, index: u32) -> &vectorcraft_doc::Node { + n.children().unwrap().iter().find(|c| c.series_index == Some(index)).unwrap_or_else(|| panic!("no series {index}")) + } + #[test] fn every_graph_type_generates_series_groups() { let mut s = Session::new(); @@ -662,6 +780,208 @@ mod tests { assert!(matches!(n.kind, NodeKind::Group { .. })); } + #[test] + fn group_selection_paint_becomes_the_series_colour_and_survives_regeneration() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for ty in GraphKind::ALL { + let id = graph(&mut s, ty.id()); + let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id; + s.execute("paint.setFill", &json!({"ids": [series_id.0], "color": "#ff0000"})).unwrap(); + let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone(); + let restored: GraphSpec = serde_json::from_value(serde_json::to_value(&spec).unwrap()).unwrap(); + assert_eq!(spec, restored); + let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + assert_eq!(spec.series_paints.first().and_then(|p| p.fill.clone()), Some(red.clone()), "{ty:?}"); + let selected_group = group(s.doc().unwrap().doc.node(id).unwrap(), "2024"); + assert!(selected_group.children().unwrap().iter().all(|n| n.appearance.fill_paint() == red), "{ty:?}"); + s.execute("graph.setData", &json!({"rows": [[2, 3], [4, 5]]})).unwrap(); + s.execute("graph.setType", &json!({"type": "line"})).unwrap(); + let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap(); + assert_eq!(spec.series_paints.first().and_then(|p| p.fill.clone()), Some(red.clone()), "{ty:?}"); + let series = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap(); + assert!(series.iter().any(|n| n.appearance.fill_paint() == red), "{ty:?}"); + } + } + + #[test] + fn painting_a_series_is_one_undoable_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id; + s.execute("paint.setFill", &json!({"ids": [series_id.0], "color": "#e8573f"})).unwrap(); + assert_eq!( + s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(), + "#e8573f" + ); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints.is_empty()); + assert_eq!( + group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0].appearance.fill_paint().color(), + Some(super::default_series_color(0)) + ); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!( + s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(), + "#e8573f" + ); + } + + #[test] + fn painting_one_bar_sets_the_colour_used_by_the_whole_series_on_rebuild() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let bar = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0].id; + s.execute("paint.setFill", &json!({"ids": [bar.0], "color": "#12ab34"})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let node = s.doc().unwrap().doc.node(id).unwrap(); + let green = vectorcraft_color::Color::rgb(18.0 / 255.0, 171.0 / 255.0, 52.0 / 255.0); + assert_eq!(node.graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color), Some(green)); + assert!(group(node, "2024").children().unwrap().iter().all(|n| n.appearance.fill_paint().color() == Some(green))); + } + + #[test] + fn painting_a_line_series_stroke_sets_its_persistent_colour() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "line"); + let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id; + s.execute("paint.setStroke", &json!({"ids": [series_id.0], "color": "#3751c8"})).unwrap(); + let blue = vectorcraft_color::Color::rgb(55.0 / 255.0, 81.0 / 255.0, 200.0 / 255.0); + assert_eq!( + s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].stroke.as_ref().and_then(Paint::color), + Some(blue) + ); + assert!(s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].fill.is_none()); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + assert!( + group(s.doc().unwrap().doc.node(id).unwrap(), "2024") + .children() + .unwrap() + .iter() + .any(|n| n.appearance.stroke_paint().color() == Some(blue)) + ); + } + + #[test] + fn series_colours_survive_native_save_open_and_export() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let first = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id; + let second = group(s.doc().unwrap().doc.node(id).unwrap(), "2025").id; + s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#f00"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [second.0], "color": "#008080"})).unwrap(); + let dir = vectorcraft_testkit::temp_dir("graph-palette"); + let path = dir.join("palette.vectorcraft"); + s.execute("document.save", &json!({"path": path})).unwrap(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let paints = &s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints; + assert_eq!(paints.iter().map(|p| p.fill.as_ref().and_then(Paint::color).unwrap().to_hex()).collect::>(), vec!["#ff0000", "#008080"]); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[3, 4, 5]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let swatch = group(n, "2025").children().unwrap().last().unwrap(); + assert_eq!(swatch.appearance.fill_paint().color().unwrap().to_hex(), "#008080"); + let third = group(n, "Series 3").children().unwrap().first().unwrap(); + assert_eq!(third.appearance.fill_paint().color().unwrap().to_hex(), "#cccccc"); + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["text"].as_str().unwrap(); + assert!(svg.contains("#ff0000") && svg.contains("#008080")); + let png = dir.join("palette.png"); + s.execute("document.export", &json!({"format": "png", "path": png})).unwrap(); + let pixels = image::open(&png).unwrap().to_rgba8(); + assert!(pixels.pixels().any(|p| p.0 == [255, 0, 0, 255])); + assert!(pixels.pixels().any(|p| p.0 == [0, 128, 128, 255])); + let old: GraphSpec = serde_json::from_value(json!({"rows": [[1.0]]})).unwrap(); + assert!(old.series_paints.is_empty(), "older files keep the greyscale default"); + } + + #[test] + fn a_column_stroke_stays_a_stroke_and_a_marker_fill_does_not_recolour_its_line() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id; + s.execute("paint.setStroke", &json!({"ids": [series_id.0], "color": "#0000ff"})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone(); + let blue = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + assert_eq!(spec.series_paints[0].stroke, Some(blue.clone())); + assert!(spec.series_paints[0].fill.is_none()); + let bar = &group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0]; + assert_eq!(bar.appearance.fill_paint().color(), Some(super::default_series_color(0))); + assert_eq!(bar.appearance.stroke_paint(), blue); + + let id = graph(&mut s, "line"); + let marker = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[1].id; + s.execute("paint.setFill", &json!({"ids": [marker.0], "color": "#ff0000"})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone(); + assert!(spec.series_paints[0].stroke.is_none()); + let series = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap(); + assert_eq!(series[0].appearance.stroke_paint().color(), Some(super::default_series_color(0))); + assert_eq!(series[1].appearance.fill_paint().color(), Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))); + } + + #[test] + fn a_gradient_fill_survives_regeneration() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id; + s.execute( + "paint.setFill", + &json!({"ids": [series_id.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ) + .unwrap(); + s.execute("graph.setData", &json!({"rows": [[2, 3], [4, 5]]})).unwrap(); + let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone(); + assert!(matches!(spec.series_paints[0].fill, Some(Paint::Gradient(_)))); + let bar = &group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0]; + assert!(matches!(bar.appearance.fill_paint(), Paint::Gradient(_))); + } + + #[test] + fn a_series_named_legend_keeps_its_own_index_and_an_empty_series_is_omitted() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let csv = ",Legend,Axes\nQ1,3,2\nQ2,5,4"; + let id = NodeId(s.execute("graph.create", &json!({"type": "column", "x": 0, "y": 0, "csv": csv})).unwrap()["id"].as_u64().unwrap()); + let legend_id = { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let legend = series(n, 0); + assert_eq!(legend.name.as_deref(), Some("Legend")); + assert!(n.children().unwrap().iter().any(|c| c.name.as_deref() == Some("Legend") && c.series_index.is_none())); + assert!(n.children().unwrap().iter().any(|c| c.name.as_deref() == Some("Axes") && c.series_index.is_none())); + legend.id + }; + s.execute("paint.setFill", &json!({"ids": [legend_id.0], "color": "#ff0000"})).unwrap(); + s.execute("graph.setData", &json!({"csv": csv})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(n.graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(), "#ff0000"); + assert!(n.graph.as_ref().unwrap().series_paints.get(1).is_none_or(|p| p.fill.is_none())); + assert_eq!(series(n, 0).children().unwrap()[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000"); + assert_eq!(series(n, 1).name.as_deref(), Some("Axes")); + assert_ne!(series(n, 1).children().unwrap()[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000"); + + let id = graph(&mut s, "pie"); + s.execute("graph.setType", &json!({"id": id.0, "legend": false})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",Keep,Drop\nQ1,4,0\nQ2,2,0"})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(n.children().unwrap().iter().any(|c| c.name.as_deref() == Some("Keep"))); + assert!(n.children().unwrap().iter().all(|c| c.name.as_deref() != Some("Drop"))); + let keep = group(n, "Keep").id; + s.execute("paint.setFill", &json!({"ids": [keep.0], "color": "#00ff00"})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[8, 0], [1, 0]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(group(n, "Keep").series_index, Some(0)); + assert_eq!(n.graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(), "#00ff00"); + assert!(n.children().unwrap().iter().all(|c| c.name.as_deref() != Some("Drop"))); + } + #[test] fn csv_parsing() { let (s, c, r) = super::parse_csv("\t2024\t2025\nQ1\t1\t2\nQ2\t3\t4\n"); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 747d849d..b98c6c82 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind}; -use super::appearance::{ItemTarget, appearance_targets, edit_items, item_target}; +use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target}; use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced}; use super::*; use crate::{DocState, EngineError}; @@ -385,30 +385,44 @@ fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result