mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-10-19 05:34:23 -04:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71371b9d58 | ||
|
|
5db200d392 | ||
|
|
c0396c0761 | ||
|
|
c7f1e00955 | ||
|
|
3c91ca8a1d | ||
|
|
7e3bcc48fe | ||
|
|
ac63002df9 | ||
|
|
f6cd4588ee | ||
|
|
aefd961bbd |
No files matched your search
+5
-4
@@ -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), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS files from Illustrator 2026, Inkscape/cairo, matplotlib, CorelDRAW, Affinity, LibreOffice and Ghostscript opening as vectors, and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG window (#493), panels, panel groups and the Tools panel undocking intLine truncated
|
||||
_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), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS files from Illustrator 2026, Inkscape/cairo, matplotlib, CorelDRAW, Affinity, LibreOffice and Ghostscript opening as vectors, and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG window (#493), panels, panel groups and the Tools panel undocking intLine truncated
|
||||
|
||||
## Where we are
|
||||
|
||||
@@ -42,7 +42,7 @@ since 2026-10-01.
|
||||
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
|
||||
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
|
||||
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
|
||||
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
|
||||
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
|
||||
| **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel |
|
||||
| **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) |
|
||||
|
||||
@@ -122,7 +122,8 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **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; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), 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; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442).
|
||||
- **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. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles; drawing then goes on.
|
||||
- **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494).
|
||||
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path).
|
||||
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type.
|
||||
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446), 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.
|
||||
@@ -155,7 +156,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs Illustrator's AGM/CoolType prologs (resource categories, `resourceforall`, `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters, `cshow`, metadata skipped with `flushfile`), so Illustrator 30 EPS files open as vectors. It also runs what other generators write (Discord feedback, #466, #469): Illustrator 2026's procsets (`gcheck`, `rootfont`, `currentcolorrendering`: every Illustrator 2026 EPS fell back to its preview before), cairo/Inkscape (`status`/`flushfile`, images with a mask, `ImageType 3`, reusable streams), matplotlib's Type 3 fonts, Illustrator 8 EPS (stock art's usual format: executable strings such as its gradients' `ed`, `load` by integer keys, #474), Ghostscript's `//name` immediate names, `pdfmark`, `token`, `execform` and user paths. Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
|
||||
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
|
||||
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
|
||||
- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.
|
||||
- **Graphics processor:** the canvas is rasterized on the CPU and the GPU only composites it, so any GPU that can show the window will do. Preferences › Performance › Graphics Processor (`gpuPreference`) is Automatic by default: the power-saving GPU on Windows and macOS (the integrated one on hybrid-graphics laptops, where presenting from the discrete GPU made the window flicker, #306), and the GPU the desktop runs on under Linux, where KWin on an NVIDIA GPU refused frames from a Ryzen's integrated GPU and 0.5.0 crashed at startup (#502). Power Saving and High Performance pick a kind of GPU; `WGPU_POWER_PREF`, `WGPU_ADAPTER_NAME` and `WGPU_BACKEND` override them. The app picks among the adapters that can present to the window (native backends before OpenGL, hardware before software), and if the window fails on one while starting up it starts again without it instead of crashing; Help › About, `ui.inspect` and the log name the adapter in use. When the browser drops the page's WebGPU device or WebGL context, the web build writes recovery copies, starts again on new graphics with the same app and uploads its textures again; if it can't, it removes the stale canvas and says to reload, which offers the copies back. The desktop app writes the copies and says to restart (#369). On Windows and Linux the tools' cursors are OS cursors (bitmaps rasterized once per display scale), which the system moves itself: painted into the window, they trailed the pointer by the frames waiting to be shown, and the window now queues one frame instead of two (#444). macOS and the web still paint them (macOS sizes cursor bitmaps in points, eframe has no bitmap cursors on the web). Pens and touch drive the tools as the mouse does, and a tap pressed and lifted within one frame clicks where it tapped (#491); pen pressure reaches the Liquify tools' Use Pressure Pen on Windows, while winit 0.30 reports none on macOS or Linux and egui none on the web. On Linux, see `docs/development.md` for pens under Wayland.
|
||||
- **Tests and robustness:** ~2,840 automated tests: model-based property tests, a junk-parameter sweep over every command, import fuzzing (SVG, PDF, libraries), golden renders, and MCP end-to-end tests over stdio. Shipped code never panics (workspace lints and a rollback safety net; see `docs/development.md`).
|
||||
|
||||
@@ -70,6 +70,49 @@ fn load_average() -> Option<f64> {
|
||||
text.split_whitespace().map(|t| t.trim_matches(|c| c == '{' || c == '}')).find_map(|t| t.parse().ok())
|
||||
}
|
||||
|
||||
/// Milliseconds per pointer move of a Direct Selection drag of a handle, then of a segment, of a
|
||||
/// 5,000-anchor wave of smooth anchors added on top of the synthetic `n`-path document.
|
||||
fn edit_drags(n: usize) -> Result<(f64, f64), String> {
|
||||
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
|
||||
use vectorcraft_geom::{Anchor, PathData, SubPath, Vec2};
|
||||
let mut doc = synthetic(n)?;
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let id = doc.alloc_id();
|
||||
// Anchors 2 pt apart, up and down by 20 pt, their handles 0.6 pt long.
|
||||
let anchor = |i: usize| {
|
||||
let p = Point::new(i as f64 * 2.0, if i.is_multiple_of(2) { 500.0 } else { 520.0 });
|
||||
Anchor::smooth(p, p + Vec2::new(0.6, 0.0))
|
||||
};
|
||||
let path = PathData::single(SubPath::new((0..5000).map(anchor).collect(), false));
|
||||
doc.insert(l, usize::MAX, Node::path(id, path, Appearance::default_art())).map_err(|e| e.to_string())?;
|
||||
let mut s = vectorcraft_engine::Session::new();
|
||||
s.add_document(doc, None);
|
||||
let view = vectorcraft_engine::ViewInfo { zoom: 8.0, ..Default::default() };
|
||||
let err = |e: vectorcraft_engine::EngineError| e.to_string();
|
||||
let mut drag = |down: Point| -> Result<f64, String> {
|
||||
let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), pressure: 1.0 };
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 400]]})).map_err(err)?;
|
||||
s.select_tool("directSelection", view).map_err(err)?;
|
||||
let undo = s.doc().map_err(err)?.history.undo.len();
|
||||
s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?;
|
||||
let mut y = 0.0;
|
||||
let ms = median_ms(9, || {
|
||||
y += 3.0;
|
||||
// A failed move shows as the missing undo step below.
|
||||
let _ = s.pointer(&ev(PointerKind::Drag, y), view);
|
||||
});
|
||||
s.pointer(&ev(PointerKind::Up, y), view).map_err(err)?;
|
||||
if s.doc().map_err(err)?.history.undo.len() != undo + 1 {
|
||||
return Err(format!("the drag from {down:?} made no undo step"));
|
||||
}
|
||||
Ok(ms)
|
||||
};
|
||||
// Anchor 400 is at (800, 500): its outgoing handle's end, then its segment to anchor 401.
|
||||
let handle = drag(Point::new(800.6, 500.0))?;
|
||||
let segment = drag(Point::new(801.0, 510.0))?;
|
||||
Ok((handle, segment))
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let mut n = 50_000usize;
|
||||
let mut it = args.iter();
|
||||
@@ -145,6 +188,15 @@ pub fn run(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
});
|
||||
rows.push(("Pathfinder Unite, 1,000 paths", unite, 150.0));
|
||||
|
||||
// Path editing: one pointer move of a Direct Selection drag (the tool event and the preview it
|
||||
// applies), on a 5,000-anchor path among the synthetic paths.
|
||||
let (handle, segment) = edit_drags(n).unwrap_or_else(|e| {
|
||||
failed = Some(e);
|
||||
(0.0, 0.0)
|
||||
});
|
||||
rows.push(("handle drag, 5,000-anchor path (per move)", handle, 8.0));
|
||||
rows.push(("segment drag, 5,000-anchor path (per move)", segment, 8.0));
|
||||
if let Some(e) = failed {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ mod window;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::{FilePick, Services, VectorcraftApp};
|
||||
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
|
||||
|
||||
struct App {
|
||||
app: VectorcraftApp,
|
||||
@@ -256,6 +256,10 @@ fn services() -> Services {
|
||||
write_shared: Some(std::sync::Arc::new(write_file)),
|
||||
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
|
||||
system_clipboard: Some(clipboard::system_clipboard()),
|
||||
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
|
||||
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
|
||||
// clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory),
|
||||
// Help → Discord / website / GitHub, the Discord button, About and Home links.
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
let _ = webbrowser::open(url);
|
||||
|
||||
@@ -701,13 +701,16 @@ fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
let n = sp.anchors.len();
|
||||
// Moving both inner control points by v moves B(t) by 3t(1-t)·v.
|
||||
// Moving both inner control points by v moves B(t) by 3t(1-t)·v. A smooth anchor stays
|
||||
// smooth: its other handle turns with the moved one.
|
||||
let v = dv / (3.0 * t * (1.0 - t));
|
||||
let (i0, i1) = (seg % n, (seg + 1) % n);
|
||||
let a = sp.anchors[i0];
|
||||
sp.anchors[i0] = Anchor::with_handles(a.p, a.h_in, a.h_out + v);
|
||||
let b = sp.anchors[i1];
|
||||
sp.anchors[i1] = Anchor::with_handles(b.p, b.h_in + v, b.h_out);
|
||||
if let Some(a) = sp.anchors.get_mut(i0) {
|
||||
a.set_handle(true, a.h_out + v, false);
|
||||
}
|
||||
if let Some(b) = sp.anchors.get_mut(i1) {
|
||||
b.set_handle(false, b.h_in + v, false);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -721,6 +721,12 @@ pub struct Session {
|
||||
/// Executed commands (for actions and debugging).
|
||||
pub journal: Vec<(String, Value)>,
|
||||
pub(crate) tool: Box<dyn Tool>,
|
||||
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
|
||||
/// back as it was at the release ([`Session::pointer`]).
|
||||
pub(crate) lender: Option<Box<dyn Tool>>,
|
||||
/// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd
|
||||
/// lends the other tools. None until one is chosen.
|
||||
pub(crate) last_selection_tool: Option<&'static str>,
|
||||
pub(crate) last_view: ViewInfo,
|
||||
depth: u32,
|
||||
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
|
||||
@@ -800,6 +806,8 @@ impl Session {
|
||||
clipboard: Clipboard::default(),
|
||||
journal: vec![],
|
||||
tool: vectorcraft_tools::create("selection"),
|
||||
lender: None,
|
||||
last_selection_tool: None,
|
||||
last_view: ViewInfo::default(),
|
||||
depth: 0,
|
||||
tool_panic: None,
|
||||
@@ -858,6 +866,8 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let view = self.last_view;
|
||||
// The switch goes on whatever the lent tool's last actions did, as for the deactivation.
|
||||
let _ = self.give_back_tool(view);
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
let _ = self.apply_actions(acts);
|
||||
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
|
||||
|
||||
@@ -57,6 +57,20 @@ fn click(s: &mut Session, tool: &str, x: f64, y: f64) -> Vec<UiRequest> {
|
||||
drag(s, tool, &[(x, y)], Mods::default())
|
||||
}
|
||||
|
||||
/// A gesture of the active tool, `m` held throughout: press at the first point, drag through the
|
||||
/// others, release at the last. The undo steps it made.
|
||||
fn gesture(s: &mut Session, pts: &[(f64, f64)], m: Mods) -> usize {
|
||||
let v = view();
|
||||
let undo = undo_steps(s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap();
|
||||
for &(x, y) in &pts[1..] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap();
|
||||
}
|
||||
let l = pts[pts.len() - 1];
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap();
|
||||
undo_steps(s) - undo
|
||||
}
|
||||
|
||||
/// A wavy stroke sampled every 2 pt.
|
||||
fn wave(x0: f64, x1: f64, y: f64) -> Vec<(f64, f64)> {
|
||||
let n = ((x1 - x0) / 2.0) as usize;
|
||||
@@ -622,16 +636,6 @@ fn pen_with_alt_moves_one_handle_and_converts_anchors() {
|
||||
let anchors = json!([{"x": 100, "y": 200}, {"x": 200, "y": 100, "in": [150, 100], "out": [250, 100]}, {"x": 300, "y": 200}]);
|
||||
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select_tool("pen", v).unwrap();
|
||||
let gesture = |s: &mut Session, pts: &[(f64, f64)], m: Mods| {
|
||||
let undo = undo_steps(s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap();
|
||||
for &(x, y) in &pts[1..] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap();
|
||||
}
|
||||
let l = pts[pts.len() - 1];
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap();
|
||||
undo_steps(s) - undo
|
||||
};
|
||||
// Alt-drag the out handle: it moves alone, the in handle stays.
|
||||
assert_eq!(gesture(&mut s, &[(250.0, 100.0), (260.0, 130.0), (275.0, 165.0)], alt), 1);
|
||||
assert!(!s.in_interaction());
|
||||
@@ -659,3 +663,130 @@ fn pen_with_alt_moves_one_handle_and_converts_anchors() {
|
||||
assert_eq!(path(&s, new).subpaths[0].anchors.len(), 3);
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
}
|
||||
|
||||
/// The anchor's handles point opposite ways.
|
||||
fn smooth(a: vectorcraft_geom::Anchor) -> bool {
|
||||
let (i, o) = (a.h_in - a.p, a.h_out - a.p);
|
||||
(i.x * o.y - i.y * o.x).abs() < 1e-6 && i.x * o.x + i.y * o.y < 0.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_with_cmd_borrows_direct_selection_and_goes_on_drawing() {
|
||||
// #494: Cmd (Ctrl) held with the Pen drags with the selection tool used last (Direct Selection
|
||||
// until one is chosen): handles, segments and anchors of the path being drawn; released, the
|
||||
// Pen goes on drawing that path. Through pointer events, so agents reach it too.
|
||||
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
gesture(&mut s, &[(100.0, 300.0)], none);
|
||||
gesture(&mut s, &[(200.0, 300.0), (250.0, 300.0)], none);
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(s.cursor(Point::new(250.0, 300.0), none, v), vectorcraft_tools::Cursor::Pen);
|
||||
assert_eq!(s.cursor(Point::new(250.0, 300.0), cmd, v), vectorcraft_tools::Cursor::ArrowHollow, "Direct Selection's");
|
||||
// The new anchor's outgoing handle: it moves, its incoming one turning with it.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 260.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 260.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
let a = path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(a.h_out == Point::new(250.0, 260.0) && smooth(a), "{a:?}");
|
||||
// The segment between the two anchors bends, the smooth anchor staying smooth.
|
||||
let before = path(&s, id).subpaths[0].anchors[1].h_in;
|
||||
gesture(&mut s, &[(120.0, 300.0), (120.0, 270.0)], cmd);
|
||||
let a = path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(a.h_in != before && smooth(a), "{a:?}");
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
// A plain click goes on drawing the same path.
|
||||
gesture(&mut s, &[(300.0, 350.0)], none);
|
||||
assert_eq!((paths(&s).len(), path(&s, id).subpaths[0].anchors.len()), (1, 3));
|
||||
// A Cmd-click away from the art deselects: the path is done, the next click starts another.
|
||||
gesture(&mut s, &[(600.0, 100.0)], cmd);
|
||||
gesture(&mut s, &[(400.0, 500.0)], none);
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3);
|
||||
// With the Selection tool chosen last, Cmd lends it.
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 100.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 600.0, 100.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
// Choosing a tool mid-gesture keeps it: the Pen doesn't come back over it.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 100.0).with_mods(cmd), v).unwrap();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 600.0, 100.0), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reshaping_a_segment_keeps_smooth_anchors_smooth() {
|
||||
// #494: the anchors at the ends of a dragged segment keep their kind: a smooth one's other
|
||||
// handle turns with the moved one (at its length), a corner's stays.
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 100, "y": 300}, {"x": 200, "y": 300, "in": [160, 300], "out": [240, 300]}, {"x": 300, "y": 300}]);
|
||||
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("path.reshapeSegment", &json!({"id": id.0, "segment": 0, "t": 0.5, "dx": 0, "dy": -30})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
let a = sp.anchors[1];
|
||||
assert!(near(a.h_in, Point::new(160.0, 260.0)) && smooth(a), "{a:?}");
|
||||
assert!((a.h_out.distance(a.p) - 40.0).abs() < 1e-9, "its length kept");
|
||||
assert!(near(sp.anchors[0].h_out, Point::new(100.0, 260.0)) && !sp.anchors[0].has_in(), "the corner end: {:?}", sp.anchors[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_drag_from_the_first_anchor_closes_the_path() {
|
||||
// #501: closing a path by dragging out of its first anchor flickered between a close and a new
|
||||
// path, and released at the wrong moment left the shape open. The press decides: the drag
|
||||
// shapes the closing curve, symmetric, and the release closes the path wherever it ends.
|
||||
let none = Mods::default();
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
for (x, y) in [(100.0, 300.0), (200.0, 300.0), (200.0, 400.0)] {
|
||||
gesture(&mut s, &[(x, y)], none);
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
let pts: Vec<(f64, f64)> = (0..=12).map(|i| (100.0 + 5.0 * f64::from(i), 300.0 - 4.0 * f64::from(i))).collect();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap();
|
||||
for &(x, y) in &pts[1..] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
let p = path(&s, id);
|
||||
assert!(p.subpaths[0].closed && paths(&s).len() == 1, "closed throughout the drag, at ({x}, {y})");
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 160.0, 252.0), v).unwrap();
|
||||
assert!(!s.in_interaction());
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() == 3, "{sp:?}");
|
||||
let a = sp.anchors[0];
|
||||
assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(160.0, 252.0)), "symmetric");
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
// The next click starts a new path.
|
||||
gesture(&mut s, &[(500.0, 500.0)], none);
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_with_alt_converts_the_anchors_of_the_path_being_drawn() {
|
||||
// #504: while drawing, Alt-click on a smooth anchor of the path makes it a corner and Alt-drag
|
||||
// on a corner one pulls out smooth handles; the next click goes on drawing the path.
|
||||
let (none, alt) = (Mods::default(), Mods { alt: true, ..Mods::default() });
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
gesture(&mut s, &[(100.0, 300.0)], none);
|
||||
gesture(&mut s, &[(200.0, 300.0), (240.0, 300.0)], none);
|
||||
gesture(&mut s, &[(300.0, 400.0)], none);
|
||||
gesture(&mut s, &[(400.0, 300.0)], none);
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert!(smooth(path(&s, id).subpaths[0].anchors[1]));
|
||||
assert_eq!(gesture(&mut s, &[(200.0, 300.0)], alt), 1);
|
||||
let a = path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(!a.has_in() && !a.has_out(), "a corner: {a:?}");
|
||||
assert_eq!(gesture(&mut s, &[(300.0, 400.0), (320.0, 400.0), (340.0, 400.0)], alt), 1);
|
||||
let a = path(&s, id).subpaths[0].anchors[2];
|
||||
assert!(smooth(a) && a.h_out == Point::new(340.0, 400.0), "smooth: {a:?}");
|
||||
gesture(&mut s, &[(500.0, 400.0)], none);
|
||||
assert_eq!((paths(&s).len(), path(&s, id).subpaths[0].anchors.len()), (1, 5));
|
||||
}
|
||||
@@ -82,6 +82,7 @@ impl Session {
|
||||
/// Switch to tool `id` without choosing it afresh (back from a temporary tool: a hidden
|
||||
/// perspective grid stays hidden), finishing any pending tool work first.
|
||||
pub fn switch_tool(&mut self, id: &str, view: ViewInfo) -> Result<()> {
|
||||
self.give_back_tool(view)?;
|
||||
if self.tool.id() == id {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -89,9 +90,47 @@ impl Session {
|
||||
self.apply_actions(acts)?;
|
||||
self.keep_tool_settings();
|
||||
self.tool = self.make_tool(id);
|
||||
if vectorcraft_tools::catalog::is_selection_tool(id) {
|
||||
self.last_selection_tool = Some(self.tool.id());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The selection tool Cmd lends tool `id` for a drag: the one chosen last; until one is,
|
||||
/// Direct Selection to the tools that edit anchors (the Pen) and Selection to the others.
|
||||
/// None for the selection tools themselves and the view tools.
|
||||
fn lent_tool(&self, id: &str) -> Option<&'static str> {
|
||||
use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool};
|
||||
if is_selection_tool(id) || matches!(id, "hand" | "zoom" | "rotateView") {
|
||||
return None;
|
||||
}
|
||||
Some(self.last_selection_tool.unwrap_or(if edits_anchors(id) { "directSelection" } else { "selection" }))
|
||||
}
|
||||
|
||||
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
|
||||
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
|
||||
/// not Select Behind). The tool lent to stays as it was, unaware, until the release.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> PointerEvent {
|
||||
if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() {
|
||||
return *ev;
|
||||
}
|
||||
let Some(id) = self.lent_tool(self.tool.id()) else { return *ev };
|
||||
let lent = self.make_tool(id);
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }
|
||||
}
|
||||
|
||||
/// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the
|
||||
/// Pen goes on drawing its path).
|
||||
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
|
||||
let Some(lender) = self.lender.take() else { return Ok(()) };
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
let r = self.apply_actions(acts);
|
||||
self.keep_tool_settings();
|
||||
self.tool = lender;
|
||||
r.map(drop)
|
||||
}
|
||||
|
||||
/// A fresh `id` tool with the options it keeps ([`settings`]): its last values, from this
|
||||
/// session or a saved one.
|
||||
pub(crate) fn make_tool(&self, id: &str) -> Box<dyn Tool> {
|
||||
@@ -212,13 +251,19 @@ impl Session {
|
||||
if let Some(r) = self.plane_widget_pointer(ev, view) {
|
||||
return r;
|
||||
}
|
||||
let ev = &self.lend_selection_tool(ev);
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
self.take_tool_panic()?;
|
||||
// A gesture may change options (Alt-drag sizes a Liquify brush): keep them.
|
||||
let r = self.take_tool_panic().and_then(|()| {
|
||||
// A gesture may change options (Alt-drag sizes a Liquify brush): keep them.
|
||||
if ev.kind == PointerKind::Up {
|
||||
self.keep_tool_settings();
|
||||
}
|
||||
self.apply_actions(acts)
|
||||
});
|
||||
if ev.kind == PointerKind::Up {
|
||||
self.keep_tool_settings();
|
||||
self.give_back_tool(view)?;
|
||||
}
|
||||
self.apply_actions(acts)
|
||||
r
|
||||
}
|
||||
|
||||
/// A guide dragged out of a ruler, whatever the tool: a vertical one out of the left ruler, a
|
||||
@@ -325,9 +370,20 @@ impl Session {
|
||||
}
|
||||
|
||||
/// The pointer the active tool shows at `p` (General › Use Precise Cursors makes the drawing
|
||||
/// tools' a crosshair, [`Cursor::precise`]).
|
||||
/// tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
|
||||
/// press would borrow ([`Self::lend_selection_tool`]).
|
||||
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
|
||||
let c = self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods));
|
||||
let lent = if mods.cmd && self.lender.is_none() { self.lent_tool(self.tool.id()) } else { None };
|
||||
let c = match lent {
|
||||
Some(id) => {
|
||||
let lent = self.make_tool(id);
|
||||
let own = std::mem::replace(&mut self.tool, lent);
|
||||
let c = self.with_tool_cx(view, |t, cx| t.cursor(cx, p, Mods { cmd: false, ..mods }));
|
||||
self.tool = own;
|
||||
c
|
||||
}
|
||||
None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)),
|
||||
};
|
||||
if self.prefs.use_precise_cursors { c.precise() } else { c }
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,8 @@ mod tests_links;
|
||||
#[cfg(test)]
|
||||
mod tests_liquify;
|
||||
#[cfg(test)]
|
||||
mod tests_pen;
|
||||
#[cfg(test)]
|
||||
mod tests_persp;
|
||||
#[cfg(test)]
|
||||
mod tests_place;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! The Pen over MCP, headless: `pointer_gesture` with the modifiers held as on the desktop.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Backend, Headless, call_tool};
|
||||
|
||||
fn text(r: &crate::ToolResult) -> Value {
|
||||
assert!(!r.is_error, "{r:?}");
|
||||
serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// A press at the first point, drags through the others, the release at the last.
|
||||
fn gesture(pts: &[(f64, f64)]) -> Value {
|
||||
let (first, last) = (pts[0], pts[pts.len() - 1]);
|
||||
let mut events = vec![json!({"kind": "down", "x": first.0, "y": first.1})];
|
||||
events.extend(pts[1..].iter().map(|(x, y)| json!({"kind": "drag", "x": x, "y": y})));
|
||||
events.push(json!({"kind": "up", "x": last.0, "y": last.1}));
|
||||
json!({ "events": events })
|
||||
}
|
||||
|
||||
/// The anchors of each path, in paint order.
|
||||
fn paths(h: &Headless) -> Vec<Vec<vectorcraft_geom::Anchor>> {
|
||||
let mut v = vec![];
|
||||
h.session.doc().unwrap().doc.walk(|n| {
|
||||
if let Some(p) = n.path_data() {
|
||||
v.push(p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect());
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
/// #494: Cmd held at the press borrows Direct Selection from the Pen; the path goes on afterwards.
|
||||
#[test]
|
||||
fn cmd_with_the_pen_edits_the_path_being_drawn() {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 800, "height": 600}})).unwrap();
|
||||
text(&call_tool(&mut h, "select_tool", &json!({"tool": "pen"})));
|
||||
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[(100.0, 300.0)])));
|
||||
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[(200.0, 300.0), (250.0, 300.0)])));
|
||||
let mut drag = gesture(&[(250.0, 300.0), (250.0, 280.0), (250.0, 263.0)]);
|
||||
drag["mods"] = json!({"cmd": true});
|
||||
let r = text(&call_tool(&mut h, "pointer_gesture", &drag));
|
||||
assert_eq!(r["tool"], "pen", "{r}");
|
||||
assert_eq!(paths(&h)[0][1].h_out, vectorcraft_geom::Point::new(250.0, 263.0));
|
||||
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[(300.0, 350.0)])));
|
||||
assert_eq!(paths(&h).iter().map(Vec::len).collect::<Vec<_>>(), [3], "the same path, three anchors");
|
||||
}
|
||||
|
||||
/// #501: a drag out of the first anchor closes the path, shaping the closing curve.
|
||||
#[test]
|
||||
fn a_drag_from_the_first_anchor_closes_the_path() {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 800, "height": 600}})).unwrap();
|
||||
text(&call_tool(&mut h, "select_tool", &json!({"tool": "pen"})));
|
||||
for p in [(100.0, 300.0), (200.0, 300.0), (200.0, 400.0)] {
|
||||
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[p])));
|
||||
}
|
||||
let close: Vec<(f64, f64)> = (0..=12).map(|i| (100.0 + 5.0 * f64::from(i), 300.0 - 4.0 * f64::from(i))).collect();
|
||||
text(&call_tool(&mut h, "pointer_gesture", &gesture(&close)));
|
||||
let d = &h.session.doc().unwrap().doc;
|
||||
let mut closed = vec![];
|
||||
d.walk(|n| closed.extend(n.path_data().map(|p| p.is_closed())));
|
||||
assert_eq!(closed, [true], "one path, closed");
|
||||
let first = paths(&h)[0][0];
|
||||
assert_eq!((first.h_in, first.h_out), (vectorcraft_geom::Point::new(40.0, 348.0), vectorcraft_geom::Point::new(160.0, 252.0)));
|
||||
}
|
||||
@@ -154,6 +154,17 @@ pub fn group_of(id: &str) -> Option<usize> {
|
||||
TOOL_GROUPS.iter().position(|g| g.iter().any(|t| t.id == id))
|
||||
}
|
||||
|
||||
/// Selection, Direct Selection and Group Selection: the tools Cmd held lends the others for a drag.
|
||||
pub fn is_selection_tool(id: &str) -> bool {
|
||||
matches!(id, "selection" | "directSelection" | "groupSelection")
|
||||
}
|
||||
|
||||
/// The tools that show a selected path's anchors and handles as Direct Selection does, and drag
|
||||
/// them: a Cmd drag with one of them is a Direct Selection drag until a selection tool is chosen.
|
||||
pub fn edits_anchors(id: &str) -> bool {
|
||||
matches!(id, "directSelection" | "pen" | "addAnchor" | "deleteAnchor" | "anchorPoint" | "curvature")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -178,5 +189,7 @@ mod tests {
|
||||
assert_eq!(tool_for_shortcut("V").unwrap().id, "selection");
|
||||
assert_eq!(tool_for_shortcut("Shift+M").unwrap().id, "shapeBuilder");
|
||||
assert_eq!(group_of("star"), group_of("rectangle"));
|
||||
assert!(is_selection_tool("groupSelection") && !is_selection_tool("pen"));
|
||||
assert!(edits_anchors("pen") && !edits_anchors("rectangle"));
|
||||
}
|
||||
}
|
||||
+88
-22
@@ -28,11 +28,11 @@ use std::borrow::Cow;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::hit::{HitKind, hit_test};
|
||||
use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, Rect};
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, Rect};
|
||||
|
||||
use crate::bbox::move_delta;
|
||||
use crate::corners::{self, CornerDrag, over_widget};
|
||||
use crate::guides::{PointSnap, Targets};
|
||||
use crate::guides::{HandleSnap, PointSnap, Targets};
|
||||
use crate::meshedit::MeshEdit;
|
||||
use crate::pathtype::{self, BracketDrag, over_bracket};
|
||||
use crate::rulerguide::GuideEdit;
|
||||
@@ -112,6 +112,8 @@ pub struct DirectSelectionTool {
|
||||
guides: Vec<Overlay>,
|
||||
/// What the dragged anchors snap to, gathered when the drag begins.
|
||||
anchor_snap: Option<PointSnap>,
|
||||
/// What the dragged handle snaps to.
|
||||
handle_snap: HandleSnap,
|
||||
/// What the objects being moved snap to, gathered when the move begins.
|
||||
move_snap: Option<MoveSnap>,
|
||||
/// The anchor under the pointer (Highlight anchors on mouse over): its path, where it is.
|
||||
@@ -128,6 +130,7 @@ impl DirectSelectionTool {
|
||||
mesh: MeshEdit::default(),
|
||||
guides: vec![],
|
||||
anchor_snap: None,
|
||||
handle_snap: HandleSnap::default(),
|
||||
move_snap: None,
|
||||
hover: None,
|
||||
guide: GuideEdit::default(),
|
||||
@@ -217,30 +220,37 @@ fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec<A
|
||||
})
|
||||
}
|
||||
|
||||
/// Selection & Anchor Display → Show handles when multiple anchors are selected: off, handles show
|
||||
/// (and drag) only while a single anchor is selected.
|
||||
pub fn handles_shown(selection: &vectorcraft_doc::Selection, multiple: bool) -> bool {
|
||||
multiple || selection.anchors.values().map(|set| set.len()).sum::<usize>() <= 1
|
||||
/// The anchors whose direction handles show, and drag, with the tools that edit anchors
|
||||
/// ([`crate::catalog::edits_anchors`]): the direct-selected anchors of a path, every anchor of a
|
||||
/// path selected as a whole. Selection & Anchor Display → Show handles when multiple anchors are
|
||||
/// selected off, none while more than one anchor is selected.
|
||||
fn handle_anchors(cx: &ToolContext) -> Vec<(NodeId, usize, usize, Anchor)> {
|
||||
let mut v = vec![];
|
||||
for &id in &cx.selection.objects {
|
||||
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
|
||||
let shown = cx.selection.partial(id);
|
||||
v.extend(pd.anchors().filter(|(si, ai, _)| shown.is_none_or(|set| set.contains(&(*si, *ai)))).map(|(si, ai, a)| (id, si, ai, *a)));
|
||||
}
|
||||
if !cx.handles_multiple && v.len() > 1 {
|
||||
v.clear();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Direction handle of a partially selected anchor under `p`: (id, si, ai, is_out).
|
||||
fn hit_handle(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, bool)> {
|
||||
if !handles_shown(cx.selection, cx.handles_multiple) {
|
||||
return None;
|
||||
}
|
||||
for (id, set) in &cx.selection.anchors {
|
||||
let Some(pd) = cx.doc.node(*id).and_then(|n| n.path_data()) else { continue };
|
||||
for &(si, ai) in set {
|
||||
let Some(a) = pd.subpaths.get(si).and_then(|s| s.anchors.get(ai)) else { continue };
|
||||
if a.has_out() && a.h_out.distance(p) <= tol {
|
||||
return Some((*id, si, ai, true));
|
||||
}
|
||||
if a.has_in() && a.h_in.distance(p) <= tol {
|
||||
return Some((*id, si, ai, false));
|
||||
/// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and
|
||||
/// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path,
|
||||
/// subpath, anchor, is_out).
|
||||
pub(crate) fn hit_handle(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, bool)> {
|
||||
let mut best: Option<((NodeId, usize, usize, bool), f64)> = None;
|
||||
for (id, si, ai, a) in handle_anchors(cx) {
|
||||
for (out, has, h) in [(true, a.has_out(), a.h_out), (false, a.has_in(), a.h_in)] {
|
||||
let d = h.distance(p);
|
||||
if has && d <= tol && d < a.p.distance(p) && best.is_none_or(|b| d < b.1) {
|
||||
best = Some(((id, si, ai, out), d));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
best.map(|b| b.0)
|
||||
}
|
||||
|
||||
fn anchors_json(v: &[AnchorRef]) -> Value {
|
||||
@@ -335,6 +345,7 @@ impl Tool for DirectSelectionTool {
|
||||
self.mesh.unfocus();
|
||||
if let Some((id, si, ai, out)) = hit_handle(cx, p, tol) {
|
||||
self.state = State::Handle { id, si, ai, out };
|
||||
self.handle_snap = HandleSnap::default();
|
||||
return vec![Action::Begin("Reshape".into())];
|
||||
}
|
||||
if let Some((id, anchor, from)) = hit_spine_point(cx, p, tol) {
|
||||
@@ -471,7 +482,7 @@ impl Tool for DirectSelectionTool {
|
||||
out
|
||||
}
|
||||
(PointerKind::Drag, State::Handle { id, si, ai, out }) => {
|
||||
let (q, guides) = crate::guides::snap_handle(cx, (id, si, ai), p, ev.mods.shift);
|
||||
let (q, guides) = self.handle_snap.snap(cx, (id, si, ai), p, ev.mods.shift);
|
||||
self.guides = guides;
|
||||
vec![Action::Preview(
|
||||
"path.setHandle".into(),
|
||||
@@ -871,6 +882,61 @@ mod tests {
|
||||
assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "object.transform"), "{a:?}");
|
||||
}
|
||||
|
||||
/// #494: the handles shown are the handles dragged. A path selected as a whole (the one the
|
||||
/// Pen just drew) shows all its handles, and they drag; the direct-selected anchors' handles
|
||||
/// only otherwise; none with Show handles when multiple anchors are selected off and several
|
||||
/// anchors selected. A handle shorter than the tolerance leaves its anchor to be picked, and
|
||||
/// the tolerance is the preference's, in screen pixels at any zoom.
|
||||
#[test]
|
||||
fn the_handles_shown_are_the_handles_dragged() {
|
||||
let (d, arch) = arch_doc();
|
||||
let p = paint();
|
||||
// Does a press at (x, y) take a handle?
|
||||
let handle = |c: &ToolContext, x: f64, y: f64| {
|
||||
DirectSelectionTool::new(false).pointer(c, &PointerEvent::new(PointerKind::Down, x, y)) == vec![Action::Begin("Reshape".into())]
|
||||
};
|
||||
let mut whole = Selection::default();
|
||||
whole.set([arch]);
|
||||
let c = cx(&d, &whole, &p);
|
||||
assert!(handle(&c, 101.0, 251.0), "the first anchor's handle, the path selected whole");
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 101.0, 251.0));
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 120.0, 240.0));
|
||||
assert!(matches!(&a[..], [Action::Preview(c, v)] if c == "path.setHandle" && v["anchor"] == 0 && v["which"] == "out"), "{a:?}");
|
||||
// Only the second anchor direct-selected: the first one's handle is hidden.
|
||||
let second = anchors_of(arch, &[(0, 1)]);
|
||||
assert!(!handle(&cx(&d, &second, &p), 101.0, 251.0));
|
||||
assert!(handle(&cx(&d, &second, &p), 201.0, 251.0));
|
||||
// Show handles when multiple anchors are selected off: the whole path's are hidden.
|
||||
assert!(!handle(&ToolContext { handles_multiple: false, ..cx(&d, &whole, &p) }, 101.0, 251.0));
|
||||
assert!(handle(&ToolContext { handles_multiple: false, ..cx(&d, &second, &p) }, 201.0, 251.0));
|
||||
// The tolerance is the preference's, in screen pixels: 3 px is 0.75 pt at 400%.
|
||||
let zoomed = ToolContext { zoom: 4.0, ..cx(&d, &whole, &p) };
|
||||
assert!(!handle(&zoomed, 101.0, 251.0));
|
||||
assert!(handle(&zoomed, 100.5, 250.5));
|
||||
assert!(handle(&ToolContext { selection_tolerance: 8.0, ..cx(&d, &whole, &p) }, 106.0, 254.0));
|
||||
}
|
||||
|
||||
/// #494: a handle 2 pt long, inside the tolerance round its anchor, doesn't hide the anchor.
|
||||
#[test]
|
||||
fn a_short_handle_leaves_its_anchor_to_be_picked() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false);
|
||||
sp.anchors[0].h_out = Point::new(102.0, 300.0);
|
||||
d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, PathData::single(sp), vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let s = anchors_of(id, &[(0, 0)]);
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), vec![], "the anchor, already selected");
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 90.0, 290.0));
|
||||
assert_eq!(a[0], Action::Begin("Move".into()));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 90.0, 290.0));
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 102.5, 300.0)), vec![Action::Begin("Reshape".into())], "the handle");
|
||||
}
|
||||
|
||||
/// [`doc_with_rect`] (A, 100..200) and a second square B, 300..400: (A, B).
|
||||
fn two_squares() -> (vectorcraft_doc::Document, NodeId, NodeId) {
|
||||
let (mut d, a) = doc_with_rect();
|
||||
|
||||
@@ -15,7 +15,6 @@ use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath};
|
||||
use crate::{Action, Tool, ToolContext};
|
||||
|
||||
pub use anchor::AnchorTool;
|
||||
pub(crate) use anchor::hit_handle;
|
||||
pub use curvature::CurvatureTool;
|
||||
pub use family::FamilyTool;
|
||||
pub use gesture::GestureTool;
|
||||
|
||||
@@ -12,6 +12,8 @@ use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::{hit_anchor, hit_segment, insert_anchor, remove_anchor};
|
||||
use crate::direct::hit_handle;
|
||||
use crate::guides::HandleSnap;
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -25,8 +27,9 @@ enum State {
|
||||
pub struct AnchorTool {
|
||||
id: &'static str,
|
||||
state: State,
|
||||
/// Smart guides of the handle being dragged.
|
||||
/// Smart guides of the handle being dragged, and what it snaps to.
|
||||
guides: Vec<Overlay>,
|
||||
snap: HandleSnap,
|
||||
}
|
||||
|
||||
impl AnchorTool {
|
||||
@@ -37,36 +40,18 @@ impl AnchorTool {
|
||||
"scissors" => "scissors",
|
||||
_ => "addAnchor",
|
||||
};
|
||||
Self { id, state: State::Idle, guides: vec![] }
|
||||
Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default() }
|
||||
}
|
||||
|
||||
fn add(cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
hit_segment(cx, p, cx.tol(4.0)).map(insert_anchor).into_iter().collect()
|
||||
hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
|
||||
}
|
||||
|
||||
fn delete(cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
hit_anchor(cx, p, cx.tol(4.0)).map(remove_anchor).into_iter().collect()
|
||||
hit_anchor(cx, p, cx.pick_tol()).map(remove_anchor).into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A direction handle of a selected path under `p`, among those shown (a path with anchors
|
||||
/// direct-selected shows theirs only): (id, subpath, anchor, is_out).
|
||||
pub(crate) fn hit_handle(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, bool)> {
|
||||
for id in &cx.selection.objects {
|
||||
let Some(pd) = cx.doc.node(*id).and_then(|n| n.path_data()) else { continue };
|
||||
let shown = cx.selection.partial(*id);
|
||||
for (si, ai, a) in pd.anchors().filter(|(si, ai, _)| shown.is_none_or(|set| set.contains(&(*si, *ai)))) {
|
||||
if a.has_out() && a.h_out.distance(p) <= tol {
|
||||
return Some((*id, si, ai, true));
|
||||
}
|
||||
if a.has_in() && a.h_in.distance(p) <= tol {
|
||||
return Some((*id, si, ai, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl Tool for AnchorTool {
|
||||
fn id(&self) -> &'static str {
|
||||
self.id
|
||||
@@ -76,7 +61,7 @@ impl Tool for AnchorTool {
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
let p = ev.pos;
|
||||
let tol = cx.tol(4.0);
|
||||
let tol = cx.pick_tol();
|
||||
match (self.id, ev.kind) {
|
||||
("addAnchor", PointerKind::Down) => {
|
||||
if ev.mods.alt {
|
||||
@@ -104,6 +89,7 @@ impl Tool for AnchorTool {
|
||||
("anchorPoint", PointerKind::Down) => {
|
||||
if let Some((id, si, ai, out)) = hit_handle(cx, p, tol) {
|
||||
self.state = State::Handle { id, si, ai, out, began: false };
|
||||
self.snap = HandleSnap::default();
|
||||
} else if let Some((id, si, ai)) = hit_anchor(cx, p, tol) {
|
||||
self.state = State::Convert { id, si, ai, start: p, began: false };
|
||||
} else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) {
|
||||
@@ -134,7 +120,7 @@ impl Tool for AnchorTool {
|
||||
json!({"id": id.0, "subpath": si, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}),
|
||||
),
|
||||
State::Handle { id, si, ai, out, .. } => {
|
||||
let (q, guides) = crate::guides::snap_handle(cx, (id, si, ai), p, ev.mods.shift);
|
||||
let (q, guides) = self.snap.snap(cx, (id, si, ai), p, ev.mods.shift);
|
||||
self.guides = guides;
|
||||
Action::Preview(
|
||||
"path.setHandle".into(),
|
||||
@@ -192,7 +178,7 @@ impl Tool for AnchorTool {
|
||||
"deleteAnchor" if !m.alt => Cursor::PenDelete,
|
||||
"deleteAnchor" => Cursor::PenAdd,
|
||||
"scissors" => {
|
||||
if hit_segment(cx, p, cx.tol(4.0)).is_some() {
|
||||
if hit_segment(cx, p, cx.pick_tol()).is_some() {
|
||||
Cursor::Crosshair
|
||||
} else {
|
||||
Cursor::NotAllowed
|
||||
@@ -257,4 +243,38 @@ mod tests {
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 230.0));
|
||||
assert!(matches!(&a[1], Action::Preview(c, v) if c == "path.reshapeSegment" && v["dy"] == 30.0));
|
||||
}
|
||||
|
||||
/// #494: the Anchor Point tool picks within Selection & Anchor Display → Tolerance, and drags
|
||||
/// only the handles shown.
|
||||
#[test]
|
||||
fn anchor_point_picks_within_the_tolerance_and_drags_shown_handles() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(300.0, 300.0)], false);
|
||||
sp.anchors[1] = vectorcraft_geom::Anchor::smooth(Point::new(200.0, 300.0), Point::new(240.0, 300.0));
|
||||
let path = vectorcraft_geom::PathData::single(sp);
|
||||
d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.set([id]);
|
||||
let p = paint();
|
||||
let press = |c: &ToolContext, x: f64, y: f64| {
|
||||
let mut t = AnchorTool::new("anchorPoint");
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Drag, x + 10.0, y + 30.0))
|
||||
};
|
||||
let dragged = |a: Vec<Action>| match a.as_slice() {
|
||||
[Action::Begin(_), Action::Preview(c, _)] => c.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
// The segment 6 px off: picked with an 8 px tolerance, not with the default 3 px.
|
||||
assert_eq!(dragged(press(&cx(&d, &s, &p), 150.0, 306.0)), "");
|
||||
let wide = ToolContext { selection_tolerance: 8.0, ..cx(&d, &s, &p) };
|
||||
assert_eq!(dragged(press(&wide, 150.0, 306.0)), "path.reshapeSegment");
|
||||
// The middle anchor's handle drags; with Show handles when multiple anchors are selected
|
||||
// off it's hidden (three anchors selected) and the press finds the segment under it.
|
||||
assert_eq!(dragged(press(&cx(&d, &s, &p), 240.0, 301.0)), "path.setHandle");
|
||||
let single = ToolContext { handles_multiple: false, ..cx(&d, &s, &p) };
|
||||
assert_eq!(dragged(press(&single, 240.0, 301.0)), "path.reshapeSegment");
|
||||
}
|
||||
}
|
||||
+28
-18
@@ -553,25 +553,35 @@ impl PointSnap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a dragged direction handle of anchor `ai` of subpath `si` of path `id` goes for the
|
||||
/// pointer at `p`: with Shift at a multiple of 45° (from the Constrain Angle) round its anchor,
|
||||
/// else snapped as a drawn point is (smart guides, the grid, pixels).
|
||||
pub fn snap_handle(cx: &ToolContext, (id, si, ai): (NodeId, usize, usize), p: Point, shift: bool) -> (Point, Vec<Overlay>) {
|
||||
let path = cx.doc.node(id).and_then(|n| n.path_data());
|
||||
if shift && let Some(a) = path.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) {
|
||||
return (a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle), vec![]);
|
||||
}
|
||||
snap_with(cx, p, || {
|
||||
// The path's bounds move with the handle, so they would chase it: its anchors (which stay
|
||||
// put) are the targets instead, the handle lining up with them too.
|
||||
let mut t = Targets::collect(cx.doc, &[id], None);
|
||||
for (_, _, a) in path.into_iter().flat_map(|pd| pd.anchors()).take(20_000) {
|
||||
t.points.push((a.p, Kind::Anchor));
|
||||
t.xs.push((a.p.x, a.p, Kind::Anchor));
|
||||
t.ys.push((a.p.y, a.p, Kind::Anchor));
|
||||
/// Snapping for a dragged direction handle: Shift keeps it at 45° steps round its anchor, else it
|
||||
/// snaps as a drawn point does. The targets are gathered on the first move that needs them and
|
||||
/// kept for the rest of the drag (gathering them takes as long as the document is big).
|
||||
#[derive(Default)]
|
||||
pub struct HandleSnap(Option<PointSnap>);
|
||||
|
||||
impl HandleSnap {
|
||||
/// Where the handle of anchor `ai` of subpath `si` of path `id` goes with the pointer at `p`,
|
||||
/// and the guides showing why.
|
||||
pub fn snap(&mut self, cx: &ToolContext, (id, si, ai): (NodeId, usize, usize), p: Point, shift: bool) -> (Point, Vec<Overlay>) {
|
||||
let path = cx.doc.node(id).and_then(|n| n.path_data());
|
||||
if shift && let Some(a) = path.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) {
|
||||
return (a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle), vec![]);
|
||||
}
|
||||
t
|
||||
})
|
||||
let snap = self.0.get_or_insert_with(|| {
|
||||
PointSnap::new(cx, || {
|
||||
// The path's bounds move with the handle, so they would chase it: its anchors
|
||||
// (which stay put) are the targets instead, the handle lining up with them too.
|
||||
let mut t = Targets::collect(cx.doc, &[id], None);
|
||||
for (_, _, a) in path.into_iter().flat_map(|pd| pd.anchors()).take(20_000) {
|
||||
t.points.push((a.p, Kind::Anchor));
|
||||
t.xs.push((a.p.x, a.p, Kind::Anchor));
|
||||
t.ys.push((a.p.y, a.p, Kind::Anchor));
|
||||
}
|
||||
t
|
||||
})
|
||||
});
|
||||
snap.snap(cx, p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Snap a picked point (a transform tool's reference point) to the nearest anchor or centre of the
|
||||
|
||||
+146
-33
@@ -3,11 +3,14 @@
|
||||
//! Click adds a corner anchor; click-drag adds a smooth anchor with symmetric handles (Alt breaks
|
||||
//! them: the incoming handle stays where it was when Alt went down and only the outgoing one
|
||||
//! follows the pointer; Space held moves the anchor, handles and all); Shift constrains to 45°.
|
||||
//! Clicking the first anchor closes the path. Clicking the last one retracts its outgoing handle, so
|
||||
//! the next segment leaves it as a corner; dragging from it pulls a new one out on its own.
|
||||
//! Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as
|
||||
//! the Anchor Point tool: dragging a handle moves it alone, clicking a smooth anchor makes it a
|
||||
//! corner and dragging an anchor pulls out new symmetric handles.
|
||||
//! A press on the first anchor closes the path, the drag shaping the closing curve. Clicking the
|
||||
//! last one retracts its outgoing handle, so the next segment leaves it as a corner; dragging from
|
||||
//! it pulls a new one out on its own.
|
||||
//! Alt held over a handle end, an anchor or a segment of a selected path (the one being drawn too)
|
||||
//! works as the Anchor Point tool: dragging a handle moves it alone, clicking a smooth anchor makes
|
||||
//! it a corner, dragging an anchor pulls out new symmetric handles and dragging a segment reshapes
|
||||
//! it. Cmd held lends the selection tool used last for a drag (the engine's
|
||||
//! `Session::pointer`); the path being drawn goes on afterwards while it stays selected.
|
||||
//! Enter/Esc (or switching tools) ends the path. Clicking the end of a selected open path continues
|
||||
//! it. The rubber-band preview shows the next segment (Enable Rubber Band for Pen Tool). Auto Add/Delete: between paths, a click on a
|
||||
//! segment of a selected path adds an anchor there and a click on one of its anchors deletes it
|
||||
@@ -18,14 +21,18 @@ use serde_json::json;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{BezPath, Point};
|
||||
|
||||
use crate::draw2::{AnchorTool, hit_handle};
|
||||
use crate::direct::hit_handle;
|
||||
use crate::draw2::AnchorTool;
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PenTool {
|
||||
/// The path being drawn (set once the first anchor exists and the engine selected it).
|
||||
/// A path is being drawn...
|
||||
drawing: bool,
|
||||
drag: Option<(Point, bool)>,
|
||||
/// ...this one, once the engine made it: another path selected meanwhile isn't drawn on.
|
||||
path: Option<NodeId>,
|
||||
/// The anchor a press placed, while the drag shapes its handles.
|
||||
drag: Option<Place>,
|
||||
hover: Option<Point>,
|
||||
/// The incoming handle of the anchor being dragged out, as last previewed.
|
||||
in_h: Point,
|
||||
@@ -38,6 +45,17 @@ pub struct PenTool {
|
||||
convert: Option<AnchorTool>,
|
||||
}
|
||||
|
||||
/// An anchor being placed, as the press decided: where it is, the path it goes on (none: the
|
||||
/// first anchor of a new path) and whether it closes that path (the press was on its first
|
||||
/// anchor). The drag only shapes its handles, whatever the path looks like meanwhile: a closing
|
||||
/// preview leaves the path closed, so no longer one the pen draws on.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Place {
|
||||
at: Point,
|
||||
path: Option<NodeId>,
|
||||
closing: bool,
|
||||
}
|
||||
|
||||
/// The open path the pen is extending: the single selected open path.
|
||||
fn active_path(cx: &ToolContext) -> Option<(NodeId, Point, Point, Point)> {
|
||||
if cx.selection.objects.len() != 1 {
|
||||
@@ -63,10 +81,14 @@ fn last_anchor(cx: &ToolContext, id: NodeId) -> Option<(usize, usize)> {
|
||||
Some((si, ai))
|
||||
}
|
||||
|
||||
/// Alt held over a handle end or an anchor of a selected path: the Anchor Point tool's gesture.
|
||||
/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's
|
||||
/// gesture, within its tolerance.
|
||||
fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
|
||||
let tol = cx.tol(4.0);
|
||||
m.alt && (hit_handle(cx, p, tol).is_some() || crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).is_some())
|
||||
let tol = cx.pick_tol();
|
||||
m.alt
|
||||
&& (hit_handle(cx, p, tol).is_some()
|
||||
|| crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).is_some()
|
||||
|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).is_some())
|
||||
}
|
||||
|
||||
/// The selected paths the pen edits (not guides, nor locked or hidden ones).
|
||||
@@ -97,9 +119,13 @@ impl Tool for PenTool {
|
||||
let exclude: Vec<vectorcraft_doc::NodeId> = if self.drawing { cx.selection.objects.clone() } else { vec![] };
|
||||
let (mut p, _) = if matches!(ev.kind, PointerKind::Down) { crate::guides::snap_draw(cx, ev.pos, &exclude) } else { (ev.pos, vec![]) };
|
||||
let tol = cx.tol(5.0);
|
||||
let active = if self.drawing { active_path(cx) } else { None };
|
||||
// The path a press began is the selected one by the next event.
|
||||
if self.drawing && self.path.is_none() {
|
||||
self.path = active_path(cx).map(|a| a.0);
|
||||
}
|
||||
let active = self.active(cx);
|
||||
if self.drawing && active.is_none() && ev.kind == PointerKind::Down {
|
||||
self.drawing = false;
|
||||
self.stop();
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
@@ -115,7 +141,7 @@ impl Tool for PenTool {
|
||||
let end = last_anchor(cx, id);
|
||||
// A one-anchor path doesn't close on itself: its anchor is the last one too.
|
||||
if p.distance(first) <= tol && end.is_some_and(|(_, ai)| ai > 0) {
|
||||
self.drag = Some((first, true));
|
||||
self.drag = Some(Place { at: first, path: Some(id), closing: true });
|
||||
return vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0}))];
|
||||
}
|
||||
if p.distance(last) <= tol
|
||||
@@ -127,7 +153,7 @@ impl Tool for PenTool {
|
||||
if let Some(acts) = self.alt_convert(cx, ev) {
|
||||
return acts;
|
||||
}
|
||||
self.drag = Some((p, false));
|
||||
self.drag = Some(Place { at: p, path: Some(id), closing: false });
|
||||
self.in_h = p;
|
||||
return vec![Action::Begin("Pen".into()), Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": p.x, "y": p.y}))];
|
||||
}
|
||||
@@ -142,6 +168,7 @@ impl Tool for PenTool {
|
||||
&& (p.distance(last) <= tol || p.distance(first) <= tol)
|
||||
{
|
||||
self.drawing = true;
|
||||
self.path = active_path(cx).map(|a| a.0);
|
||||
if p.distance(first) <= tol && p.distance(last) > tol {
|
||||
return vec![Action::Exec("path.reverse".into(), json!({}))];
|
||||
}
|
||||
@@ -150,8 +177,8 @@ impl Tool for PenTool {
|
||||
if let Some(act) = auto_add_delete(cx, ev.pos, ev.mods, tol) {
|
||||
return vec![act];
|
||||
}
|
||||
self.drawing = true;
|
||||
self.drag = Some((p, false));
|
||||
(self.drawing, self.path) = (true, None);
|
||||
self.drag = Some(Place { at: p, path: None, closing: false });
|
||||
vec![Action::Begin("Pen".into()), Action::Preview("path.create".into(), json!({"anchors": [{"x": p.x, "y": p.y}]}))]
|
||||
}
|
||||
PointerKind::Drag => {
|
||||
@@ -165,13 +192,13 @@ impl Tool for PenTool {
|
||||
}
|
||||
return vec![set_out_handle(id, si, ai, h)];
|
||||
}
|
||||
let Some((mut a, closing)) = self.drag else { return vec![] };
|
||||
let Some(Place { at: mut a, path, closing }) = self.drag else { return vec![] };
|
||||
// Space held moves the anchor being placed, handles and all.
|
||||
if ev.mods.space && !closing {
|
||||
let d = ev.pos - self.last;
|
||||
a += d;
|
||||
self.in_h += d;
|
||||
self.drag = Some((a, closing));
|
||||
self.drag = Some(Place { at: a, path, closing });
|
||||
}
|
||||
self.last = ev.pos;
|
||||
let mut out_h = ev.pos;
|
||||
@@ -179,7 +206,7 @@ impl Tool for PenTool {
|
||||
out_h = a + vectorcraft_geom::constrain_angle(ev.pos - a, 45.0);
|
||||
}
|
||||
let alt = ev.mods.alt;
|
||||
let Some((id, ..)) = active_path(cx).or(active) else {
|
||||
let Some(id) = path else {
|
||||
// First anchor of a new path: re-issue create with handles.
|
||||
let in_h = a - (out_h - a);
|
||||
return vec![Action::Preview(
|
||||
@@ -209,9 +236,9 @@ impl Tool for PenTool {
|
||||
if self.handle.take().is_some() {
|
||||
return vec![Action::Commit];
|
||||
}
|
||||
let Some((_, closing)) = self.drag.take() else { return vec![] };
|
||||
if closing {
|
||||
self.drawing = false;
|
||||
let Some(place) = self.drag.take() else { return vec![] };
|
||||
if place.closing {
|
||||
self.stop();
|
||||
}
|
||||
vec![Action::Commit]
|
||||
}
|
||||
@@ -221,7 +248,7 @@ impl Tool for PenTool {
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec<Action> {
|
||||
match key {
|
||||
ToolKey::Enter | ToolKey::Escape => {
|
||||
self.drawing = false;
|
||||
self.stop();
|
||||
self.drag = None;
|
||||
self.handle = None;
|
||||
// An Alt gesture under way ends as it stands.
|
||||
@@ -231,17 +258,17 @@ impl Tool for PenTool {
|
||||
}
|
||||
}
|
||||
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
self.drawing = false;
|
||||
self.stop();
|
||||
self.convert.take().map(|mut t| t.deactivate(cx)).unwrap_or_default()
|
||||
}
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
if let Some(t) = &self.convert {
|
||||
return t.overlays(cx);
|
||||
}
|
||||
if !cx.pen_rubber_band || !self.drawing || self.drag.is_some() || self.handle.is_some() {
|
||||
if !cx.pen_rubber_band || self.drag.is_some() || self.handle.is_some() {
|
||||
return vec![];
|
||||
}
|
||||
let (Some((id, _, last, out)), Some(h)) = (active_path(cx), self.hover) else { return vec![] };
|
||||
let (Some((id, _, last, out)), Some(h)) = (self.active(cx), self.hover) else { return vec![] };
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(last);
|
||||
if out.distance(last) > 1e-9 {
|
||||
@@ -254,10 +281,7 @@ impl Tool for PenTool {
|
||||
}
|
||||
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
|
||||
let tol = cx.tol(5.0);
|
||||
let active = active_path(cx);
|
||||
if self.drawing
|
||||
&& let Some((id, first, last, _)) = active
|
||||
{
|
||||
if let Some((id, first, last, _)) = self.active(cx) {
|
||||
let one = last_anchor(cx, id).is_some_and(|(_, ai)| ai == 0);
|
||||
if p.distance(first) <= tol && !one {
|
||||
return Cursor::PenClose;
|
||||
@@ -275,7 +299,7 @@ impl Tool for PenTool {
|
||||
Some([_]) => return Cursor::PenAdd,
|
||||
_ => {}
|
||||
}
|
||||
if active.is_some_and(|(_, first, last, _)| p.distance(last) <= tol || p.distance(first) <= tol) {
|
||||
if active_path(cx).is_some_and(|(_, first, last, _)| p.distance(last) <= tol || p.distance(first) <= tol) {
|
||||
return Cursor::PenContinue;
|
||||
}
|
||||
match auto_add_delete(cx, p, m, tol) {
|
||||
@@ -289,13 +313,27 @@ impl Tool for PenTool {
|
||||
}
|
||||
|
||||
impl PenTool {
|
||||
/// Hand an Alt press on a selected path's handle or anchor to the Anchor Point tool.
|
||||
/// The open path being drawn: the one the pen made or went on with, while it is the single
|
||||
/// selected open path.
|
||||
fn active(&self, cx: &ToolContext) -> Option<(NodeId, Point, Point, Point)> {
|
||||
active_path(cx).filter(|(id, ..)| self.drawing && self.path.is_none_or(|p| p == *id))
|
||||
}
|
||||
|
||||
/// The path is finished.
|
||||
fn stop(&mut self) {
|
||||
(self.drawing, self.path) = (false, None);
|
||||
}
|
||||
|
||||
/// Hand an Alt press on a selected path's handle, anchor or segment to the Anchor Point tool.
|
||||
fn alt_convert(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
|
||||
if !alt_converts(cx, ev.pos, ev.mods) {
|
||||
return None;
|
||||
}
|
||||
let mut t = AnchorTool::new("anchorPoint");
|
||||
let acts = t.pointer(cx, ev);
|
||||
if !t.busy() {
|
||||
return None;
|
||||
}
|
||||
self.convert = Some(t);
|
||||
Some(acts)
|
||||
}
|
||||
@@ -467,6 +505,32 @@ mod tests {
|
||||
assert_eq!(t.cursor(&cx, Point::new(10.0, 300.0), Mods::default()), Cursor::PenClose);
|
||||
}
|
||||
|
||||
/// #501: a press on the first anchor closes the path, however far the drag then goes: the
|
||||
/// closing preview leaves the path closed (so not one the pen extends), and each move still
|
||||
/// previews the close with symmetric handles (Alt breaks them), released as a close.
|
||||
#[test]
|
||||
fn a_drag_from_the_first_anchor_always_closes() {
|
||||
let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)];
|
||||
let (mut d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false));
|
||||
let p = paint();
|
||||
let mut t = PenTool { drawing: true, ..PenTool::default() };
|
||||
let a = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 101.0, 301.0));
|
||||
assert_eq!(a, vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0}))]);
|
||||
// What the tool sees once the preview applied: the path closed.
|
||||
d.node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].closed = true;
|
||||
let c = cx(&d, &s, &p);
|
||||
let close = |x: f64, y: f64, alt: bool| {
|
||||
vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [200.0 - x, 600.0 - y], "independent": alt}))]
|
||||
};
|
||||
for (x, y) in [(105.0, 290.0), (130.0, 260.0), (160.0, 240.0)] {
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x, y)), close(x, y, false), "at ({x}, {y})");
|
||||
}
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 250.0).with_mods(alt)), close(170.0, 250.0, true));
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 250.0)), vec![Action::Commit]);
|
||||
assert!(!t.busy() && t.active(&c).is_none(), "the path is done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_anchor_path_does_not_close_on_itself() {
|
||||
let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0)], false));
|
||||
@@ -587,4 +651,53 @@ mod tests {
|
||||
let cx1 = cx(&d, &s, &p);
|
||||
assert_eq!(t.cursor(&cx1, Point::new(250.0, 101.0), alt), Cursor::Pen);
|
||||
}
|
||||
|
||||
/// #494: Alt held over a segment of a selected path reshapes it as the Anchor Point tool does,
|
||||
/// while drawing too; Alt away from paths still places an anchor.
|
||||
#[test]
|
||||
fn alt_over_a_segment_reshapes_it() {
|
||||
let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false));
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let mut t = PenTool { drawing: true, ..PenTool::default() };
|
||||
assert_eq!(t.cursor(&cx, Point::new(150.0, 302.0), alt), Cursor::PenConvert);
|
||||
assert_eq!(t.cursor(&cx, Point::new(150.0, 302.0), Mods::default()), Cursor::Pen);
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 302.0).with_mods(alt)), vec![]);
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 262.0).with_mods(alt));
|
||||
assert_eq!(a[0], Action::Begin("Reshape".into()));
|
||||
assert!(
|
||||
matches!(&a[1], Action::Preview(c, v) if c == "path.reshapeSegment" && v["id"] == id.0 && v["segment"] == 0 && v["dy"] == -40.0),
|
||||
"{a:?}"
|
||||
);
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 262.0)), vec![Action::Commit]);
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 400.0).with_mods(alt));
|
||||
assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.appendAnchor"), "{a:?}");
|
||||
}
|
||||
|
||||
/// #494: the Pen goes on drawing the path it drew while that path stays selected (after a Cmd
|
||||
/// drag with Direct Selection), but never another open path selected meanwhile.
|
||||
#[test]
|
||||
fn the_pen_draws_on_the_path_it_began_only() {
|
||||
let (mut d, a, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0), Point::new(60.0, 300.0)], false));
|
||||
let l = d.layers[0].id;
|
||||
let b = d.alloc_id();
|
||||
let line = vectorcraft_geom::shapes::line(Point::new(10.0, 400.0), Point::new(60.0, 400.0));
|
||||
d.insert(Some(l), 2, vectorcraft_doc::Node::path(b, line, vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let p = paint();
|
||||
let mut t = PenTool { drawing: true, ..PenTool::default() };
|
||||
let cx_a = cx(&d, &s, &p);
|
||||
let appended = |acts: &[Action]| match acts {
|
||||
[Action::Begin(_), Action::Preview(c, v)] if c == "path.appendAnchor" => v["id"].as_u64(),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(appended(&click(&mut t, &cx_a, 100.0, 320.0, Mods::default())), Some(a.0));
|
||||
// Path B selected instead: the next click starts a new path.
|
||||
let mut sb = Selection::default();
|
||||
sb.set([b]);
|
||||
let cx_b = cx(&d, &sb, &p);
|
||||
assert_eq!(t.cursor(&cx_b, Point::new(150.0, 350.0), Mods::default()), Cursor::Pen);
|
||||
let acts = click(&mut t, &cx_b, 150.0, 350.0, Mods::default());
|
||||
assert!(matches!(&acts[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"), "{acts:?}");
|
||||
}
|
||||
}
|
||||
@@ -76,31 +76,19 @@ enum Drag {
|
||||
start_angle: f64,
|
||||
start_rot: f64,
|
||||
},
|
||||
/// Cmd held: temporary selection tool; restore this tool on release.
|
||||
TempSelect,
|
||||
/// A Selection tool move dragged off the canvas: the panels get the art
|
||||
/// ([`widgets::PanelDrag::Art`]); `temp` restores the tool Cmd switched from on release.
|
||||
Art {
|
||||
temp: bool,
|
||||
},
|
||||
/// ([`widgets::PanelDrag::Art`]).
|
||||
Art,
|
||||
}
|
||||
|
||||
fn drag_id() -> egui::Id {
|
||||
egui::Id::new("canvas-drag")
|
||||
}
|
||||
fn temp_tool_id() -> egui::Id {
|
||||
egui::Id::new("canvas-temp-tool")
|
||||
}
|
||||
/// Where the pointer was last seen during a press on the canvas.
|
||||
fn drag_pos_id() -> egui::Id {
|
||||
egui::Id::new("canvas-drag-pos")
|
||||
}
|
||||
|
||||
/// Selection, Direct Selection and Group Selection: the tools Cmd switches to for a drag.
|
||||
pub(crate) fn is_selection_tool(id: &str) -> bool {
|
||||
matches!(id, "selection" | "directSelection" | "groupSelection")
|
||||
}
|
||||
|
||||
/// The pen pressure (0..1) of the press in progress: the force of this frame's pen or touch
|
||||
/// input, else the last one seen since the press (`pressed`: a new press, whose mouse has none
|
||||
/// until a pen reports it). A mouse presses fully (1).
|
||||
@@ -531,19 +519,10 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
let c = rect.center();
|
||||
Drag::RotateView { start_angle: (p.y - c.y).atan2(p.x - c.x) as f64, start_rot: v.rotation }
|
||||
} else {
|
||||
let mut kind = Drag::Tool;
|
||||
// Cmd with another tool: drag with the selection tool used last.
|
||||
if m.command && !is_selection_tool(tool) {
|
||||
ui.data_mut(|d| d.insert_temp(temp_tool_id(), tool.to_string()));
|
||||
let last = app.ui.last_selection_tool.clone();
|
||||
app.select_tool(if is_selection_tool(&last) { &last } else { "selection" });
|
||||
kind = Drag::TempSelect;
|
||||
}
|
||||
// Cmd only brought the selection tool: its click is a plain one, not Select Behind.
|
||||
let mods = Mods { cmd: m.command && kind != Drag::TempSelect, ..mods(m, space) };
|
||||
let ev = PointerEvent { kind: PointerKind::Down, pos: xf.to_doc(p), mods, pressure: pen_pressure(ui, true) };
|
||||
// Cmd with another tool drags with the selection tool used last (the session lends it).
|
||||
let ev = PointerEvent { kind: PointerKind::Down, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, true) };
|
||||
dispatch(app, &ev, view);
|
||||
kind
|
||||
Drag::Tool
|
||||
};
|
||||
ui.data_mut(|dd| {
|
||||
dd.insert_temp(drag_id(), d);
|
||||
@@ -580,11 +559,11 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
vm.rotation = vectorcraft_geom::normalize_deg(deg);
|
||||
}
|
||||
}
|
||||
Drag::ZoomBox { .. } | Drag::Art { .. } => {}
|
||||
Drag::Tool | Drag::TempSelect if drag_art_out(app, ui, resp, p, view) => {
|
||||
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art { temp: d == Drag::TempSelect }));
|
||||
Drag::ZoomBox { .. } | Drag::Art => {}
|
||||
Drag::Tool if drag_art_out(app, ui, resp, p, view) => {
|
||||
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art));
|
||||
}
|
||||
Drag::Tool | Drag::TempSelect => {
|
||||
Drag::Tool => {
|
||||
if pointer.delta() != egui::Vec2::ZERO {
|
||||
let ev = PointerEvent { kind: PointerKind::Drag, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, false) };
|
||||
dispatch(app, &ev, view);
|
||||
@@ -620,17 +599,11 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
}
|
||||
}
|
||||
}
|
||||
Drag::Tool | Drag::TempSelect | Drag::Art { .. } => {
|
||||
if !matches!(d, Drag::Art { .. }) {
|
||||
let ev = PointerEvent { kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, false) };
|
||||
dispatch(app, &ev, view);
|
||||
}
|
||||
if matches!(d, Drag::TempSelect | Drag::Art { temp: true })
|
||||
&& let Some(prev) = ui.data(|dd| dd.get_temp::<String>(temp_tool_id()))
|
||||
{
|
||||
app.restore_tool(&prev);
|
||||
}
|
||||
Drag::Tool => {
|
||||
let ev = PointerEvent { kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, false) };
|
||||
dispatch(app, &ev, view);
|
||||
}
|
||||
Drag::Art => {}
|
||||
Drag::Pan { .. } | Drag::RotateView { .. } => {}
|
||||
}
|
||||
}
|
||||
@@ -1371,7 +1344,7 @@ fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
|
||||
let app = &*app;
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let tool = app.session.tool_id();
|
||||
let direct = matches!(tool, "directSelection" | "pen" | "addAnchor" | "deleteAnchor" | "anchorPoint" | "curvature");
|
||||
let direct = vectorcraft_tools::catalog::edits_anchors(tool);
|
||||
// Selection & Anchor Display › Size (1–7, 3 the default): anchors, handles and the bounding
|
||||
// box's handles a point bigger or smaller per step.
|
||||
let look = HandleLook::of(&app.session.prefs);
|
||||
|
||||
@@ -108,10 +108,32 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
/// An anchor button: icon, tooltip, command and the convert command's `to`.
|
||||
type AnchorButton<'a> = (&'a str, &'a str, &'a str, Option<&'a str>);
|
||||
|
||||
/// What the Control bar and the Properties panel offer for direct-selected anchors: "Convert:"
|
||||
/// corner or smooth, then "Anchors:" remove, connect (Join) and cut. Each group is a row of its
|
||||
/// own: inline in the Control bar, one under the other in a panel.
|
||||
pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
/// The anchor controls the Control bar and the Properties panel show.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AnchorControls {
|
||||
None,
|
||||
/// Paths selected as a whole with a tool that edits anchors (Direct Selection, the Pen…),
|
||||
/// which shows all their anchors selected: "Convert:" only, as removing or cutting at every
|
||||
/// anchor isn't what they're for.
|
||||
Convert,
|
||||
/// Anchors direct-selected: "Convert:" and "Anchors:".
|
||||
All,
|
||||
}
|
||||
|
||||
/// Which anchor controls show for the selection and the active tool.
|
||||
pub fn anchor_controls(app: &VectorcraftApp) -> AnchorControls {
|
||||
let Some(st) = app.session.active() else { return AnchorControls::None };
|
||||
if !st.selection.anchors.is_empty() {
|
||||
return AnchorControls::All;
|
||||
}
|
||||
let paths = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
if paths && vectorcraft_tools::catalog::edits_anchors(app.session.tool_id()) { AnchorControls::Convert } else { AnchorControls::None }
|
||||
}
|
||||
|
||||
/// What the Control bar and the Properties panel offer for selected anchors ([`anchor_controls`]):
|
||||
/// "Convert:" corner or smooth, then "Anchors:" remove, connect (Join) and cut. Each group is a
|
||||
/// row of its own: inline in the Control bar, one under the other in a panel.
|
||||
pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorControls) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let mut run = None;
|
||||
let groups: [(&str, &[AnchorButton]); 2] = [
|
||||
@@ -131,7 +153,12 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
],
|
||||
),
|
||||
];
|
||||
for (label, buttons) in groups {
|
||||
let shown = match controls {
|
||||
AnchorControls::None => 0,
|
||||
AnchorControls::Convert => 1,
|
||||
AnchorControls::All => groups.len(),
|
||||
};
|
||||
for (label, buttons) in groups.into_iter().take(shown) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(label).size(12.0).color(t.text));
|
||||
for &(icon, tip, id, to) in buttons {
|
||||
@@ -166,9 +193,9 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let sel = st.selection.objects.clone();
|
||||
let units = app.session.general_unit();
|
||||
let first = sel.first().and_then(|id| st.doc.node(*id)).cloned();
|
||||
let anchor_mode = !st.selection.anchors.is_empty();
|
||||
let anchors = anchor_controls(app);
|
||||
let label = match &first {
|
||||
Some(_) if sel.len() == 1 && anchor_mode => tl!("Anchor Point"),
|
||||
Some(_) if sel.len() == 1 && anchors != AnchorControls::None => tl!("Anchor Point"),
|
||||
Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if sel.len() == 1 => {
|
||||
if im.link.is_some() {
|
||||
tl!("Linked File")
|
||||
@@ -180,8 +207,8 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
_ => tl!(crate::panels::appearance::object_label(app)),
|
||||
};
|
||||
ui.label(egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text));
|
||||
if anchor_mode {
|
||||
anchor_buttons(app, ui);
|
||||
if anchors != AnchorControls::None {
|
||||
anchor_buttons(app, ui, anchors);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
// An image or an Image Trace object shows its own controls in place of Fill and Stroke.
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Checks the system clipboard for Paste off the UI thread. `has()` can block for seconds when the
|
||||
//! clipboard owner never answers (an unresponsive X11 client), so it must not run on the thread that
|
||||
//! draws the window: a worker owns a second clipboard handle, sends its verdict when it changes, and
|
||||
//! the UI only reads the latest one. Without a worker the check stays in line, as before (the web,
|
||||
//! and hosts that don't install a factory).
|
||||
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, TryRecvError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
|
||||
|
||||
use crate::sysclip::ClipboardProbeFactory;
|
||||
|
||||
/// How often the worker looks at the clipboard while the UI wants to know.
|
||||
const PROBE_INTERVAL: Duration = Duration::from_millis(250);
|
||||
|
||||
/// How long dropping the probe waits for the worker to let go of its clipboard handle.
|
||||
const STOP_WAIT: Duration = Duration::from_millis(250);
|
||||
|
||||
/// The background clipboard check ([`crate::VectorcraftApp`]'s `clipboard_probe`).
|
||||
pub(crate) struct Probe {
|
||||
/// Tells the worker whether Paste depends on the system clipboard; dropped to stop it.
|
||||
wants: Option<Sender<bool>>,
|
||||
wanted: bool,
|
||||
verdicts: Receiver<bool>,
|
||||
/// The worker's last verdict.
|
||||
last: bool,
|
||||
}
|
||||
|
||||
impl Probe {
|
||||
/// Start the worker. `None` on wasm, or when the thread can't be spawned: the caller then falls
|
||||
/// back to the in-line check.
|
||||
pub(crate) fn start(make: ClipboardProbeFactory, ctx: egui::Context) -> Option<Self> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let (wants, wanted_rx) = std::sync::mpsc::channel();
|
||||
let (tx, verdicts) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("vectorcraft-clip".into())
|
||||
.spawn(move || {
|
||||
let mut clipboard = make();
|
||||
let (mut wanted, mut sent) = (false, None);
|
||||
loop {
|
||||
if wanted {
|
||||
// This thread may wait here for a slow owner; the UI's never does.
|
||||
let verdict = clipboard.has(&PASTE_ORDER);
|
||||
if sent != Some(verdict) {
|
||||
if tx.send(verdict).is_err() {
|
||||
break;
|
||||
}
|
||||
sent = Some(verdict);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
// Sleep until the next look (no looks while unwanted) or the UI's next word.
|
||||
let next =
|
||||
if wanted { wanted_rx.recv_timeout(PROBE_INTERVAL) } else { wanted_rx.recv().map_err(|_| RecvTimeoutError::Disconnected) };
|
||||
match next {
|
||||
Ok(w) => wanted = w,
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
// The handle goes before the app stops waiting (`Drop`): on X11 the last one alive
|
||||
// hands what the app copied to the clipboard manager, which must finish before exit.
|
||||
drop(clipboard);
|
||||
drop(tx);
|
||||
})
|
||||
.ok()?;
|
||||
Some(Self { wants: Some(wants), wanted: false, verdicts, last: false })
|
||||
}
|
||||
|
||||
/// Paste can take from the system clipboard: `wanted` (nothing copied in the app, a document
|
||||
/// open) and the worker's latest verdict says so. Never blocks. `None` once the worker is gone.
|
||||
pub(crate) fn pasteable(&mut self, wanted: bool) -> Option<bool> {
|
||||
if wanted != self.wanted {
|
||||
self.wants.as_ref()?.send(wanted).ok()?;
|
||||
self.wanted = wanted;
|
||||
}
|
||||
loop {
|
||||
match self.verdicts.try_recv() {
|
||||
Ok(verdict) => self.last = verdict,
|
||||
Err(TryRecvError::Empty) => return Some(wanted && self.last),
|
||||
Err(TryRecvError::Disconnected) => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Probe {
|
||||
/// Wake the worker to stop and wait (a moment at most: it may be stuck on an owner that never
|
||||
/// answers) until it has let go of its clipboard handle.
|
||||
fn drop(&mut self) {
|
||||
self.wants = None;
|
||||
let end = Instant::now() + STOP_WAIT;
|
||||
while self.verdicts.recv_timeout(end.saturating_duration_since(Instant::now())).is_ok() {}
|
||||
}
|
||||
}
|
||||
+27
-21
@@ -17,6 +17,7 @@ pub mod background;
|
||||
mod brand;
|
||||
pub mod canvas;
|
||||
pub mod chrome;
|
||||
mod clipboard_probe;
|
||||
pub mod community;
|
||||
pub mod control;
|
||||
pub mod credits;
|
||||
@@ -129,6 +130,8 @@ mod tests_sysclip;
|
||||
#[cfg(test)]
|
||||
mod tests_sysclip_emf;
|
||||
#[cfg(test)]
|
||||
mod tests_sysclip_probe;
|
||||
#[cfg(test)]
|
||||
mod tests_transparencygrid;
|
||||
#[cfg(test)]
|
||||
mod tests_widthtool;
|
||||
@@ -142,7 +145,7 @@ use vectorcraft_engine::{Session, ViewInfo};
|
||||
|
||||
pub use control::{ControlRequest, ControlResponse};
|
||||
pub use state::{UiState, View};
|
||||
pub use sysclip::SystemClipboard;
|
||||
pub use sysclip::{ClipboardProbeFactory, SystemClipboard};
|
||||
|
||||
/// What a file dialog shows: a suggested file name (save dialogs), the folder to start in and the
|
||||
/// file-type filters.
|
||||
@@ -205,6 +208,10 @@ pub struct Services {
|
||||
/// Paste takes SVG, PDF, text and bitmaps from other apps. Without it, SVG text only (through
|
||||
/// egui and `clipboard_read`).
|
||||
pub system_clipboard: Option<Box<dyn SystemClipboard>>,
|
||||
/// A second system-clipboard handle, for checking whether Paste has something to take on a
|
||||
/// background thread (Linux: an X11 clipboard owner that never answers would freeze the UI).
|
||||
/// Taken on the first frame. Without it the check runs on the UI thread.
|
||||
pub clipboard_probe: Option<ClipboardProbeFactory>,
|
||||
/// File → Show in Folder: select a file in the system file manager (desktop).
|
||||
pub reveal: Option<RevealFn>,
|
||||
/// Write a file from any thread (desktop): lets Background Save and Export write off the UI
|
||||
@@ -327,8 +334,11 @@ pub struct VectorcraftApp {
|
||||
/// (SVG without a `system_clipboard`) while the internal clipboard is empty. It enables the
|
||||
/// Paste menu items.
|
||||
pub(crate) system_paste: bool,
|
||||
/// When `system_paste` was last checked (app time, s; at most once per frame).
|
||||
/// When `system_paste` was last checked in line (app time, s; at most once per frame).
|
||||
system_paste_at: f64,
|
||||
/// The thread that checks the system clipboard for `system_paste` instead
|
||||
/// ([`Services::clipboard_probe`]).
|
||||
clipboard_probe: Option<clipboard_probe::Probe>,
|
||||
/// Keyboard pastes of something other than text (see [`shortcuts::PasteChord`]).
|
||||
pub(crate) paste_chord: shortcuts::PasteChord,
|
||||
/// Saves and exports running in the background (Preferences → File Handling).
|
||||
@@ -404,6 +414,7 @@ impl VectorcraftApp {
|
||||
place: Default::default(),
|
||||
system_paste: false,
|
||||
system_paste_at: f64::NEG_INFINITY,
|
||||
clipboard_probe: None,
|
||||
paste_chord: Default::default(),
|
||||
background: Default::default(),
|
||||
recovery: Default::default(),
|
||||
@@ -540,19 +551,8 @@ impl VectorcraftApp {
|
||||
|
||||
/// Select a tool (also used by the toolbar and shortcuts).
|
||||
pub fn select_tool(&mut self, id: &str) {
|
||||
self.change_tool(id, true);
|
||||
}
|
||||
|
||||
/// Go back to tool `id` after a temporary one, without choosing it afresh
|
||||
/// ([`vectorcraft_engine::Session::switch_tool`]).
|
||||
pub fn restore_tool(&mut self, id: &str) {
|
||||
self.change_tool(id, false);
|
||||
}
|
||||
|
||||
fn change_tool(&mut self, id: &str, choose: bool) {
|
||||
let v = self.view_info();
|
||||
let r = if choose { self.session.select_tool(id, v) } else { self.session.switch_tool(id, v) };
|
||||
if let Err(e) = r {
|
||||
if let Err(e) = self.session.select_tool(id, v) {
|
||||
self.ui.status = e.to_string();
|
||||
}
|
||||
if let Some(g) = vectorcraft_tools::catalog::group_of(id)
|
||||
@@ -560,9 +560,6 @@ impl VectorcraftApp {
|
||||
{
|
||||
*slot = id.to_string();
|
||||
}
|
||||
if canvas::is_selection_tool(id) {
|
||||
self.ui.last_selection_tool = id.to_string();
|
||||
}
|
||||
toolbar::remember(self, id);
|
||||
self.ui.flyout = None;
|
||||
}
|
||||
@@ -743,11 +740,20 @@ impl VectorcraftApp {
|
||||
}
|
||||
self.last_time = now;
|
||||
self.sync_views();
|
||||
// Read the system clipboard only when that alone decides whether Paste is enabled, and at
|
||||
// most a few times a second (opening it locks it against other apps on some systems).
|
||||
if !(0.0..SYSTEM_CLIPBOARD_POLL).contains(&(now - self.system_paste_at)) {
|
||||
// Read the system clipboard only when that alone decides whether Paste is enabled. A
|
||||
// background thread reads it where the host installs one (an unresponsive owner must never
|
||||
// stall the frame loop); otherwise, or once that thread is gone, it is read here, at most a
|
||||
// few times a second (opening it locks it against other apps on some systems).
|
||||
let wanted = self.session.clipboard.is_empty() && self.session.active().is_some();
|
||||
if let Some(make) = self.services.clipboard_probe.take() {
|
||||
self.clipboard_probe = clipboard_probe::Probe::start(make, ctx.clone());
|
||||
}
|
||||
if let Some(pasteable) = self.clipboard_probe.as_mut().and_then(|p| p.pasteable(wanted)) {
|
||||
self.system_paste = pasteable;
|
||||
} else if !(0.0..SYSTEM_CLIPBOARD_POLL).contains(&(now - self.system_paste_at)) {
|
||||
self.clipboard_probe = None;
|
||||
self.system_paste_at = now;
|
||||
self.system_paste = self.session.clipboard.is_empty() && self.session.active().is_some() && self.system_clipboard_pasteable();
|
||||
self.system_paste = wanted && self.system_clipboard_pasteable();
|
||||
}
|
||||
background::poll(self);
|
||||
if !self.background.jobs.is_empty() {
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
return;
|
||||
};
|
||||
let n_sel = st.selection.len();
|
||||
let anchor_mode = !st.selection.anchors.is_empty();
|
||||
let anchors = crate::chrome::anchor_controls(app);
|
||||
let first = first_selected(app);
|
||||
let label = match (&first, n_sel) {
|
||||
(None, _) => tl!("Document").to_string(),
|
||||
@@ -85,10 +85,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
}
|
||||
if anchor_mode {
|
||||
if anchors != crate::chrome::AnchorControls::None {
|
||||
divider(ui);
|
||||
section_header(ui, tl!("Anchor Point"));
|
||||
crate::chrome::anchor_buttons(app, ui);
|
||||
crate::chrome::anchor_buttons(app, ui, anchors);
|
||||
}
|
||||
divider(ui);
|
||||
section_header(ui, tl!("Quick Actions"));
|
||||
|
||||
@@ -246,7 +246,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// Enter with a selection tool opens the Move dialog, as a double-click on its button
|
||||
// does.
|
||||
let tool = app.session.tool_id();
|
||||
if app.ui.dialog.is_none() && crate::canvas::is_selection_tool(tool) {
|
||||
if app.ui.dialog.is_none() && vectorcraft_tools::catalog::is_selection_tool(tool) {
|
||||
// Nothing selected: it fails and nothing opens (the menu item is disabled then too).
|
||||
let _ = crate::toolbar::open_options(app, tool);
|
||||
}
|
||||
|
||||
@@ -283,9 +283,6 @@ pub struct UiState {
|
||||
pub flyout: Option<usize>,
|
||||
/// Last tool shown for each toolbar group (flyout selection sticks).
|
||||
pub group_tool: Vec<String>,
|
||||
/// The selection tool used last (Selection, Direct Selection or Group Selection): a Cmd press
|
||||
/// with any other tool drags with it.
|
||||
pub last_selection_tool: String,
|
||||
pub status: String,
|
||||
pub palette_open: bool,
|
||||
pub palette_query: String,
|
||||
@@ -496,7 +493,6 @@ impl Default for UiState {
|
||||
dialog: None,
|
||||
flyout: None,
|
||||
group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(),
|
||||
last_selection_tool: "selection".into(),
|
||||
status: String::new(),
|
||||
palette_open: false,
|
||||
palette_query: String::new(),
|
||||
|
||||
@@ -24,6 +24,11 @@ pub trait SystemClipboard {
|
||||
fn has(&mut self, mimes: &[&'static str]) -> bool;
|
||||
}
|
||||
|
||||
/// Makes a second system-clipboard handle, to check off the UI thread whether Paste has something
|
||||
/// to take ([`Services::clipboard_probe`](crate::Services::clipboard_probe)). It is called on that
|
||||
/// thread and the handle lives and dies there, so the handle needn't be `Send`.
|
||||
pub type ClipboardProbeFactory = Box<dyn FnOnce() -> Box<dyn SystemClipboard> + Send>;
|
||||
|
||||
/// The command (and its params) that loads `f` into the internal clipboard, centred on `center`.
|
||||
pub(crate) fn import_command(f: &Flavour, center: Option<[f64; 2]>) -> (&'static str, Value) {
|
||||
let b64 = || vectorcraft_format::base64_encode(&f.data);
|
||||
|
||||
@@ -205,3 +205,26 @@ fn the_control_bar_converts_connects_and_cuts_selected_anchors() {
|
||||
assert!(app.session.active().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].closed);
|
||||
assert_eq!(anchor_count(&app, id), 4, "the coincident ends merge");
|
||||
}
|
||||
|
||||
/// #504: with a tool that edits anchors (Direct Selection, the Pen…), a path selected as a whole
|
||||
/// shows all its anchors selected, and the Control bar and the Properties panel offer to convert
|
||||
/// them; removing and cutting wait for anchors direct-selected. The Selection tool shows neither.
|
||||
#[test]
|
||||
fn a_whole_path_converts_with_the_tools_that_edit_anchors() {
|
||||
let mut app = app();
|
||||
let id = rect(&mut app);
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
app.select_tool("selection");
|
||||
assert!(!has(&control_frame(&mut app, &ctx, vec![]), "Convert:"));
|
||||
for tool in ["directSelection", "pen"] {
|
||||
app.select_tool(tool);
|
||||
let texts = control_frame(&mut app, &ctx, vec![]);
|
||||
assert!(has(&texts, "Convert:") && !has(&texts, "Anchors:"), "{tool}: {texts:?}");
|
||||
let props = crate::tests_labels::painted_text(&mut app, crate::panels::properties::show);
|
||||
assert!(props.contains("Convert:") && !props.contains("Anchors:"), "{tool}: {props}");
|
||||
}
|
||||
click_button(&mut app, &ctx, "Convert:", 1);
|
||||
let sp = app.session.active().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
|
||||
assert!(sp.anchors.iter().all(|a| a.has_in() && a.has_out()), "every corner made smooth: {sp:?}");
|
||||
}
|
||||
@@ -66,7 +66,7 @@ pub(super) fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value {
|
||||
app.run(id, p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn copy_rect(app: &mut VectorcraftApp) {
|
||||
pub(super) fn copy_rect(app: &mut VectorcraftApp) {
|
||||
let id = run(app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone();
|
||||
run(app, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(app, "select.set", json!({"ids": [id]}));
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! The system clipboard is checked for Paste off the UI thread where the host installs a probe
|
||||
//! (Linux): an X11 clipboard owner that never answers used to block the frame loop for seconds, so
|
||||
//! the window stopped drawing and could not even be closed. The in-line check (no probe: the web,
|
||||
//! Windows, macOS) is covered by `tests_clipboard` and `tests_sysclip`.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::clipboard::Flavour;
|
||||
|
||||
use crate::tests_sysclip::{copy_rect, run};
|
||||
use crate::{Services, SystemClipboard, VectorcraftApp, menus};
|
||||
|
||||
/// What the clipboard handles saw: the thread each `has()` ran on, and how many handles are alive.
|
||||
#[derive(Default)]
|
||||
struct Recorder {
|
||||
threads: Mutex<Vec<Option<String>>>,
|
||||
alive: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
fn looks(&self) -> usize {
|
||||
self.threads.lock().unwrap().len()
|
||||
}
|
||||
}
|
||||
|
||||
/// A system clipboard whose `has()` takes `delay` (an owner slow to answer) and answers `verdict`,
|
||||
/// or panics without one (a bug in the platform code).
|
||||
struct Slow {
|
||||
rec: Arc<Recorder>,
|
||||
delay: Duration,
|
||||
verdict: Option<bool>,
|
||||
}
|
||||
|
||||
impl Slow {
|
||||
fn boxed(rec: &Arc<Recorder>, delay: Duration, verdict: Option<bool>) -> Box<dyn SystemClipboard> {
|
||||
rec.alive.fetch_add(1, Ordering::SeqCst);
|
||||
Box::new(Self { rec: Arc::clone(rec), delay, verdict })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Slow {
|
||||
fn drop(&mut self) {
|
||||
self.rec.alive.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl SystemClipboard for Slow {
|
||||
fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
fn holds_ours(&mut self) -> bool {
|
||||
false
|
||||
}
|
||||
fn read(&mut self, _mimes: &[&'static str]) -> Option<Flavour> {
|
||||
None
|
||||
}
|
||||
fn has(&mut self, _mimes: &[&'static str]) -> bool {
|
||||
self.rec.threads.lock().unwrap().push(std::thread::current().name().map(str::to_owned));
|
||||
std::thread::sleep(self.delay);
|
||||
self.verdict.expect("the clipboard failed")
|
||||
}
|
||||
}
|
||||
|
||||
/// An app whose two clipboard handles record into `rec`: the UI's says `inline`, the probe's
|
||||
/// `probe`, each after `delay`.
|
||||
fn app(rec: &Arc<Recorder>, delay: Duration, inline: bool, probe: Option<bool>) -> VectorcraftApp {
|
||||
let make = {
|
||||
let rec = Arc::clone(rec);
|
||||
move || Slow::boxed(&rec, delay, probe)
|
||||
};
|
||||
let services =
|
||||
Services { system_clipboard: Some(Slow::boxed(rec, delay, Some(inline))), clipboard_probe: Some(Box::new(make)), ..Default::default() };
|
||||
VectorcraftApp::new(Session::new(), services)
|
||||
}
|
||||
|
||||
/// One headless frame of app logic in the test's one context (a new one would restart the fonts),
|
||||
/// half a second after the last: past the in-line check's throttle, so it would run every frame.
|
||||
fn frame(app: &mut VectorcraftApp) {
|
||||
thread_local! {
|
||||
static CTX: egui::Context = egui::Context::default();
|
||||
static NOW: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
|
||||
}
|
||||
let time = NOW.with(|t| {
|
||||
t.set(t.get() + 0.5);
|
||||
t.get()
|
||||
});
|
||||
let input = egui::RawInput { time: Some(time), ..Default::default() };
|
||||
CTX.with(|ctx| ctx.run_ui(input, |ui| app.logic(ui.ctx())).textures_delta.clear());
|
||||
}
|
||||
|
||||
/// Frames for `wait`, or until `done` holds; whether it does.
|
||||
fn frames_until(app: &mut VectorcraftApp, wait: Duration, done: impl Fn(&VectorcraftApp) -> bool) -> bool {
|
||||
let end = Instant::now() + wait;
|
||||
loop {
|
||||
frame(app);
|
||||
if done(app) || Instant::now() > end {
|
||||
return done(app);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_clipboard_is_read_off_the_ui_thread() {
|
||||
let rec = Arc::new(Recorder::default());
|
||||
let mut app = app(&rec, Duration::from_secs(1), false, Some(true));
|
||||
// The first frames install the UI fonts. Without a document Paste is off whatever the clipboard
|
||||
// holds: nobody looks.
|
||||
assert!(!frames_until(&mut app, Duration::from_millis(100), |_| rec.looks() > 0));
|
||||
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
|
||||
frame(&mut app);
|
||||
let t0 = Instant::now();
|
||||
frame(&mut app);
|
||||
assert!(t0.elapsed() < Duration::from_millis(300), "the frame waited on the clipboard: {:?}", t0.elapsed());
|
||||
// The probe's verdict (the UI's own handle would say no) enables Paste once it arrives.
|
||||
assert!(frames_until(&mut app, Duration::from_secs(3), |app| app.system_paste), "the probe's verdict never arrived");
|
||||
assert!(menus::enabled(&app, "edit.paste"));
|
||||
let threads = rec.threads.lock().unwrap().clone();
|
||||
assert!(threads.iter().all(|n| n.as_deref() == Some("vectorcraft-clip")), "checked on: {threads:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probe_rests_after_a_copy_and_stops_with_the_app() {
|
||||
let rec = Arc::new(Recorder::default());
|
||||
let mut app = app(&rec, Duration::ZERO, false, Some(true));
|
||||
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
|
||||
assert!(frames_until(&mut app, Duration::from_secs(2), |app| app.system_paste));
|
||||
// Something copied in the app enables Paste alone: the clipboard isn't read any more.
|
||||
copy_rect(&mut app);
|
||||
frames_until(&mut app, Duration::from_millis(50), |_| false);
|
||||
let looks = rec.looks();
|
||||
frames_until(&mut app, Duration::from_millis(600), |_| false);
|
||||
assert_eq!(rec.looks(), looks);
|
||||
assert!(!app.system_paste && menus::enabled(&app, "edit.paste"));
|
||||
// Quitting waits until the probe's thread has let go of its handle: on X11 the last handle
|
||||
// alive hands what the app copied to the clipboard manager.
|
||||
assert_eq!(rec.alive.load(Ordering::SeqCst), 2);
|
||||
drop(app);
|
||||
assert_eq!(rec.alive.load(Ordering::SeqCst), 0, "the probe's thread kept its clipboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_its_thread_the_check_runs_in_line_again() {
|
||||
let rec = Arc::new(Recorder::default());
|
||||
// The probe's clipboard panics: its thread ends.
|
||||
let mut app = app(&rec, Duration::ZERO, true, None);
|
||||
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
|
||||
assert!(frames_until(&mut app, Duration::from_secs(2), |app| app.system_paste), "no fallback");
|
||||
assert!(app.clipboard_probe.is_none());
|
||||
let threads = rec.threads.lock().unwrap().clone();
|
||||
assert_eq!(threads.first().cloned().flatten().as_deref(), Some("vectorcraft-clip"), "{threads:?}");
|
||||
}
|
||||
@@ -300,7 +300,7 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::
|
||||
"hand" => app.run("view.fitArtboard", json!({})),
|
||||
"zoom" => app.run("view.actualSize", json!({})),
|
||||
"rotate" | "scale" | "reflect" | "shear" | "selection" | "directSelection" | "groupSelection" => {
|
||||
let dialog = if crate::canvas::is_selection_tool(tool) { "move" } else { tool };
|
||||
let dialog = if vectorcraft_tools::catalog::is_selection_tool(tool) { "move" } else { tool };
|
||||
let id = format!("object.{dialog}");
|
||||
if let Some(c) = vectorcraft_engine::find_command(&id) {
|
||||
(c.enabled)(&app.session)?;
|
||||
|
||||
@@ -22,7 +22,7 @@ so only enable it while you use it. Transport: `apps/vectorcraft/src/control_ser
|
||||
| `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item |
|
||||
| `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected |
|
||||
| `ui.tool.select` / `ui.tool.list` | `{tool}` | |
|
||||
| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse |
|
||||
| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse: `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was |
|
||||
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input |
|
||||
| `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls and Cmd- or Alt-wheel (Option on the Mac) zooms about the pointer; with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it |
|
||||
| `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?}` | |
|
||||
|
||||
@@ -74,6 +74,7 @@ By default VectorCraft's own crates log at `info` and everything else at `warn`.
|
||||
The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On machines with two GPUs it renders on the one the desktop runs on unless Preferences say otherwise; see [Desktop graphics processor](#desktop-graphics-processor) (#502). The system clipboard (`apps/vectorcraft/src/clipboard.rs`) is arboard with its `wayland-data-control` feature:
|
||||
|
||||
- **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. egui's own text paste into fields goes through smithay-clipboard and works either way.
|
||||
- **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. A paste itself still reads on the UI thread, so pasting from such an owner waits for it once. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server.
|
||||
- **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EMF/WMF or a bitmap), before the clipboard's other formats (which include the files' paths as text).
|
||||
- **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.36 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or run the app under XWayland, where drops work (`WAYLAND_DISPLAY= vectorcraft`).
|
||||
- **Pens and pen displays under Wayland (#491):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336)): the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, either run the app under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer (`WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse, without pressure: winit 0.30 reads pen pressure on Windows only (Windows Ink, which reaches the Liquify tools' Use Pressure Pen). Other compositors that don't emulate a pointer for tablets behave the same way.
|
||||
|
||||
+20
-5
@@ -1049,7 +1049,20 @@ on top of each other, and an open path becomes one path per piece. Each cut leav
|
||||
so `path.moveAnchors {dx, dy}` (or a Direct Selection drag) pulls the path apart there; `path.join {}` (Connect
|
||||
Selected End Points) joins the ends again. `path.convertAnchor {id, subpath?, anchor, to, x?, y?}` and
|
||||
`path.split {id, subpath?, anchor}` do the same to one anchor (the Anchor Point and Scissors tools); the Pen with Alt
|
||||
held over a selected path's handle or anchor works as the Anchor Point tool.
|
||||
held over a selected path's handle, anchor or segment works as the Anchor Point tool. `path.reshapeSegment {id,
|
||||
subpath?, segment, t, dx, dy}` (a segment dragged with Direct Selection or the Anchor Point tool) moves the segment's
|
||||
point at `t` by `dx`, `dy`: a smooth anchor at either end stays smooth, its other handle turning with the moved one.
|
||||
|
||||
A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on
|
||||
macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen,
|
||||
Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing
|
||||
the path it had begun while that stays selected. Its reply's `tool` is the tool given back.
|
||||
|
||||
```json
|
||||
{"name":"pointer_gesture","arguments":{"tool":"pen","events":[{"kind":"down","x":100,"y":300},{"kind":"up","x":100,"y":300},{"kind":"down","x":200,"y":300},{"kind":"drag","x":250,"y":300},{"kind":"up","x":250,"y":300}]}}
|
||||
{"name":"pointer_gesture","arguments":{"mods":{"cmd":true},"events":[{"kind":"down","x":250,"y":300},{"kind":"drag","x":250,"y":260},{"kind":"up","x":250,"y":260}]}}
|
||||
{"name":"pointer_gesture","arguments":{"events":[{"kind":"down","x":300,"y":350},{"kind":"up","x":300,"y":350}]}}
|
||||
```
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"select.anchors","params":{"id":12,"anchors":[[0,2]]}}}
|
||||
@@ -1153,8 +1166,9 @@ Effects off a 100 pt wide rectangle with a 10 pt stroke set to `width: 220` gets
|
||||
|
||||
The Selection & Anchor Display and General preferences apply to `pointer_gesture` as they do to the mouse:
|
||||
|
||||
- `selectionTolerance` (1–8 px, 3 by default): how near a click must be to a path to pick it, and to an anchor or
|
||||
handle for Direct Selection.
|
||||
- `selectionTolerance` (1–8 px, 3 by default): how near a click must be to a path to pick it, and to an anchor,
|
||||
handle or segment for Direct Selection, the Anchor Point, Add and Delete Anchor Point and Scissors tools, and the
|
||||
Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor.
|
||||
- `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does.
|
||||
- `ctrlClickSelectsBehind` (on by default): a Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl
|
||||
elsewhere) selects the object under the selected one there, the next such click the one under that, then the
|
||||
@@ -1168,8 +1182,9 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture
|
||||
hidden art with the artboard too; off (the default) it stays where it is.
|
||||
- `penRubberBand`, `curvatureRubberBand` (on by default): off, the Pen and Curvature tools draw no preview segment to
|
||||
the pointer.
|
||||
- `showHandlesMultipleAnchors` (on by default): off, Direct Selection shows and drags direction handles only while a
|
||||
single anchor is selected. `handleStyle` (`solid`, `hollow`, `large`) draws their ends (desktop app).
|
||||
- `showHandlesMultipleAnchors` (on by default): off, Direct Selection (and the Anchor Point tool, and the Pen with Alt)
|
||||
shows and drags direction handles only while a single anchor is selected. On, the handles of the direct-selected
|
||||
anchors, or of every anchor of a path selected as a whole, show and drag. `handleStyle` (`solid`, `hollow`, `large`) draws their ends (desktop app).
|
||||
- `hideCornerWidgetAbove` (177° by default): corners wider than this show no Live Corners widget (a rectangle's right
|
||||
angles hide below 90°).
|
||||
- `transformPatternTiles` (off by default): the default of the transforms' `patterns` param (`object.transform`,
|
||||
|
||||
Reference in new issue
Block a user