VectorCraft: An open-source, vector art tool written by scratch in pure Rust
Merge pull request #376 from Haven-King/feat/artboard-snapping
Brandon Thomas4f159b98fb18
diff --cc ROADMAP.mdindex bb3458edd,d0d0ddee1..1bc99864e--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -111,23 -109,22 +111,23 @@@ grade by behaviour against `plan/illust- **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes).- **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag).- **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout. 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.+ - **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. 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.- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type.- - **Other:** Eyedropper, Gradient annotator, Artboard, Measure, Type, Hand, Zoom, Rotate View.+ - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on), 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.- - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, and a symbol dragged onto the canvas places an instance where it is dropped.+ - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, Gradient, Eyedropper, Blend and the Liquify tools their panels or options.-- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies, the trash deletes), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.-- **Drawing aids:** Smart Guides and snapping (the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H), guides dragged out of the rulers, and Draw Normal / Behind / Inside modes.-- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard.+- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies, the trash deletes), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.- - **Drawing aids:** Smart Guides and snapping (moving, and resizing by the bounding-box handles: the dragged edges align with the other objects), guides dragged out of the rulers, and Draw Normal / Behind / Inside modes.++- **Drawing aids:** Smart Guides and snapping (moving, and resizing by the bounding-box handles: the dragged edges align with the other objects; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H), guides dragged out of the rulers, and Draw Normal / Behind / Inside modes.+- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it.- **Geometry and effects:**- - Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below.+ - Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected.- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done.-- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional Chinese covers the whole interface, Czech and Japanese every menu label (tested); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech ones from the bundled UI fonts. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.+- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional Chinese and Japanese cover the whole interface, Czech every menu label (tested); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech ones from the bundled UI fonts. The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph › Mojikumi: Line-end Punctuation Half Width (new type's default) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width, and puts a quarter em between Japanese and Latin letters or digits; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.-- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type, Gradient Mesh, Shape Builder, Live Paint (every path an edge, open lines included), Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).+- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder, Live Paint (every path an edge, open lines included), Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).- **Paint and appearance (M3):**- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved and loaded as `.vcswatches`, `.gpl` or CSS. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers, panels have their shortcuts, and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening.diff --cc crates/engine/src/cmd/xform.rsindex ef0b86f13,0767fcf60..6012d28bd--- a/crates/engine/src/cmd/xform.rs+++ b/crates/engine/src/cmd/xform.rs@@@ -374,55 -374,17 +374,32 @@@ fn artboard_move(s: &mut Session, p: &Vlet move_art = bool_or(p, "moveArt", false);let st = s.doc()?;let rect = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;- // Top-level objects (children of layers) lying entirely inside the artboard.- let mut art = vec![];- if move_art {- fn collect(n: &Node, rect: Rect, out: &mut Vec<NodeId>) {- for c in n.children().into_iter().flatten() {- if c.locked {- continue;- }- if c.is_layer() {- collect(c, rect, out);- } else if let Some(b) = c.geometric_bounds()- && rect.contains(Point::new(b.x0, b.y0))- && rect.contains(Point::new(b.x1, b.y1))- {- out.push(c.id);- }- }- }- for l in &st.doc.layers {- if !l.locked {- collect(l, rect, &mut art);- }- }- }+ let art = if move_art { st.doc.art_on_artboard(rect) } else { vec![] };let scale_strokes = s.prefs.scale_strokes;- s.edit("Move Artboard", |d, _| {- let a = d.artboards.get_mut(i).ok_or_else(|| EngineError::Other("no such artboard".into()))?;- a.rect = a.rect + dv;- for id in &art {- if let Some(n) = d.node_mut(*id) {- n.transform(Affine::translate(dv), scale_strokes);+ let copy = bool_or(p, "copy", false);+ let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| {+ let src = d.artboards.get(i).cloned().ok_or_else(|| EngineError::Other("no such artboard".into()))?;+ // A copy keeps the artboard (and its art) where they are and moves duplicates instead.+ if !copy {+ if let Some(a) = d.artboards.get_mut(i) {+ a.rect = src.rect + dv;+ }+ for id in &art {+ if let Some(n) = d.node_mut(*id) {+ n.transform(Affine::translate(dv), scale_strokes);+ }}+ return Ok((i, art.clone()));}- Ok(())+ let index = super::panelcmds::push_artboard_copy(d, &src, src.rect + dv);+ let mut copies = Vec::with_capacity(art.len());+ for id in &art {+ let (Some((parent, at, _)), Some(n)) = (d.position(*id), d.node(*id).cloned()) else { continue };+ let mut c = d.reid(&n);+ c.transform(Affine::translate(dv), scale_strokes);+ copies.push(d.insert(parent, at + 1, c)?);+ }+ Ok((index, copies))})?;- Ok(json!({ "index": i, "moved": art.iter().map(|i| i.0).collect::<Vec<_>>() }))+ Ok(json!({ "index": index, "moved": moved.iter().map(|i| i.0).collect::<Vec<_>>() }))}diff --cc crates/tools/src/xform/artboard.rsindex d07e4ba30,9576edff2..866a62080--- a/crates/tools/src/xform/artboard.rs+++ b/crates/tools/src/xform/artboard.rs@@@ -1,10 -1,12 +1,13 @@@//! Artboard tool (Shift+O).//!//! Click an artboard to make it active (dashed bounds, 8 handles and its name). Drag inside moves-//! it (with its artwork when the `moveArt` option is on, Shift constrains), drag a handle resizes it+//! it (with its artwork when the `moveArt` option is on, Shift constrains; Alt moves a copy and+//! leaves the artboard where it was), drag a handle resizes it//! (Shift proportional, Alt from centre), drag on the pasteboard draws a new artboard, Delete removes- //! the active one and Escape returns to the Selection tool.+ //! the active one and Escape returns to the Selection tool. Moving and resizing snap like drawing+ //! does: to whole pixels, to the grid, or with Smart Guides to other artboards, their bleed and+ //! objects (never to the dragged artboard or the art moving with it); the artboard's own bleed edges+ //! snap too.use serde_json::{Value, json};use vectorcraft_geom::{Point, Rect, Vec2};@@@ -15,13 -18,15 +19,17 @@@ use crate::{Action, Cursor, Mods, Overl#[derive(Clone, Copy, Debug)]enum Drag {- /// `copy`: Alt was held at the last drag event (the step under way is a duplicate).+ /// `rect` is the artboard as it was when the drag started: during the drag the document- /// already shows the preview, so it can't be read back from there.++ /// already shows the preview, so it can't be read back from there. `copy`: Alt was held at the++ /// last drag event (the step under way is a duplicate).Move {index: usize,start: Point,+ rect: Rect,began: bool,+ copy: bool,},+ /// `grab` is the handle's offset from the pointer, so the handle itself follows and snaps.Resize {index: usize,handle: Handle,@@@ -41,11 -47,15 +50,17 @@@ pub struct ArtboardToolpub move_art: bool,drag: Option<Drag>,preview: Option<Rect>,+ /// Smart Guide targets, gathered when a move or resize starts.+ targets: Option<Targets>,++ /// The targets for an Alt-drag copy: the original artboard and its art stay where they are.++ copy_targets: Option<Targets>,+ /// Smart Guides shown while dragging.+ guides: Vec<Overlay>,}impl Default for ArtboardTool {fn default() -> Self {- Self { active: 0, move_art: true, drag: None, preview: None }- Self { active: 0, move_art: true, drag: None, preview: None, targets: None, guides: vec![] }++ Self { active: 0, move_art: true, drag: None, preview: None, targets: None, copy_targets: None, guides: vec![] }}}@@@ -57,6 -67,77 +72,80 @@@ impl ArtboardToolfn active_rect(&self, cx: &ToolContext) -> Option<Rect> {cx.doc.artboards.get(self.active).map(|a| a.rect)}++ /// Gather the Smart Guide targets for dragging artboard `index` (call before the first preview,+ /// while the document still shows where everything started).+ fn begin_snapping(&mut self, cx: &ToolContext, index: usize, art_moves: bool) {+ self.guides.clear();+ self.targets = cx.smart_guides.then(|| {+ let art = match cx.doc.artboards.get(index) {+ Some(a) if art_moves => cx.doc.art_on_artboard(a.rect),+ _ => vec![],+ };+ Targets::for_artboard(cx.doc, index, &art)+ });++ // Nothing to skip: no artboard has this index.++ self.copy_targets = cx.smart_guides.then(|| Targets::for_artboard(cx.doc, usize::MAX, &[]));+ }++ /// Snap a dragged handle: to whole pixels, the grid, or Smart Guides (in that order, as when+ /// drawing). With Smart Guides the bleed edge `bleed` beyond the handle may snap instead.+ fn snap_handle(&mut self, cx: &ToolContext, p: Point, bleed: Vec2) -> Point {+ self.guides.clear();+ if cx.snap_to_pixel {+ return Point::new(p.x.round(), p.y.round());+ }+ if cx.snap_to_grid {+ return vectorcraft_geom::snap::snap_point_to_grid(p, grid_step(cx));+ }+ let Some(t) = &self.targets else { return p };+ let offsets: &[Vec2] = if bleed == Vec2::ZERO { &[] } else { &[bleed] };+ let (q, ov) = t.snap_point_with(p, offsets, cx.tol(5.0));+ self.guides = ov;+ q+ }+- /// Snap a move of `rect` by `d`: its top-left to whole pixels or the grid, or any of its edges- /// and centre to Smart Guides. Returns the snapped delta.- fn snap_move(&mut self, cx: &ToolContext, rect: Rect, d: Vec2) -> Vec2 {++ /// Snap a move (or an Alt-drag `copy`) of `rect` by `d`: its top-left to whole pixels or the++ /// grid, or any of its edges and centre to Smart Guides. Returns the snapped delta.++ fn snap_move(&mut self, cx: &ToolContext, rect: Rect, d: Vec2, copy: bool) -> Vec2 {+ self.guides.clear();+ let tl = Point::new(rect.x0, rect.y0);+ if cx.snap_to_pixel {+ return Vec2::new((tl.x + d.x).round() - tl.x, (tl.y + d.y).round() - tl.y);+ }+ if cx.snap_to_grid {+ return vectorcraft_geom::snap::snap_point_to_grid(tl + d, grid_step(cx)) - tl;+ }- let Some(t) = &self.targets else { return d };++ let Some(t) = (if copy { &self.copy_targets } else { &self.targets }) else { return d };+ let moved = rect + d;+ let (adj, ov) = if cx.doc.setup.has_bleed() {+ t.snap_rects(&[moved, cx.doc.setup.bleed_rect(moved)], cx.tol(5.0))+ } else {+ t.snap_rect(moved, cx.tol(5.0))+ };+ self.guides = ov;+ d + adj+ }++ fn end_drag(&mut self) {+ self.drag = None;+ self.preview = None;+ self.targets = None;++ self.copy_targets = None;+ self.guides.clear();+ }+ }++ /// Where the bleed edge lies beyond a handle, along the axes the handle moves.+ fn bleed_offset(cx: &ToolContext, rect: Rect, handle: Handle) -> Vec2 {+ let d = handle.pos(cx.doc.setup.bleed_rect(rect)) - handle.pos(rect);+ let (ax, ay) = handle.axes();+ Vec2::new(if ax { d.x } else { 0.0 }, if ay { d.y } else { 0.0 })+ }++ /// The grid's snapping step (gridline spacing over subdivisions), as `guides::snap_draw` uses.+ fn grid_step(cx: &ToolContext) -> f64 {+ cx.doc.grid.spacing / cx.doc.grid.subdivisions.max(1) as f64}impl Tool for ArtboardTool {@@@ -76,41 -157,36 +165,44 @@@if let Some(r) = self.active_rect(cx)&& let Some(handle) = hit_handle(r, p, cx.tol(5.0)){- self.drag = Some(Drag::Resize { index: self.active, handle, rect: r, began: false });+ self.drag = Some(Drag::Resize { index: self.active, handle, rect: r, grab: handle.pos(r) - p, began: false });return vec![];}- if let Some(i) = (0..cx.doc.artboards.len()).rev().find(|i| cx.doc.artboards[*i].rect.contains(p)) {+ if let Some(i) = cx.doc.artboard_at(p)+ && let Some(a) = cx.doc.artboards.get(i)+ {self.active = i;- self.drag = Some(Drag::Move { index: i, start: p, began: false, copy: false });- self.drag = Some(Drag::Move { index: i, start: p, rect: a.rect, began: false });++ self.drag = Some(Drag::Move { index: i, start: p, rect: a.rect, began: false, copy: false });} else {let (p, _) = crate::guides::snap_draw(cx, p, &[]);self.drag = Some(Drag::Create { start: p, cur: p });}vec![]}- (PointerKind::Drag, Some(Drag::Move { index, start, began, copy })) => {- (PointerKind::Drag, Some(Drag::Move { index, start, rect, began })) => {++ (PointerKind::Drag, Some(Drag::Move { index, start, rect, began, copy })) => {let mut out = vec![];+ let label = |copy: bool| if copy { "Duplicate Artboard" } else { "Move Artboard" };if !began {if p.distance(start) < cx.tol(3.0) {return out;}- out.push(Action::Begin("Move Artboard".into()));+ out.push(Action::Begin(label(m.alt).into()));+ self.begin_snapping(cx, index, self.move_art);+ } else if m.alt != copy {+ // Alt pressed or released mid-drag: start over as a copy or a move.+ out.push(Action::Cancel);+ out.push(Action::Begin(label(m.alt).into()));}- self.drag = Some(Drag::Move { index, start, began: true, copy: m.alt });- let d = move_delta(start, p, m.shift);- self.preview = cx.doc.artboards.get(index).map(|a| a.rect + d);- self.drag = Some(Drag::Move { index, start, rect, began: true });- let d = self.snap_move(cx, rect, move_delta(start, p, m.shift));++ self.drag = Some(Drag::Move { index, start, rect, began: true, copy: m.alt });++ let d = self.snap_move(cx, rect, move_delta(start, p, m.shift), m.alt);+ self.preview = Some(rect + d);- out.push(Action::Preview("artboard.move".into(), json!({ "index": index, "dx": d.x, "dy": d.y, "moveArt": self.move_art })));+ out.push(Action::Preview(+ "artboard.move".into(),+ json!({ "index": index, "dx": d.x, "dy": d.y, "moveArt": self.move_art, "copy": m.alt }),+ ));out}- (PointerKind::Drag, Some(Drag::Resize { index, handle, rect, began })) => {+ (PointerKind::Drag, Some(Drag::Resize { index, handle, rect, grab, began })) => {let mut out = vec![];if !began {out.push(Action::Begin("Resize Artboard".into()));@@@ -132,17 -210,9 +226,16 @@@vec![]}(PointerKind::Up, Some(d)) => {- self.drag = None;- self.preview = None;+ self.end_drag();match d {- Drag::Move { began: true, .. } | Drag::Resize { began: true, .. } => vec![Action::Commit],+ Drag::Move { began: true, copy, .. } => {+ // The copy, last in the previewed document, becomes the active artboard.+ if copy {+ self.active = cx.doc.artboards.len().saturating_sub(1);+ }+ vec![Action::Commit]+ }+ Drag::Resize { began: true, .. } => vec![Action::Commit],Drag::Create { start, cur } => {let r = Rect::from_points(start, cur);if r.width() < cx.tol(3.0) || r.height() < cx.tol(3.0) {@@@ -300,25 -505,4 +528,42 @@@ mod testsassert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![Action::Exec("artboard.delete".into(), json!({"index": 1}))]);assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]);}+++ #[test]++ fn an_alt_drag_copy_snaps_to_the_artboard_it_leaves_behind() {++ let d = two_boards();++ let (s, p) = (Selection::default(), paint());++ let c = cx(&d, &s, &p);++ let alt = Mods { alt: true, ..Mods::default() };++ let mut t = ArtboardTool::default();++ // A copy of artboard 2 dragged 203 pt right: its left edge 3 pt off the original's right++ // edge (800), which stays put and is a target.++ t.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0).with_mods(alt));++ let v = preview_params(&t.pointer(&c, &ev(PointerKind::Drag, 903.0, 100.0).with_mods(alt)));++ assert_eq!((v["dx"].as_f64(), v["copy"].as_bool()), (Some(200.0), Some(true)));++ // Released Alt: a plain move, and the artboard's own old edge is no target.++ let v = preview_params(&t.pointer(&c, &ev(PointerKind::Drag, 903.0, 100.0)));++ assert_eq!((v["dx"].as_f64(), v["copy"].as_bool()), (Some(203.0), Some(false)));++ }+++ #[test]+ fn alt_drag_moves_a_copy_of_the_artboard() {+ let (d, _) = doc_with_rect();+ let s = Selection::default();+ let p = paint();+ let cx = cx(&d, &s, &p);+ let alt = Mods { alt: true, ..Mods::default() };+ let moved =+ |dx: f64, copy: bool| Action::Preview("artboard.move".into(), json!({"index": 0, "dx": dx, "dy": 0.0, "moveArt": true, "copy": copy}));+ let mut t = ArtboardTool::default();+ t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0).with_mods(alt));+ let a = t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 100.0).with_mods(alt));+ assert_eq!(a, vec![Action::Begin("Duplicate Artboard".into()), moved(50.0, true)]);+ // Alt released mid-drag: a plain move after all, and back.+ let a = t.pointer(&cx, &ev(PointerKind::Drag, 160.0, 100.0));+ assert_eq!(a, vec![Action::Cancel, Action::Begin("Move Artboard".into()), moved(60.0, false)]);+ let a = t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 100.0).with_mods(alt));+ assert_eq!(a, vec![Action::Cancel, Action::Begin("Duplicate Artboard".into()), moved(70.0, true)]);+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 170.0, 100.0).with_mods(alt)), vec![Action::Commit]);+ }}