Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 2f710d3acc Fix #414: select, move and delete ruler guides with the selection tools
Guides dragged out of the rulers could not be touched again: no tool hit-tested
them, so a click on a guide went to the art under it.

- The Selection, Direct Selection and Group Selection tools pick a ruler guide
  within the selection tolerance (over the art; Direct Selection takes an
  anchor on it first) through a shared tools::rulerguide::GuideEdit. A drag
  moves the selected guides in one undo step (Alt copies them, Shift snaps the
  dragged one to the ruler's ticks, otherwise it snaps to pixels, the grid or,
  with Smart Guides, the art's edges, centres and anchors); dropped off the
  canvas onto its ruler, the guide is deleted. Hidden or locked guides can't be
  picked; the pointer shows which way a guide moves.
- Selection::guides holds the selected guides (on their own, like slices); the
  canvas draws them in the selection colour. Delete/Backspace (edit.clear)
  delete them, the arrow keys (object.nudge) nudge them, Lock Guides and Hide
  Guides deselect them.
- Commands for agents: guide.list, guide.select {indexes, toggle?},
  guide.move {dx?, dy?, copy?} (besides {index, pos}) and guide.remove {index?};
  guide positions out of range are refused. Documented in docs/mcp.md.
- Shift while dragging a new guide out of a ruler snaps it to the ticks too
  (Unit::ruler_step, shared with the rulers' drawing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:55:51 +07:00
Brandon ThomasandClaude Opus 5.5 2bcaf08dbd Release CI: macOS job on the org macos-release runner
The standard macOS runners are shared with all CI and queue for an hour or
more. The macos-release runner (GitHub-hosted M2 Pro) is in a runner group
usable only by release.yml on the release branch, with a monthly spend cap
on the actions_macos_xl SKU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 21:54:52 -04:00
BFlat e1de706245 Merge pull request #412 from imachus/pr/ja-hangul-jamo
Type: no Japanese–Latin space next to Hangul compatibility or half-width jamo
2026-10-08 08:36:36 +07:00
imachusandClaude Opus 5.5 6952780c1f Type: no Japanese–Latin space next to Hangul compatibility or half-width jamo
Follow-up to #370: Hangul Compatibility Jamo (U+3130–318F, ㄱ ㅏ) and
half-width Hangul (U+FFA0–FFDC) counted as Japanese letters, so a Latin
letter next to them took the quarter em. They are left out like Hangul
syllables; the test covers both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:29:07 +07:00
BFlat f5183da3dd Merge pull request #413 from storytold/fix/issue-394
Part of #394: Preferences that act on selection, the wheel, tool tips and the grid
2026-10-08 08:28:32 +07:00
28 changed files with 860 additions and 60 deletions

No files matched your search

+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
macos:
name: macOS universal
needs: version
runs-on: macos-15
runs-on: macos-release # org larger runner (M2 Pro), release.yml@release only; capped by the actions_macos_xl budget
environment: release
env:
VECTORCRAFT_VERSION: ${{ needs.version.outputs.version }}
+3 -3
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398) and the first Preferences options that were stored but unused (#394); see [Honest assessment](#honest-assessment-2026-10-05))._
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414) and the first Preferences options that were stored but unused (#394); see [Honest assessment](#honest-assessment-2026-10-05))._
## Where we are
@@ -124,7 +124,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **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, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
- **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; 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.
- **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 (Shift snaps them to the ruler's ticks) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the art's edges, centres and anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), 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. 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.
@@ -206,7 +206,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (Vector Halftone is 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 presets/rearrange polish (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 | 75% | global/video rulers, smart-guide preference depth, ruler-drag modifiers (Shift snaps to ticks, Alt swaps orientation) and dragging existing guides | 4–8 |
| Guides, grids, smart guides, snapping, rulers | 3 | 80% | global/video rulers, smart-guide preference depth, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click) and on layers (dragging existing guides is done, #414) | 3–6 |
| File formats | 6 | 85% | DWG (no open spec: DXF instead), PSD placement as layers, Illustrator EPS checked against more real files (two Illustrator 30 files open as vectors so far), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers and presets are done | 6–10 |
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done) | 1–2 |
+12
View File
@@ -167,6 +167,18 @@ impl Unit {
Unit::Feet => "Feet",
}
}
/// The rulers' label step at `zoom` (screen pixels per point), in this unit: the first of
/// 1, 2, 5 × 10ⁿ that puts labels at least 50 pixels apart. Ticks mark every tenth of it.
pub fn ruler_step(self, zoom: f64) -> f64 {
const STEPS: [f64; 19] =
[0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0];
STEPS.iter().copied().find(|s| s * self.points() * zoom >= 50.0).unwrap_or(10000.0)
}
/// `v` (points) on the nearest ruler tick at `zoom` ([`Self::ruler_step`]).
pub fn snap_to_ruler_tick(self, v: f64, zoom: f64) -> f64 {
let tick = self.ruler_step(zoom) / 10.0 * self.points();
(v / tick).round() * tick
}
pub fn from_pt(self, v: f64) -> f64 {
v / self.points()
}
+39 -1
View File
@@ -1,4 +1,4 @@
//! Selection state (objects and, for direct selection, individual anchors).
//! Selection state (objects and, for direct selection, individual anchors; ruler guides).
use std::collections::{BTreeMap, BTreeSet};
@@ -29,12 +29,20 @@ pub struct Selection {
/// clears them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub slices: Vec<NodeId>,
/// Ruler guides selected with a selection tool, as indexes into [`Document::guides`]. They are
/// selected on their own: any change to the object selection clears them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub guides: Vec<usize>,
}
impl Selection {
pub fn is_empty(&self) -> bool {
self.objects.is_empty()
}
/// Is anything selected that Delete and the arrow keys act on: objects or ruler guides?
pub fn has_objects_or_guides(&self) -> bool {
!self.objects.is_empty() || !self.guides.is_empty()
}
pub fn len(&self) -> usize {
self.objects.len()
}
@@ -47,6 +55,7 @@ impl Selection {
self.key = None;
self.target = None;
self.slices.clear();
self.guides.clear();
}
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
@@ -57,6 +66,7 @@ impl Selection {
pub fn add(&mut self, id: NodeId) {
self.target = None;
self.slices.clear();
self.guides.clear();
if !self.objects.contains(&id) {
self.objects.push(id);
}
@@ -64,6 +74,7 @@ impl Selection {
pub fn remove(&mut self, id: NodeId) {
self.target = None;
self.slices.clear();
self.guides.clear();
self.objects.retain(|x| *x != id);
self.anchors.remove(&id);
if self.key == Some(id) {
@@ -79,6 +90,15 @@ impl Selection {
}
}
}
/// Select ruler guides `indexes` (see [`Selection::guides`]) and nothing else.
pub fn set_guides(&mut self, indexes: impl IntoIterator<Item = usize>) {
self.clear();
for i in indexes {
if !self.guides.contains(&i) {
self.guides.push(i);
}
}
}
pub fn toggle(&mut self, id: NodeId) {
if self.contains(id) { self.remove(id) } else { self.add(id) }
}
@@ -97,6 +117,7 @@ impl Selection {
self.target = None;
}
self.slices.retain(|id| doc.is_slice(*id));
self.guides.retain(|i| *i < doc.guides.len());
}
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected
/// (the art of its sublayers too), anything else is selected itself.
@@ -138,6 +159,23 @@ mod tests {
assert!(s.is_empty());
}
#[test]
fn guides_are_selected_on_their_own() {
let mut s = Selection::default();
s.add(NodeId(1));
s.set_guides([2, 0, 2]);
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![2, 0]));
assert!(s.has_objects_or_guides() && s.is_empty());
s.add(NodeId(1));
assert!(s.guides.is_empty());
// Pruning drops guides the document no longer has.
let mut d = Document::new(100.0, 100.0);
d.guides.push(crate::Guide { vertical: true, pos: 10.0 });
s.set_guides([0, 1]);
s.prune(&d);
assert_eq!(s.guides, vec![0]);
}
#[test]
fn selection_changes_clear_the_target() {
let mut s = Selection::default();
+114 -17
View File
@@ -155,8 +155,34 @@ pub fn specs() -> Vec<CommandSpec> {
clear_guides
),
cmd!("guide.add", "Add Guide", [], None, "{vertical: bool, pos: pt (x for vertical, y for horizontal)} → {index}", has_doc, guide_add),
cmd!("guide.remove", "Remove Guide", [], None, "{index}", guides_unlocked, guide_remove),
cmd!("guide.move", "Move Guide", [], None, "{index, pos: pt}", guides_unlocked, guide_move),
cmd!(query "guide.list", "Guides", [], None, "{} → [{index, vertical, pos, selected}…] the ruler guides", has_doc, guide_list),
cmd!(
"guide.select",
"Select Guides",
[],
None,
"{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead → {selected: [index…]}",
guides_unlocked,
guide_select
),
cmd!(
"guide.remove",
"Remove Guide",
[],
None,
"{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}",
guides_unlocked,
guide_remove
),
cmd!(
"guide.move",
"Move Guide",
[],
None,
"{index, pos: pt} put ruler guide `index` at `pos` | {dx?, dy?: pt, copy?: bool} move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
guides_unlocked,
guide_move
),
cmd!("file.closeAll", "Close All", ["File"], Some("Cmd+Alt+W"), "{} → {closed}", has_doc, close_all),
cmd!(
"file.documentColorMode",
@@ -428,6 +454,10 @@ fn release_guides(s: &mut Session, _: &Value) -> Result<Value> {
fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("locked").and_then(Value::as_bool).unwrap_or(!s.menu.guides_locked);
s.menu.guides_locked = v;
// Locked guides can't stay selected.
if v && !s.doc()?.selection.guides.is_empty() {
s.select(|_, sel| sel.guides.clear())?;
}
Ok(json!({ "locked": v }))
}
@@ -458,28 +488,95 @@ fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "index": i }))
}
fn guide_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing index"))? as usize;
fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
let row = |(i, g): (usize, &Guide)| json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": st.selection.guides.contains(&i) });
Ok(Value::Array(st.doc.guides.iter().enumerate().map(row).collect()))
}
/// Ruler guide `index` of the active document (`index` validated).
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> {
let i = v.and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "an index must be a whole number"))?;
if i >= s.doc()?.doc.guides.len() {
return Err(bad(cmd, "no such guide"));
return Err(bad(cmd, format!("no guide {i}")));
}
Ok(i)
}
fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
let i = guide_index(s, p, "guide.remove")?;
s.edit("Delete Guide", |d, _| {
d.guides.remove(i);
Ok(())
})?;
ok()
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
let picked = list.iter().map(|v| guide_index(s, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
if bool_or(p, "toggle", false) {
let mut now = s.doc()?.selection.guides.clone();
for i in picked {
if let Some(k) = now.iter().position(|g| *g == i) {
now.remove(k);
} else {
now.push(i);
}
}
s.select(|_, sel| sel.set_guides(now))?;
} else {
s.select(|_, sel| sel.set_guides(picked))?;
}
Ok(json!({ "selected": s.doc()?.selection.guides }))
}
fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
let i = guide_index(s, p, "guide.move")?;
let pos = f64_req(p, "pos", "guide.move")?;
s.edit("Move Guide", |d, _| {
d.guides[i].pos = pos;
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
let gone: Vec<usize> = match p.get("index") {
Some(v) => vec![guide_index(s, Some(v), "guide.remove")?],
None => s.doc()?.selection.guides.clone(),
};
if gone.is_empty() {
return Err(bad("guide.remove", "no guide selected"));
}
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
s.edit(label, |d, sel| {
let kept = |i: &usize| !gone.contains(i);
// The guides left selected keep their place among the rest.
let left: Vec<usize> = sel.guides.iter().filter(|i| kept(i)).map(|i| i - gone.iter().filter(|g| *g < i).count()).collect();
d.guides = std::mem::take(&mut d.guides).into_iter().enumerate().filter(|(i, _)| kept(i)).map(|(_, g)| g).collect();
sel.set_guides(left);
Ok(())
})?;
Ok(json!({ "count": gone.len() }))
}
/// Put ruler guide `index` at `pos`, else move (or copy) the selected guides, in one undo step.
pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = p.get("index") {
let i = guide_index(s, Some(v), "guide.move")?;
let pos = f64_req(p, "pos", "guide.move")?;
s.edit("Move Guide", |d, _| {
if let Some(g) = d.guides.get_mut(i) {
g.pos = pos;
}
Ok(())
})?;
return ok();
}
let moving = s.doc()?.selection.guides.clone();
if moving.is_empty() {
return Err(bad("guide.move", "no guide selected (or give an index)"));
}
let (dx, dy, copy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0), bool_or(p, "copy", false));
s.edit(if copy { "Copy Guide" } else { "Move Guide" }, |d, sel| {
let mut copies = vec![];
for &i in &moving {
let Some(g) = d.guides.get_mut(i) else { continue };
let moved = Guide { vertical: g.vertical, pos: g.pos + if g.vertical { dx } else { dy } };
if copy {
copies.push(moved);
} else {
*g = moved;
}
}
if copy {
let first = d.guides.len();
d.guides.extend(copies);
sel.set_guides(first..d.guides.len());
}
Ok(())
})?;
ok()
+13 -1
View File
@@ -85,7 +85,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_clipboard,
|s, p| paste(s, p, PasteMode::AllArtboards)
),
cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{ids?}", has_selection, clear),
cmd!(
"edit.clear",
"Clear",
["Edit"],
Some("Delete"),
"{ids?} delete the objects `ids`, else the selection (direct-selected anchors, else objects, else ruler guides)",
has_selection_or_guides,
clear
),
cmd!("edit.duplicate", "Duplicate", [], None, "{dx?, dy?} duplicate the selection in place (offset optional)", has_selection, duplicate),
]
}
@@ -224,6 +232,10 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
if ids_param(p, "ids").is_none() && !s.doc()?.selection.anchors.is_empty() {
return super::path::delete_anchors(s, p);
}
// Selected ruler guides (selected on their own).
if ids_param(p, "ids").is_none() && s.doc()?.selection.is_empty() {
return super::docmenu::guide_remove(s, &json!({}));
}
let ids = match ids_param(p, "ids") {
Some(v) => v,
None => selected_roots(s)?,
+5
View File
@@ -144,6 +144,11 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
}
/// Objects or ruler guides are selected (what Delete and the arrow keys act on).
pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.has_objects_or_guides() { Ok(()) } else { Err("nothing selected".into()) }
}
pub fn has_anchors(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.anchors.values().all(|a| a.is_empty()) { Err("no anchor points selected".into()) } else { Ok(()) }
+5 -2
View File
@@ -68,8 +68,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool} arrow-key nudge by the keyboard increment",
has_selection,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool} arrow-key nudge by the keyboard increment (the selected anchors, else objects, else ruler guides)",
has_selection_or_guides,
nudge
),
cmd!("object.arrange.bringToFront", "Bring to Front", ["Object", "Arrange"], Some("Cmd+Shift+]"), "{}", has_selection, |s, _| arrange(
@@ -268,6 +268,9 @@ fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
if !s.doc()?.selection.anchors.is_empty() {
return super::path::move_anchors(s, &json!({ "dx": dx, "dy": dy }));
}
if s.doc()?.selection.is_empty() {
return super::docmenu::guide_move(s, &json!({ "dx": dx, "dy": dy, "copy": bool_or(p, "copy", false) }));
}
let ids = selected_roots(s)?;
apply_transform(s, "Move", ids, Affine::translate((dx, dy)), p)
}
+3 -1
View File
@@ -293,7 +293,9 @@ fn strip_replay_only(id: &str, p: &mut Value) {
/// have finite, in-range geometry, so saved files always reload and renderers never see NaN/∞.
fn doc_sane(d: &Document, sel: &Selection) -> bool {
let ok = |r: vectorcraft_geom::Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD);
d.artboards.iter().all(|a| ok(a.rect)) && sel.objects.iter().all(|id| d.node(*id).and_then(|n| n.geometric_bounds()).is_none_or(ok))
d.artboards.iter().all(|a| ok(a.rect))
&& d.guides.iter().all(|g| g.pos.is_finite() && g.pos.abs() <= MAX_COORD)
&& sel.objects.iter().all(|id| d.node(*id).and_then(|n| n.geometric_bounds()).is_none_or(ok))
}
/// Where new art goes (Illustrator's drawing modes, Shift+D cycles).
+93
View File
@@ -740,6 +740,99 @@ fn ruler_guides_and_lock() {
assert!(s.execute("guide.remove", &json!({"index": 0})).is_err());
}
fn guides(s: &Session) -> Vec<(bool, f64)> {
s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect()
}
fn selected_guides(s: &Session) -> Vec<usize> {
s.doc().unwrap().selection.guides.clone()
}
/// #414: ruler guides are selected, moved, copied, nudged and deleted like art, over commands.
#[test]
fn ruler_guides_select_move_and_delete() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
for (vertical, pos) in [(true, 100.0), (false, 50.0), (true, 300.0)] {
s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap();
}
sel(&mut s, &[a]);
// Selecting guides deselects the art; toggle adds and removes.
assert_eq!(s.execute("guide.select", &json!({"indexes": [0]})).unwrap()["selected"], json!([0]));
assert!(selected(&s).is_empty());
assert_eq!(s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap()["selected"], json!([0, 1]));
assert_eq!(s.execute("guide.list", &json!({})).unwrap()[1], json!({"index": 1, "vertical": false, "pos": 50.0, "selected": true}));
assert!(s.execute("guide.select", &json!({"indexes": [7]})).is_err());
// A move takes each selected guide along its own axis, in one undo step.
let n = undo_len(&s);
s.execute("guide.move", &json!({"dx": 10, "dy": -5})).unwrap();
assert_eq!(guides(&s), [(true, 110.0), (false, 45.0), (true, 300.0)]);
assert_eq!(undo_len(&s), n + 1);
// Alt: copies, which are then the selection.
s.execute("guide.move", &json!({"dx": 20, "copy": true})).unwrap();
assert_eq!(guides(&s).len(), 5);
assert_eq!(&guides(&s)[3..], [(true, 130.0), (false, 45.0)]);
assert_eq!(selected_guides(&s), [3, 4]);
// The arrow keys nudge them.
s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "big": true})).unwrap();
assert_eq!(guides(&s)[3], (true, 140.0));
// Delete (edit.clear) deletes the selected guides; the others keep their places.
s.execute("guide.select", &json!({"indexes": [1, 3]})).unwrap();
assert_eq!(s.execute("guide.list", &json!({})).unwrap().as_array().unwrap().len(), 5);
s.execute("edit.clear", &json!({})).unwrap();
assert_eq!(guides(&s), [(true, 110.0), (true, 300.0), (false, 45.0)]);
assert!(selected_guides(&s).is_empty());
assert!(s.doc().unwrap().doc.node(a).is_some(), "the art stays");
// Removing one keeps the rest of the selection pointing at the same guides.
s.execute("guide.select", &json!({"indexes": [1, 2]})).unwrap();
assert_eq!(s.execute("guide.remove", &json!({"index": 0})).unwrap()["count"], 1);
assert_eq!((guides(&s), selected_guides(&s)), (vec![(true, 300.0), (false, 45.0)], vec![0, 1]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![1, 2]));
// Out of range positions are refused.
assert!(s.execute("guide.move", &json!({"index": 0, "pos": 1e300})).is_err());
assert!(s.execute("guide.add", &json!({"vertical": true, "pos": -1e300})).is_err());
// Locking deselects them, and they can't be picked again until unlocked.
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
assert!(selected_guides(&s).is_empty());
assert!(matches!(s.execute("guide.select", &json!({"indexes": [0]})), Err(EngineError::Disabled(..))));
assert!(matches!(s.execute("edit.clear", &json!({})), Err(EngineError::Disabled(..))));
}
/// #414: the Selection tool picks a ruler guide over the art and drags it in one undo step; with
/// guides hidden or locked the press goes to the art.
#[test]
fn selection_tool_drags_a_ruler_guide() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
s.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.select_tool("selection", v).unwrap();
let drag = |s: &mut Session, v: ViewInfo, from: (f64, f64), to: (f64, f64)| {
s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1), v).unwrap();
};
let n = undo_len(&s);
drag(&mut s, v, (151.0, 120.0), (171.0, 140.0));
assert_eq!(guides(&s), [(true, 170.0)]);
assert_eq!(selected_guides(&s), [0]);
assert!(selected(&s).is_empty());
assert_eq!(bounds(&s, a).x0, 100.0, "the art stays");
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Move Guide");
// Hidden guides: the press takes the art.
let hidden = ViewInfo { guides: false, ..v };
drag(&mut s, hidden, (170.0, 120.0), (180.0, 120.0));
assert_eq!((guides(&s), bounds(&s, a).x0), (vec![(true, 170.0)], 110.0));
// Locked guides too.
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
drag(&mut s, v, (170.0, 120.0), (180.0, 120.0));
assert_eq!((guides(&s), bounds(&s, a).x0), (vec![(true, 170.0)], 120.0));
}
// ---------- File ----------
#[test]
+4
View File
@@ -13,6 +13,8 @@ pub struct ViewInfo {
pub zoom: f64,
pub outline: bool,
pub smart_guides: bool,
/// View → Show Guides: the ruler guides show (and, unlocked, can be picked).
pub guides: bool,
pub snap_to_grid: bool,
pub show_bbox: bool,
/// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi).
@@ -31,6 +33,7 @@ impl Default for ViewInfo {
zoom: 1.0,
outline: false,
smart_guides: true,
guides: true,
snap_to_grid: false,
show_bbox: true,
snap_to_pixel: false,
@@ -134,6 +137,7 @@ impl Session {
paint: &self.paint,
outline: view.outline,
smart_guides: view.smart_guides,
guides: view.guides && !self.menu.guides_locked,
snap_to_grid: view.snap_to_grid,
show_bbox: view.show_bbox,
snap_to_pixel: view.snap_to_pixel,
+6 -2
View File
@@ -281,7 +281,10 @@ fn is_japanese_letter(c: char) -> bool {
return true;
}
is_cjk(c)
&& !matches!(c as u32, 0x3000..=0x303F | 0xAC00..=0xD7AF | 0xFF01..=0xFF0F | 0xFF1A..=0xFF20 | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65)
&& !matches!(
c as u32,
0x3000..=0x303F | 0x3130..=0x318F | 0xAC00..=0xD7AF | 0xFF01..=0xFF0F | 0xFF1A..=0xFF20 | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65 | 0xFFA0..=0xFFDC
)
&& c != '・'
&& punct(c).is_none()
}
@@ -818,7 +821,8 @@ fn japanese_letters_for_the_latin_space_are_kana_kanji_and_marks_not_hangul_or_p
for c in ['あ', 'カ', '漢', '々', '〆', '〇', 'A'] {
assert!(is_japanese_letter(c), "{c}");
}
for c in ['한', '。', '「', '・', '、', 'a'] {
// Hangul in every form: syllables, compatibility jamo (ㄱ ㅏ), half-width jamo (ᄀ).
for c in ['한', 'ㄱ', 'ㅏ', '\u{FFA1}', '。', '「', '・', '、', 'a'] {
assert!(!is_japanese_letter(c), "{c}");
}
}
+43 -8
View File
@@ -7,11 +7,11 @@
//! (the selected ones when anchors are selected; Alt-click cycles their kind, double-click opens
//! the Corners dialog).
//! Group Selection: click selects the leaf; each further click on it adds the next enclosing group.
//! Both pick the key objects of a blend. Direct Selection also edits a blend's spine: drag its
//! points (a key object on a point moves with it) and, once a point is clicked, its handles; and
//! the points of selected gradient meshes and mesh envelopes and their handles ([`MeshEdit`]).
//! Dragging a corner or an edge of area type's frame reshapes the type area (`text.reshapeArea`):
//! the text reflows at its size.
//! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]).
//! Direct Selection also edits a blend's spine: drag its points (a key object on a point moves
//! with it) and, once a point is clicked, its handles; and the points of selected gradient meshes
//! and mesh envelopes and their handles ([`MeshEdit`]). Dragging a corner or an edge of area
//! type's frame reshapes the type area (`text.reshapeArea`): the text reflows at its size.
//!
//! A press on the stroke of a path that isn't selected as a whole selects that segment's two anchors
//! (the fill, or Alt, selects the whole path); dragging the segment bends it if it's curved, else
@@ -27,6 +27,7 @@ use vectorcraft_geom::{PathData, Point, Rect};
use crate::bbox::move_delta;
use crate::corners::{self, CornerDrag, over_widget};
use crate::meshedit::MeshEdit;
use crate::rulerguide::GuideEdit;
use crate::select::{is_area_type, matrix_json};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext};
@@ -97,11 +98,12 @@ pub struct DirectSelectionTool {
guides: Vec<Overlay>,
/// The anchor under the pointer (Highlight anchors on mouse over): its path, where it is.
hover: Option<(NodeId, Point)>,
guide: GuideEdit,
}
impl DirectSelectionTool {
pub fn new(group: bool) -> Self {
Self { group, state: State::Idle, spine: None, mesh: MeshEdit::default(), guides: vec![], hover: None }
Self { group, state: State::Idle, spine: None, mesh: MeshEdit::default(), guides: vec![], hover: None, guide: GuideEdit::default() }
}
}
@@ -234,13 +236,20 @@ impl Tool for DirectSelectionTool {
if self.group { "groupSelection" } else { "directSelection" }
}
fn busy(&self) -> bool {
!matches!(self.state, State::Idle)
!matches!(self.state, State::Idle) || self.guide.busy()
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
if let Some(out) = self.guide.pointer(cx, ev) {
return out;
}
let p = ev.pos;
let tol = cx.pick_tol();
match (ev.kind, self.state.clone()) {
(PointerKind::Down, _) if self.group => {
if let Some(out) = self.guide.press(cx, ev) {
self.state = State::Idle;
return out;
}
let Some(h) = hit_test(cx.doc, p, cx.hit_options()) else {
self.state = State::Marquee { start: p, cur: p, add: ev.mods.shift };
return vec![];
@@ -309,6 +318,10 @@ impl Tool for DirectSelectionTool {
if let Some((id, anchors)) = hit_frame_edge(cx, p, tol) {
return self.press_type_area(cx, id, anchors, p, ev.mods.shift);
}
if let Some(out) = self.guide.press(cx, ev) {
self.state = State::Idle;
return out;
}
if let Some(h) = hit_test(cx.doc, p, cx.hit_options()) {
// A segment of a path that isn't selected as a whole: its two anchors get
// selected, and dragging it reshapes it if it's curved, else moves it. Alt picks
@@ -501,6 +514,7 @@ impl Tool for DirectSelectionTool {
if let Some((id, p)) = self.hover.filter(|_| matches!(self.state, State::Idle)) {
out.push(Overlay::Anchor { p, color: cx.doc.layer_color(id), filled: false, size: 8.0 });
}
out.extend(self.guide.overlays(cx));
out
}
}
@@ -509,7 +523,8 @@ impl Tool for DirectSelectionTool {
if !self.group && (matches!(self.state, State::Corner(_)) || over_widget(cx, p)) {
return Cursor::CornerRadius;
}
Cursor::ArrowHollow
// A press on the highlighted anchor picks it, not the guide.
self.guide.cursor(cx, p).filter(|_| self.hover.is_none() || self.guide.busy()).unwrap_or(Cursor::ArrowHollow)
}
}
@@ -570,6 +585,26 @@ mod tests {
use crate::testutil::*;
use vectorcraft_doc::Selection;
/// #414: a ruler guide is picked over the art, but an anchor on it is picked first.
#[test]
fn direct_and_group_selection_pick_ruler_guides() {
let (mut d, id) = doc_with_rect();
d.guides.push(vectorcraft_doc::Guide { vertical: true, pos: 100.0 });
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let down = |t: &mut DirectSelectionTool, y: f64| t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, y));
let pick = vec![Action::Exec("guide.select".into(), json!({"indexes": [0]}))];
for group in [false, true] {
let mut t = DirectSelectionTool::new(group);
assert_eq!(down(&mut t, 150.0), pick, "on the rect's edge (group: {group})");
assert!(t.busy());
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 150.0));
assert_eq!(t.cursor(&c, Point::new(101.0, 300.0), Mods::default()), Cursor::ResizeH);
}
let mut t = DirectSelectionTool::new(false);
assert_eq!(down(&mut t, 100.0), vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))]);
}
/// A blend of two 20 pt squares centred on (110, 310) and (210, 310), selected.
fn blend_doc() -> (vectorcraft_doc::Document, NodeId, NodeId) {
let (mut d, _) = doc_with_rect();
+18 -2
View File
@@ -142,6 +142,23 @@ impl Targets {
(out, ov)
}
/// Snap a ruler guide at `v` (the x of a vertical one, the y of a horizontal one) into line
/// with the nearest edge, centre or anchor within `tol`: where it goes, and a label there.
pub fn snap_guide(&self, vertical: bool, v: f64, tol: f64) -> (f64, Vec<Overlay>) {
let along = |q: &Point| if vertical { q.x } else { q.y };
let lines = if vertical { &self.xs } else { &self.ys };
let best = lines
.iter()
.map(|(t, from, k)| (*t, *from, *k))
.chain(self.points.iter().map(|(q, k)| (along(q), *q, *k)))
.filter(|(t, ..)| (t - v).abs() <= tol)
.min_by(|a, b| (a.0 - v).abs().total_cmp(&(b.0 - v).abs()));
match best {
Some((t, from, k)) => (t, vec![Overlay::Label { p: from, text: k.label().into(), color: MAGENTA }]),
None => (v, vec![]),
}
}
/// Snap a dragged point that carries others along at `offsets` (a resize handle and the
/// bleed edge beyond it): onto an anchor or centre near the point itself, otherwise into line
/// with targets, each axis on whichever of them comes nearest.
@@ -298,8 +315,7 @@ fn snap_with(cx: &ToolContext, p: Point, targets: impl FnOnce() -> Targets) -> (
return (Point::new(p.x.round(), p.y.round()), vec![]);
}
if cx.snap_to_grid {
let s = cx.doc.grid.spacing / cx.doc.grid.subdivisions.max(1) as f64;
return (vectorcraft_geom::snap::snap_point_to_grid(p, s), vec![]);
return (vectorcraft_geom::snap::snap_point_to_grid(p, cx.grid_step()), vec![]);
}
if !cx.smart_guides {
return (p, vec![]);
+15
View File
@@ -23,6 +23,7 @@ pub mod params;
pub mod pen;
pub mod place;
pub mod printtiling;
pub mod rulerguide;
pub mod select;
pub mod settings;
pub mod shape;
@@ -201,6 +202,13 @@ impl ScreenFrame {
pub fn at(&self, x: f64, y: f64) -> Point {
self.origin + self.right * x + self.down * y
}
/// Where the document point `p` is, in screen pixels from the window's top-left corner (the
/// inverse of [`Self::at`]); none for a degenerate frame.
pub fn to_screen(&self, p: Point) -> Option<(f64, f64)> {
let (r, d, v) = (self.right, self.down, p - self.origin);
let det = r.x * d.y - d.x * r.y;
(det.is_finite() && det.abs() > 1e-12).then(|| ((v.x * d.y - d.x * v.y) / det, (r.x * v.y - v.x * r.y) / det))
}
}
/// Read-only context a tool sees.
@@ -213,6 +221,8 @@ pub struct ToolContext<'a> {
pub paint: &'a PaintDefaults,
pub outline: bool,
pub smart_guides: bool,
/// View → Show Guides with Lock Guides off: the selection tools pick and drag ruler guides.
pub guides: bool,
pub snap_to_grid: bool,
/// Bounding box shown (View → Show/Hide Bounding Box).
pub show_bbox: bool,
@@ -292,6 +302,10 @@ impl ToolContext<'_> {
pub fn offset_label(&self, dx: f64, dy: f64) -> String {
format!("dX: {}\ndY: {}", self.len(dx), self.len(dy))
}
/// What Snap to Grid snaps to: the grid's subdivisions (or its lines without any).
pub fn grid_step(&self) -> f64 {
self.doc.grid.spacing / self.doc.grid.subdivisions.max(1) as f64
}
/// The selection tolerance in document units ([`Self::selection_tolerance`]).
pub fn pick_tol(&self) -> f64 {
self.tol(self.selection_tolerance)
@@ -547,6 +561,7 @@ pub(crate) mod testutil {
paint: p,
outline: false,
smart_guides: true,
guides: true,
snap_to_grid: false,
show_bbox: true,
snap_to_pixel: false,
+314
View File
@@ -0,0 +1,314 @@
//! Ruler guides on the canvas, for the selection tools. A press on a guide selects it (Shift adds
//! it to the selected guides or, released without a drag, takes it out); dragging moves the
//! selected guides (Alt copies them). The dragged guide snaps: with Shift to the ruler's ticks,
//! else as a drawn point does (whole pixels, the grid, or with Smart Guides the art's edges,
//! centres and anchors). Dropped off the canvas onto its ruler, the guide is deleted. Hidden or
//! locked guides (View › Guides) can't be picked.
use serde_json::json;
use vectorcraft_geom::Point;
use crate::guides::Targets;
use crate::{Action, Cursor, Overlay, PointerEvent, PointerKind, ToolContext};
/// The ruler guide under `p`: the nearest within the selection tolerance (the newest of equals).
pub fn guide_at(cx: &ToolContext, p: Point) -> Option<usize> {
if !cx.guides {
return None;
}
let tol = cx.pick_tol();
let off = |pos: f64, vertical: bool| (if vertical { p.x } else { p.y } - pos).abs();
cx.doc
.guides
.iter()
.enumerate()
.map(|(i, g)| (i, off(g.pos, g.vertical)))
.filter(|(_, d)| *d <= tol)
.min_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0)))
.map(|(i, _)| i)
}
/// The pointer for a guide: it moves sideways if vertical, up and down if horizontal.
fn guide_cursor(vertical: bool) -> Cursor {
if vertical { Cursor::ResizeH } else { Cursor::ResizeV }
}
#[derive(Clone, Copy, Debug)]
struct Drag {
index: usize,
vertical: bool,
/// Where the guide was, and where it is now (x of a vertical guide, y of a horizontal one).
from: f64,
at: f64,
start: Point,
pointer: Point,
began: bool,
/// Shift-pressed on a selected guide: released without a drag, it leaves the selection.
deselect: bool,
}
/// A selection tool's ruler-guide handling: [`Self::press`] on a press, [`Self::pointer`] for
/// the rest of the gesture.
#[derive(Default)]
pub struct GuideEdit {
drag: Option<Drag>,
/// Smart Guides targets, gathered when the drag starts.
targets: Option<Targets>,
/// The smart guide the dragged guide snapped to.
snapped: Vec<Overlay>,
}
impl GuideEdit {
/// Is a guide pressed or being dragged?
pub fn busy(&self) -> bool {
self.drag.is_some()
}
/// A press `ev` on a ruler guide: it gets selected and the drag starts. None (and nothing
/// done) when no guide is there.
pub fn press(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
let index = guide_at(cx, ev.pos)?;
let g = cx.doc.guides.get(index)?;
let (shift, selected) = (ev.mods.shift, cx.selection.guides.contains(&index));
self.drag = Some(Drag {
index,
vertical: g.vertical,
from: g.pos,
at: g.pos,
start: ev.pos,
pointer: ev.pos,
began: false,
deselect: shift && selected,
});
self.targets = None;
self.snapped.clear();
Some(match (selected, shift) {
(true, _) => vec![],
(false, true) => vec![Action::Exec("guide.select".into(), json!({ "indexes": [index], "toggle": true }))],
(false, false) => vec![Action::Exec("guide.select".into(), json!({ "indexes": [index] }))],
})
}
/// The drag and release of a guide [`Self::press`] picked; None when no guide is pressed.
pub fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
let mut d = self.drag?;
Some(match ev.kind {
PointerKind::Drag => {
let out = self.drag_to(cx, &mut d, ev);
self.drag = Some(d);
out
}
PointerKind::Up => {
self.drag = None;
self.targets = None;
self.snapped.clear();
if d.began && on_ruler(cx, d.vertical, ev.pos) {
// Dropped on its ruler: the guide goes (a copy is just not made).
let mut out = vec![Action::Cancel];
if !ev.mods.alt {
out.push(Action::Exec("guide.remove".into(), json!({ "index": d.index })));
}
out
} else if d.began {
vec![Action::Commit]
} else if d.deselect {
vec![Action::Exec("guide.select".into(), json!({ "indexes": [d.index], "toggle": true }))]
} else {
vec![]
}
}
// Another press ends the gesture.
_ => {
self.drag = None;
return None;
}
})
}
fn drag_to(&mut self, cx: &ToolContext, d: &mut Drag, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
let mut out = vec![];
if !d.began {
if p.distance(d.start) < cx.tol(3.0) {
return out;
}
d.began = true;
out.push(Action::Begin(if ev.mods.alt { "Copy Guide" } else { "Move Guide" }.into()));
self.targets = cx.smart_guides.then(|| Targets::collect(cx.doc, &[], None));
}
let moved = p - d.start;
let (at, snapped) = self.snap(cx, d.vertical, d.from + if d.vertical { moved.x } else { moved.y }, ev.mods.shift);
(d.at, d.pointer, self.snapped) = (at, p, snapped);
// The other selected guides follow the pointer: vertical ones across, horizontal ones down.
let (dx, dy) = if d.vertical { (at - d.from, moved.y) } else { (moved.x, at - d.from) };
out.push(Action::Preview("guide.move".into(), json!({ "dx": dx, "dy": dy, "copy": ev.mods.alt })));
out
}
/// Where a guide dragged to `v` goes: with Shift on the nearest ruler tick, else on whole
/// pixels, the grid or a smart guide (as a drawn point snaps).
fn snap(&self, cx: &ToolContext, vertical: bool, v: f64, shift: bool) -> (f64, Vec<Overlay>) {
if shift {
return (cx.unit.snap_to_ruler_tick(v, cx.zoom), vec![]);
}
if cx.snap_to_pixel {
return (v.round(), vec![]);
}
if cx.snap_to_grid {
return (vectorcraft_geom::snap::snap_to_grid(v, cx.grid_step(), 0.0), vec![]);
}
match &self.targets {
Some(t) => t.snap_guide(vertical, v, cx.tol(5.0)),
None => (v, vec![]),
}
}
/// The pointer over a guide, or while one is dragged.
pub fn cursor(&self, cx: &ToolContext, p: Point) -> Option<Cursor> {
if let Some(d) = &self.drag {
return Some(guide_cursor(d.vertical));
}
guide_at(cx, p).and_then(|i| cx.doc.guides.get(i)).map(|g| guide_cursor(g.vertical))
}
/// While a guide is dragged: the smart guide it snapped to and its position by the pointer.
pub fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let Some(d) = self.drag.filter(|d| d.began) else { return vec![] };
let mut o = self.snapped.clone();
let axis = if d.vertical { "X" } else { "Y" };
o.push(Overlay::Measure { p: d.pointer, text: format!("{axis}: {}", cx.len(d.at)) });
o
}
}
/// Is `p` off the canvas on the side of the ruler a guide comes from (the top one for a
/// horizontal guide, the left one for a vertical guide)? Never without a window.
fn on_ruler(cx: &ToolContext, vertical: bool, p: Point) -> bool {
cx.screen.and_then(|s| s.to_screen(p)).is_some_and(|(x, y)| if vertical { x < 0.0 } else { y < 0.0 })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::*;
use crate::{Mods, ScreenFrame};
use vectorcraft_doc::{Guide, Selection};
use vectorcraft_geom::Vec2;
fn ev(kind: PointerKind, x: f64, y: f64, mods: Mods) -> PointerEvent {
PointerEvent::new(kind, x, y).with_mods(mods)
}
fn guides_doc() -> vectorcraft_doc::Document {
let (mut d, _) = doc_with_rect();
d.guides = vec![Guide { vertical: true, pos: 300.0 }, Guide { vertical: false, pos: 400.0 }];
d
}
#[test]
fn picks_the_guide_within_the_tolerance_unless_hidden_or_locked() {
let (d, s, p) = (guides_doc(), Selection::default(), paint());
let c = cx(&d, &s, &p);
assert_eq!(guide_at(&c, Point::new(302.0, 50.0)), Some(0));
assert_eq!(guide_at(&c, Point::new(50.0, 398.0)), Some(1));
// Where they cross, the nearer one.
assert_eq!(guide_at(&c, Point::new(301.0, 398.0)), Some(0));
assert_eq!(guide_at(&c, Point::new(305.0, 50.0)), None, "beyond the 3 px tolerance");
let hidden = ToolContext { guides: false, ..cx(&d, &s, &p) };
assert_eq!(guide_at(&hidden, Point::new(300.0, 50.0)), None);
}
#[test]
fn a_drag_moves_the_selected_guides_in_one_step() {
let d = guides_doc();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let mut g = GuideEdit::default();
let m = Mods::default();
assert_eq!(g.press(&c, &ev(PointerKind::Down, 300.0, 50.0, m)), Some(vec![Action::Exec("guide.select".into(), json!({"indexes": [0]}))]));
// The tool sees the guide selected from now on.
let mut s = s;
s.set_guides([0]);
let c = cx(&d, &s, &p);
let a = g.pointer(&c, &ev(PointerKind::Drag, 340.0, 60.0, m)).unwrap();
assert_eq!(a[0], Action::Begin("Move Guide".into()));
assert_eq!(a[1], Action::Preview("guide.move".into(), json!({"dx": 40.0, "dy": 10.0, "copy": false})));
assert!(matches!(g.overlays(&c).last(), Some(Overlay::Measure { text, .. }) if text == "X: 340.00 pt"));
assert_eq!(g.cursor(&c, Point::ZERO), Some(Cursor::ResizeH));
assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 340.0, 60.0, m)), Some(vec![Action::Commit]));
assert!(!g.busy() && g.pointer(&c, &ev(PointerKind::Drag, 0.0, 0.0, m)).is_none());
}
#[test]
fn the_dragged_guide_snaps_to_art_ruler_ticks_and_the_grid() {
let d = guides_doc();
let mut s = Selection::default();
s.set_guides([0]);
let p = paint();
let drag_to = |c: &ToolContext, x: f64, mods: Mods| {
let mut g = GuideEdit::default();
g.press(c, &ev(PointerKind::Down, 300.0, 50.0, Mods::default()));
let a = g.pointer(c, &ev(PointerKind::Drag, x, 50.0, mods)).unwrap();
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
(300.0 + v["dx"].as_f64().unwrap(), g.overlays(c))
};
// Smart Guides: onto the rect's right edge (x = 200), labelled.
let (x, ov) = drag_to(&cx(&d, &s, &p), 203.0, Mods::default());
assert_eq!(x, 200.0);
assert!(matches!(&ov[0], Overlay::Label { .. }));
let off = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
assert_eq!(drag_to(&off, 203.0, Mods::default()).0, 203.0);
// Shift: the ruler's ticks (labels every 50 pt at 100 %, ticks every 5 pt).
assert_eq!(drag_to(&off, 223.0, Mods { shift: true, ..Default::default() }).0, 225.0);
let zoomed = ToolContext { zoom: 5.0, ..cx(&d, &s, &p) };
assert_eq!(drag_to(&zoomed, 223.4, Mods { shift: true, ..Default::default() }).0, 223.0, "every point at 500 %");
let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) };
assert_eq!(drag_to(&grid, 226.0, Mods::default()).0, 225.0, "the grid's 9 pt subdivisions");
}
#[test]
fn shift_click_toggles_and_alt_drag_copies() {
let d = guides_doc();
let mut s = Selection::default();
s.set_guides([0, 1]);
let p = paint();
let c = cx(&d, &s, &p);
let (shift, alt) = (Mods { shift: true, ..Default::default() }, Mods { alt: true, ..Default::default() });
let mut g = GuideEdit::default();
assert_eq!(g.press(&c, &ev(PointerKind::Down, 50.0, 400.0, shift)), Some(vec![]));
let deselect = Action::Exec("guide.select".into(), json!({"indexes": [1], "toggle": true}));
assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 50.0, 400.0, shift)), Some(vec![deselect]));
g.press(&c, &ev(PointerKind::Down, 50.0, 400.0, alt));
let a = g.pointer(&c, &ev(PointerKind::Drag, 50.0, 420.0, alt)).unwrap();
assert_eq!(a[0], Action::Begin("Copy Guide".into()));
assert_eq!(a[1], Action::Preview("guide.move".into(), json!({"dx": 0.0, "dy": 20.0, "copy": true})));
}
#[test]
fn dropped_on_its_ruler_the_guide_is_deleted() {
let d = guides_doc();
let p = paint();
let mut s = Selection::default();
s.set_guides([1]);
// The window shows the document from (0, 0) at 100 %: above y = 0 is the top ruler.
let screen = ScreenFrame { origin: Point::ZERO, right: Vec2::new(1.0, 0.0), down: Vec2::new(0.0, 1.0), size: (800.0, 600.0) };
let c = ToolContext { screen: Some(screen), ..cx(&d, &s, &p) };
let m = Mods::default();
let gesture = |to: Point, mods: Mods| {
let mut g = GuideEdit::default();
g.press(&c, &ev(PointerKind::Down, 50.0, 400.0, m));
g.pointer(&c, &ev(PointerKind::Drag, to.x, to.y, mods));
g.pointer(&c, &ev(PointerKind::Up, to.x, to.y, mods)).unwrap()
};
assert_eq!(gesture(Point::new(50.0, -6.0), m), vec![Action::Cancel, Action::Exec("guide.remove".into(), json!({"index": 1}))]);
assert_eq!(gesture(Point::new(50.0, -6.0), Mods { alt: true, ..m }), vec![Action::Cancel], "a copy is just not made");
// Off the left side: not its ruler.
assert_eq!(gesture(Point::new(-6.0, 300.0), m), vec![Action::Commit]);
// Headless (no window): no ruler to drop it on.
let mut g = GuideEdit::default();
let c = cx(&d, &s, &p);
g.press(&c, &ev(PointerKind::Down, 50.0, 400.0, m));
g.pointer(&c, &ev(PointerKind::Drag, 50.0, -6.0, m));
assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 50.0, -6.0, m)), Some(vec![Action::Commit]));
}
}
+45 -3
View File
@@ -2,7 +2,8 @@
//! bounding-box scale (Shift proportional, Alt from centre) and rotate (outside corners, Shift 45°),
//! drag a live rectangle's corner widget to round its corners (Alt-click cycles their kind,
//! double-click opens the Corners dialog), double-click to enter isolation mode (Double Click To
//! Isolate), Cmd/Ctrl-click to select the object behind (Command Click to Select Objects Behind).
//! Isolate), Cmd/Ctrl-click to select the object behind (Command Click to Select Objects Behind),
//! click or drag a ruler guide ([`crate::rulerguide`]).
//! The bounding box stands at the selection's own angle after a rotation, so its handles scale
//! along the objects' axes. A handle drag resizes area type's frame (the type area) instead of
//! scaling its type: the text reflows at its size.
@@ -14,6 +15,7 @@ use vectorcraft_geom::{Affine, Point, Rect};
use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag};
use crate::corners::{self, CornerDrag, over_widget};
use crate::rulerguide::GuideEdit;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, json_ids};
#[derive(Clone, Debug, Default)]
@@ -54,6 +56,7 @@ pub struct SelectionTool {
guides: Vec<Overlay>,
targets: Option<crate::guides::Targets>,
start_bounds: Option<Rect>,
guide: GuideEdit,
}
pub fn matrix_json(a: Affine) -> Value {
@@ -101,10 +104,13 @@ impl Tool for SelectionTool {
}
fn busy(&self) -> bool {
!matches!(self.state, State::Idle)
!matches!(self.state, State::Idle) || self.guide.busy()
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
if let Some(out) = self.guide.pointer(cx, ev) {
return out;
}
let p = ev.pos;
let m = ev.mods;
match (ev.kind, self.state.clone()) {
@@ -113,6 +119,9 @@ impl Tool for SelectionTool {
if let Some(a) = corners::double_click(cx, p) {
return vec![a];
}
if crate::rulerguide::guide_at(cx, p).is_some() {
return vec![];
}
if let Some(h) = hit_test(cx.doc, p, cx.hit_options()) {
let top = h.top_object(cx.isolation);
if cx.double_click_isolate && cx.doc.node(top).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. })) {
@@ -153,7 +162,12 @@ impl Tool for SelectionTool {
None => {}
}
}
// 2. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling).
// 2. Ruler guides (over the art, as they are drawn).
if let Some(out) = self.guide.press(cx, ev) {
self.state = State::Idle;
return out;
}
// 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling).
if m.cmd
&& cx.select_behind
&& let Some(behind) = object_behind(cx, p)
@@ -293,6 +307,7 @@ impl Tool for SelectionTool {
_ => {}
}
o.extend(self.guides.iter().cloned());
o.extend(self.guide.overlays(cx));
if let Some((p, t)) = &self.measure {
o.push(Overlay::Measure { p: *p, text: t.clone() });
}
@@ -307,6 +322,9 @@ impl Tool for SelectionTool {
State::Corner(_) => return Cursor::CornerRadius,
_ => {}
}
if self.guide.busy() {
return self.guide.cursor(cx, p).unwrap_or_default();
}
if over_widget(cx, p) {
return Cursor::CornerRadius;
}
@@ -319,6 +337,9 @@ impl Tool for SelectionTool {
None => {}
}
}
if let Some(c) = self.guide.cursor(cx, p) {
return c;
}
if let Some(h) = hit_test(cx.doc, p, cx.hit_options()) {
if cx.selection.contains(h.top_object(cx.isolation)) || m.alt {
return Cursor::Move;
@@ -378,6 +399,27 @@ mod tests {
assert!(t.pointer(&cx, &ev(PointerKind::Up, 150.0, 150.0)).is_empty());
}
/// #414: a press on a ruler guide picks it over the art, and drags it.
#[test]
fn a_press_on_a_ruler_guide_picks_it_over_the_art() {
let (mut d, _) = doc_with_rect();
d.guides.push(vectorcraft_doc::Guide { vertical: false, pos: 150.0 });
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&cx, Point::new(160.0, 151.0), Mods::default()), Cursor::ResizeV);
let a = t.pointer(&cx, &ev(PointerKind::Down, 160.0, 151.0));
assert_eq!(a, vec![Action::Exec("guide.select".into(), json!({"indexes": [0]}))]);
assert!(t.busy());
let a = t.pointer(&cx, &ev(PointerKind::Drag, 160.0, 171.0));
assert_eq!(a[1], Action::Preview("guide.move".into(), json!({"dx": 0.0, "dy": 20.0, "copy": false})));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 160.0, 171.0)), vec![Action::Commit]);
assert!(!t.busy());
// A double-click there doesn't go through to the art.
assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 160.0, 150.0)).is_empty());
}
#[test]
fn drag_moves_with_single_undo() {
let (d, id) = doc_with_rect();
+2 -6
View File
@@ -96,7 +96,7 @@ impl ArtboardTool {
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));
return vectorcraft_geom::snap::snap_point_to_grid(p, cx.grid_step());
}
let Some(t) = &self.targets else { return p };
let offsets: &[Vec2] = if bleed == Vec2::ZERO { &[] } else { &[bleed] };
@@ -114,7 +114,7 @@ impl ArtboardTool {
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;
return vectorcraft_geom::snap::snap_point_to_grid(tl + d, cx.grid_step()) - tl;
}
let Some(t) = (if copy { &self.copy_targets } else { &self.targets }) else { return d };
let moved = rect + d;
@@ -144,10 +144,6 @@ fn bleed_offset(cx: &ToolContext, rect: Rect, handle: Handle) -> Vec2 {
}
/// 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 {
fn id(&self) -> &'static str {
"artboard"
+84 -10
View File
@@ -315,7 +315,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
if app.ui.view.guides {
let look = LineLook::guides(&app.session.prefs, &t);
for g in &doc.guides {
// Selected guides in the selection colour.
let picked = LineLook { color: t.selection, ..look };
let selected: &[usize] = app.session.active().map_or(&[], |st| &st.selection.guides);
for (i, g) in doc.guides.iter().enumerate() {
let (a, b) = if g.vertical {
let x = xf.to_screen(Point::new(g.pos, 0.0)).x;
(pos2(x, rect.top()), pos2(x, rect.bottom()))
@@ -323,7 +326,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let y = xf.to_screen(Point::new(0.0, g.pos)).y;
(pos2(rect.left(), y), pos2(rect.right(), y))
};
look.guide(&painter, a, b);
if selected.contains(&i) { picked } else { look }.guide(&painter, a, b);
}
}
@@ -817,23 +820,32 @@ fn ruler_rects(full: egui::Rect) -> [egui::Rect; 3] {
}
/// A drag from a ruler onto the canvas makes a guide where the button is released: a horizontal
/// one from the top ruler, a vertical one from the left ruler. Released anywhere else, it makes
/// none.
/// one from the top ruler, a vertical one from the left ruler; with Shift on the nearest ruler
/// tick. Released anywhere else, it makes none.
fn ruler_guides(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, canvas: egui::Rect, xf: &Xf, t: &Tokens) {
let [top, left, _] = ruler_rects(full);
let shift = ui.input(|i| i.modifiers.shift);
for (r, vertical, id) in [(top, false, "ruler-top"), (left, true, "ruler-left")] {
let resp = ui.interact(r, egui::Id::new(id), Sense::drag());
let Some(p) = resp.interact_pointer_pos().filter(|p| canvas.contains(*p)) else { continue };
let d = xf.to_doc(p);
let mut pos = if vertical { d.x } else { d.y };
if shift {
pos = app.session.general_unit().snap_to_ruler_tick(pos, xf.zoom);
}
if resp.drag_stopped() {
let d = xf.to_doc(p);
// The new guide shows even if guides were hidden.
app.ui.view.guides = true;
if let Err(e) = app.run("guide.add", json!({ "vertical": vertical, "pos": if vertical { d.x } else { d.y } })) {
if let Err(e) = app.run("guide.add", json!({ "vertical": vertical, "pos": pos })) {
app.status(e);
}
} else if resp.dragged() {
let (a, b) =
if vertical { (pos2(p.x, canvas.top()), pos2(p.x, canvas.bottom())) } else { (pos2(canvas.left(), p.y), pos2(canvas.right(), p.y)) };
let at = xf.to_screen(if vertical { Point::new(pos, d.y) } else { Point::new(d.x, pos) });
let (a, b) = if vertical {
(pos2(at.x, canvas.top()), pos2(at.x, canvas.bottom()))
} else {
(pos2(canvas.left(), at.y), pos2(canvas.right(), at.y))
};
LineLook::guides(&app.session.prefs, t).guide(&ui.painter_at(canvas), a, b);
}
}
@@ -853,8 +865,7 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, unit: Unit,
// Pick a label step (in `unit`) that gives ≥ 50 px between labels; positions below are in `unit`
// (`per` points each).
let per = unit.points();
let steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0];
let step = steps.iter().copied().find(|s| s * per * xf.zoom >= 50.0).unwrap_or(10000.0);
let step = unit.ruler_step(xf.zoom);
let minor = step / 10.0;
let font = egui::FontId::proportional(9.5);
let a = xf.to_doc(top.left_top());
@@ -1693,6 +1704,69 @@ mod tests {
assert_eq!(app.session.active().unwrap().doc.art_bounds(), None, "the tool drew nothing");
}
/// #414: guides dragged out of the rulers are picked and dragged with the Selection tool
/// (highlighted while selected), go with Delete or Backspace, and dragged back onto their
/// ruler.
#[test]
fn the_selection_tool_moves_and_deletes_ruler_guides() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
// A square under the guides: the press takes the guide.
app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap();
app.session.execute("select.none", &json!({})).unwrap();
let art = app.session.active().unwrap().doc.art_bounds();
app.ui.view.rulers = true;
app.select_tool("selection");
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let xf = Xf::new(rect, app.view().unwrap());
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(app, &ctx, vec![button(from, true)]);
frame(app, &ctx, vec![egui::Event::PointerMoved(to)]);
frame(app, &ctx, vec![button(to, false)]);
};
let guides = |app: &VectorcraftApp| app.session.active().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos)).collect::<Vec<_>>();
// Two guides out of the rulers.
let (h, v) = (pos2(rect.center().x + 30.0, rect.center().y + 20.0), pos2(rect.center().x - 40.0, rect.center().y));
drag(&mut app, pos2(h.x, rect.top() - RULER / 2.0), h);
drag(&mut app, pos2(rect.left() - RULER / 2.0, v.y), v);
assert_eq!(guides(&app), [(false, xf.to_doc(h).y), (true, xf.to_doc(v).x)]);
// Drag the horizontal one down 30 px (across the vertical one: the nearer is picked).
let to = pos2(h.x + 10.0, h.y + 30.0);
drag(&mut app, h, to);
let st = app.session.active().unwrap();
assert_eq!(guides(&app), [(false, xf.to_doc(to).y), (true, xf.to_doc(v).x)]);
assert_eq!((st.selection.guides.clone(), st.selection.objects.clone()), (vec![0], vec![]));
assert_eq!(st.history.undo.last().unwrap().label, "Move Guide");
let picked = Tokens::get(&ctx).selection;
let s = shapes(&mut app, &ctx);
assert!(s.iter().any(|s| matches!(s, Shape::LineSegment { points, stroke } if stroke.color == picked && points[0].y == to.y)), "highlighted");
// Backspace deletes the selected guide; Delete too.
let press = |app: &mut VectorcraftApp, key| {
let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx()));
out.textures_delta.clear();
};
press(&mut app, egui::Key::Backspace);
assert_eq!(guides(&app), [(true, xf.to_doc(v).x)]);
app.session.execute("guide.select", &json!({"indexes": [0]})).unwrap();
press(&mut app, egui::Key::Delete);
assert!(guides(&app).is_empty());
app.session.execute("edit.undo", &json!({})).unwrap();
// Hide Guides deselects them.
app.session.execute("guide.select", &json!({"indexes": [0]})).unwrap();
app.run("view.guides", json!({})).unwrap();
assert!(app.session.active().unwrap().selection.guides.is_empty());
app.run("view.guides", json!({})).unwrap();
// Dragged back onto its ruler, the vertical guide goes.
drag(&mut app, v, pos2(rect.left() - RULER / 2.0, v.y + 20.0));
assert!(guides(&app).is_empty(), "{:?}", guides(&app));
assert_eq!(app.session.active().unwrap().doc.art_bounds(), art, "the square stayed");
}
#[test]
fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+1
View File
@@ -2273,6 +2273,7 @@
Select art and use New Brush to make one. Selecciona una ilustración y usa Nuevo pincel para crear uno.
Select Freeform Point Seleccionar punto libre
Select Gradient Stop Seleccionar parada de degradado
Select Guides Seleccionar guías
Select Objects Seleccionar objetos
Select objects to see their CSS, or Generate CSS for the whole document. Selecciona objetos para ver su CSS, o usa Generar CSS para todo el documento.
Select Same Tint % Seleccionar mismo % de matiz
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -2844,6 +2844,7 @@
Search 検索
Security セキュリティ
Select All Pins すべてのピンを選択
Select Guides ガイドを選択
Select text or click into text with the Type tool to insert glyphs 字形を挿入するには、テキストを選択するか、文字ツールでテキスト内をクリックしてください
Server-side (.map) サーバーサイド (.map)
Set 1 セット 1
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -2013,6 +2013,7 @@
Select Appearance Item Selecionar Item de Aparência
Select Freeform Point Selecionar Ponto Livre
Select Gradient Stop Selecionar Parada de Gradiente
Select Guides Selecionar Guias
Select Objects Selecionar Objetos
Select Same Tint % Selecionar Mesmo Tom %
Select Slices Selecionar Fatias
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3189,6 +3189,7 @@
Release to Layers (Build) 释放到图层 (累积)
Release to Layers (Sequence) 释放到图层 (顺序)
Select Art 选择图稿
Select Guides 选择参考线
Show All Layers 显示所有图层
Unlock All Layers 解锁所有图层
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -2292,6 +2292,7 @@
Select art and use New Brush to make one. 選取圖稿,然後使用「新增筆刷」來製作。
Select Freeform Point 選取任意形狀點
Select Gradient Stop 選取漸層色標
Select Guides 選取參考線
Select Objects 選取物件
Select objects to see their CSS, or Generate CSS for the whole document. 選取物件以檢視其 CSS,或對整份文件「產生 CSS」。
Select Same Tint % 選取相同色調 %
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -423,6 +423,7 @@ impl VectorcraftApp {
zoom: self.view().map(|v| v.zoom).unwrap_or(1.0),
outline: self.ui.view.outline,
smart_guides: self.ui.view.smart_guides,
guides: self.ui.view.guides,
snap_to_grid: self.ui.view.snap_to_grid,
snap_to_pixel: self.ui.view.snap_to_pixel,
show_bbox: self.ui.view.bounding_box,
+9 -1
View File
@@ -910,7 +910,15 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
"view.artboards" => flag(&mut app.ui.view.artboards),
"view.rulers" => flag(&mut app.ui.view.rulers),
"view.boundingBox" => flag(&mut app.ui.view.bounding_box),
"view.guides" => flag(&mut app.ui.view.guides),
"view.guides" => {
let r = flag(&mut app.ui.view.guides);
// Hidden guides can't stay selected (selected, they are all that is).
if !app.ui.view.guides && app.session.active().is_some_and(|d| !d.selection.guides.is_empty()) {
// Deselecting a document that is open can't fail.
let _ = app.run("select.none", json!({}));
}
r
}
"view.smartGuides" => flag(&mut app.ui.view.smart_guides),
"view.grid" => flag(&mut app.ui.view.grid),
"view.snapToGrid" => flag(&mut app.ui.view.snap_to_grid),
+3 -2
View File
@@ -386,12 +386,13 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
let arrows = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)];
for (k, dx, dy) in arrows {
let m = ctx.input(|i| i.modifiers);
if ctx.input_mut(|i| i.consume_key(m, k)) && app.session.active().is_some_and(|d| !d.selection.is_empty()) {
if ctx.input_mut(|i| i.consume_key(m, k)) && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) {
let _ = app.run("object.nudge", json!({"dx": dx, "dy": dy, "big": m.shift, "copy": m.alt}));
}
}
// Delete / Backspace clear the selection.
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Backspace)) && app.session.active().is_some_and(|d| !d.selection.is_empty()) {
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Backspace)) && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides())
{
let _ = app.run("edit.clear", json!({}));
}
// Single-key tool shortcuts (no Cmd/Ctrl/Alt).
+23
View File
@@ -549,6 +549,29 @@ names must stay unique. In the desktop app the saved selections are listed at th
(`select.recall1` … `select.recall25`). A file's saved selections are checked when it opens: past 25, blank or
repeated names, and ids the document doesn't have are dropped.
## Ruler guides
Ruler guides are numbered in the order they were made. `guide.add {vertical, pos}` makes one (the x of a vertical
guide, the y of a horizontal one, in points) → `{index}`; `guide.list` → `[{index, vertical, pos, selected}…]`.
`guide.select {indexes: [index…], toggle?}` selects guides on their own (the art is deselected; `toggle` adds or
removes them) → `{selected}`. `guide.move {index, pos}` puts one guide somewhere, `guide.move {dx?, dy?, copy?}`
moves the selected ones (vertical guides by `dx`, horizontal ones by `dy`; `copy` leaves them and selects the
moved copies), and `guide.remove {index?}` deletes one guide or the selected ones → `{count}`; each is one undo
step. With guides selected, `edit.clear` (Delete) deletes them and `object.nudge` (the arrow keys) nudges them.
View › Guides › Lock Guides (`view.guides.lock`) deselects them and refuses these commands until unlocked.
The Selection, Direct Selection and Group Selection tools pick a guide within the selection tolerance, over the art
(an anchor on it comes first with Direct Selection), and drag the selected guides: `mods.alt` copies them,
`mods.shift` snaps the dragged guide to the ruler's ticks, and otherwise it snaps to whole pixels, the grid or, with
Smart Guides, the art's edges, centres and anchors. In the desktop app a guide dropped off the canvas onto its
ruler is deleted, and hidden guides (View › Guides › Hide Guides) can't be picked.
```json
{"name":"run_command","arguments":{"command":"guide.add","params":{"vertical":true,"pos":100}}}
{"name":"pointer_gesture","arguments":{"tool":"selection","events":[{"kind":"down","x":100,"y":50},{"kind":"drag","x":140,"y":50},{"kind":"up","x":140,"y":50}]}}
{"name":"run_command","arguments":{"command":"guide.list","params":{}}}
```
## Graphic styles
A graphic style holds an appearance (fills, strokes, effects) plus opacity, blend mode, isolate and knockout.