diff --git a/ROADMAP.md b/ROADMAP.md index bae11f915..3944f6d57 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), 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 import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), 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 into floating panels that move, stack and dock again (#495), the 0.5.0 startup crash on dual-GPU Linux desktops under Wayland fixed: the desktop's own GPU by default and a restart on the next GPU when one can't show the window (#502), path editing while drawing: Cmd/Ctrl with the Pen borrowing Direct Selection and drawing on afterwards, Pen+Alt reshaping segments, handles of a whole selected path dragging, and handle drags no longer re-gathering snap targets every move (#494), the Control bar's and Properties panel's Convert buttons for a path selected as a whole with Direct Selection, the Pen and the anchor tools (#504), the Pen closing a path dragged out of its first anchor every time, without flicker (#501), the Paste menu checking the system clipboard on a background thread on Linux so an X11 clipboard owner that never answers no longer freezes the window (#510), PDF/`.ai` import keeping a type object's outline stroke on the type, wrapped lines as area type, barcode digits in place and layers in the file's stacking order (#508), the Italian interface (#514), EPS images with several data sources read in turn (#498), `restore` undoing dictionary changes in EPS import (part of #505), the macOS menu bar laid out as a Mac app's (the VectorCraft menu with Settings, Language and Appearance, the system's Hide, Services and Window items; owner's request), Object › Image Trace › Make tracing with the Default preset instead of asking for a preset's name (#543), the rulers' unit menu (#528), Live Corners on stars, polygons and pen paths (#511), the drawing tools snapping to Smart Guides as the Selection tool does, with Construction Guides (#506), the in-window menus' Select All, Cut, Copy and Paste acting on the text field they were opened from (#516), Windows rendering through DX12 before Vulkan (#545), Image Trace tracing colour layers in parallel and refusing traces too large for memory, with the canvas outlining huge selections by their bounds (#525), SVGs of chosen artboards holding only the art over each artboard (#550), the font menu scrolling only its list, under a search field and filters that stay put (#555), a click on an object of a selection making it the key object that Align aligns to and Distribute Spacing spaces from, drawn with a thicker outline (#541), Shape Builder merges taken from the planar map itself, so merged regions leave no inner edge, hairline gap or spur in their outline (#569), `.ai` written by the exports and the CLI (`--export`, `convert`) as Save As writes it (#526), SVG round trips keeping hidden objects and `data-*` attributes (#522), the gradient stop popover staying open after the click that opens it from the Gradient panel (#577), standard ligatures kept under small tracking and dropped only past about −8% / +22% of a word space or when the character asks for them (#583), the Color panel keeping its height as warnings come and go so a drag on its spectrum no longer flickers near white (#578), fonts that font services such as Adobe Fonts load on Windows, listed through DirectWrite (#579), `.ai` files writing their layers and sublayers as PDF layers, hidden ones with their art, and PDF layers nested in layers importing as sublayers (#372), file dialogs on Linux shown off the UI thread so the compositor no longer finds the window not responding, and parented to the window on Linux and Windows (#592), anchors and handle ends picked from 2 px past their drawn size before the segments through them (#593), an image copied in a browser pasting as the picture, not its address (#597), the Free Transform widget with Constrain, Free Transform, Perspective Distort and Free Distort (#598), touch gestures: a two-finger tap undoes and a three-finger tap redoes (#585), the font menus' live preview staying on the text instead of flickering on and off every frame (#563), Edit Artboards showing the active artboard in the Properties panel with New Artboard, Delete Artboard and Exit (#530), the same DirectWrite fonts in `vectorcraft-cli` and its MCP server (#579), SVG layers keeping their names when wrapped and sublayers round-tripping through SVG (#372), a Layers panel that lays out only the rows in view and keeps a document's open rows in its file (#638), a panel dropped on the dock lights up the icon column it goes back to and pops out of its icon (#649), Image Trace's View modes and an Advanced section that stays as it was left (part of #641), Image Trace's Palette: Limited, Full Tone, Automatic and Document Library (part of #641), Image Trace's Create Strokes: line art traced as stroked centre lines (part of #641), a dual-GPU Mac falling back to its other GPU when one fails to start (#651), two fingers dragged on a touch screen panning the canvas (part of #449), the Home screen's Recent Files and a double-clicked New Document preset creating the document (part of #663), quitting no longer crashing on Macs with a Touch Bar (#661), Animated Zoom, Large Tabs, Scale Cursor Proportional to UI and anti-aliased bitmaps in Pixel Preview acting (part of #394), Smart Guides › Spacing Guides (part of #394), Edit Artboards' Properties choosing an artboard's size preset and flipping it between portrait and landscape (#671), Preferences › Type › Additional Fonts Folder loading the fonts of a folder you choose (#683), Canvas Color's light, medium and dark grey (part of #663), a document tab's close box after its title on Windows and Linux, before it on macOS (part of #673), Rearrange All Artboards' layouts (a grid by row or by column, one row, one column) and right-to-left order, one click away in the Properties and Artboards panels (#681), User Interface › Show Tool Group Labels and Cmd+, opening Settings on the Mac (part of #663), the Windows taskbar and Alt+Tab showing VectorCraft's icon, a click with a selection tool making its artboard the active one, and Paste in Place, in Front and in Back pasting onto the active artboard (#693), Photoshop-style raster effects on a pixel-filter pipeline: Effect › Blur › Radial Blur and Smart Blur, Effect › Sharpen › Unsharp Mask (part of gap 2), the Properties panel's number fields all one width (#696), the rotate cursor drawn as a curved double arrow (#701), the Templates folder in the desktop's own documents folder, made when missing (#703), PDF and .ai glyphs whose ToUnicode names no character (U+FFFD) taking their character from the embedded font or keeping their outlines, with a warning (#708), Illustrator EPS and `.ai` files opening from their editing data with their colours, gradients, transparency, images, names and every artboard (part of #637), `.ai` files saved without PDF compatibility opening from their editing data (part of #637), guides left out of raster exports and Fit to Artwork Bounds, hidden art left out of Fit to Artwork Bounds, Illustrator files compared with their page object by object, and `editingData: false` opening only what the page prints (#735), art reaching past a PDF's page clipped to its crop box (#675), Package collecting what placed documents link to (#777), area type, threaded type and type on a path made whole from Illustrator files' text documents (part of #637), the missing-fonts dialog with Find Fonts and a folder search (#792), Effect › Stylize › Glowing Edges (#765), Offset Path's Joins and Zig Zag's Points as dropdowns and Relative/Absolute as radio buttons in the effect dialogs (#828), the control channel's `app.quit` reporting a pending save prompt (#830), blurred type that stays put while the view moves (#755), Windows starting on Direct3D 12 and loading no Vulkan driver unless asked (#806), the Artboard tool naming its artboard once (#824), Save for Web taking typed pixel sizes (#839), rulers ticked over their whole length in a rotated view (#826), the gradient stop popover opening beside the art (#862) and recent colours recolouring the selected stop (#835), every align button following Align To (#789), the Properties panel's Paragraph section with all seven alignments and Hyphenate (#775), isolation mode dimming and locking the art around the isolated group (#833), color books (`.acb`) opening as swatch libraries (#831), files that can't be opened reported in a dialog (#861), `run` and `command_batch` steps using earlier steps' results (#785), ruler guides pulling drawn points with Smart Guides on and Smart Guides labelling centres and anchors on hover (#812), shadows and glows keeping their blend modes in PDF (#827) and `.ai` import skipping layer checks that can't succeed (#758), the Curvature tool editing any selected path (#798), raster exports composited in floating point so translucent edges over opaque art stay opaque (#787), Calligraphic and Bristle Brush Options with pen-pressure Calligraphic brushes (part of #852); see [Honest assessment](#honest-assessment-2026-10-05))._ +_Last updated: 2026-10-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), 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 import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), 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 into floating panels that move, stack and dock again (#495), the 0.5.0 startup crash on dual-GPU Linux desktops under Wayland fixed: the desktop's own GPU by default and a restart on the next GPU when one can't show the window (#502), path editing while drawing: Cmd/Ctrl with the Pen borrowing Direct Selection and drawing on afterwards, Pen+Alt reshaping segments, handles of a whole selected path dragging, and handle drags no longer re-gathering snap targets every move (#494), the Control bar's and Properties panel's Convert buttons for a path selected as a whole with Direct Selection, the Pen and the anchor tools (#504), the Pen closing a path dragged out of its first anchor every time, without flicker (#501), the Paste menu checking the system clipboard on a background thread on Linux so an X11 clipboard owner that never answers no longer freezes the window (#510), PDF/`.ai` import keeping a type object's outline stroke on the type, wrapped lines as area type, barcode digits in place and layers in the file's stacking order (#508), the Italian interface (#514), EPS images with several data sources read in turn (#498), `restore` undoing dictionary changes in EPS import (part of #505), the macOS menu bar laid out as a Mac app's (the VectorCraft menu with Settings, Language and Appearance, the system's Hide, Services and Window items; owner's request), Object › Image Trace › Make tracing with the Default preset instead of asking for a preset's name (#543), the rulers' unit menu (#528), Live Corners on stars, polygons and pen paths (#511), the drawing tools snapping to Smart Guides as the Selection tool does, with Construction Guides (#506), the in-window menus' Select All, Cut, Copy and Paste acting on the text field they were opened from (#516), Windows rendering through DX12 before Vulkan (#545), Image Trace tracing colour layers in parallel and refusing traces too large for memory, with the canvas outlining huge selections by their bounds (#525), SVGs of chosen artboards holding only the art over each artboard (#550), the font menu scrolling only its list, under a search field and filters that stay put (#555), a click on an object of a selection making it the key object that Align aligns to and Distribute Spacing spaces from, drawn with a thicker outline (#541), Shape Builder merges taken from the planar map itself, so merged regions leave no inner edge, hairline gap or spur in their outline (#569), `.ai` written by the exports and the CLI (`--export`, `convert`) as Save As writes it (#526), SVG round trips keeping hidden objects and `data-*` attributes (#522), the gradient stop popover staying open after the click that opens it from the Gradient panel (#577), standard ligatures kept under small tracking and dropped only past about −8% / +22% of a word space or when the character asks for them (#583), the Color panel keeping its height as warnings come and go so a drag on its spectrum no longer flickers near white (#578), fonts that font services such as Adobe Fonts load on Windows, listed through DirectWrite (#579), `.ai` files writing their layers and sublayers as PDF layers, hidden ones with their art, and PDF layers nested in layers importing as sublayers (#372), file dialogs on Linux shown off the UI thread so the compositor no longer finds the window not responding, and parented to the window on Linux and Windows (#592), anchors and handle ends picked from 2 px past their drawn size before the segments through them (#593), an image copied in a browser pasting as the picture, not its address (#597), the Free Transform widget with Constrain, Free Transform, Perspective Distort and Free Distort (#598), touch gestures: a two-finger tap undoes and a three-finger tap redoes (#585), the font menus' live preview staying on the text instead of flickering on and off every frame (#563), Edit Artboards showing the active artboard in the Properties panel with New Artboard, Delete Artboard and Exit (#530), the same DirectWrite fonts in `vectorcraft-cli` and its MCP server (#579), SVG layers keeping their names when wrapped and sublayers round-tripping through SVG (#372), a Layers panel that lays out only the rows in view and keeps a document's open rows in its file (#638), a panel dropped on the dock lights up the icon column it goes back to and pops out of its icon (#649), Image Trace's View modes and an Advanced section that stays as it was left (part of #641), Image Trace's Palette: Limited, Full Tone, Automatic and Document Library (part of #641), Image Trace's Create Strokes: line art traced as stroked centre lines (part of #641), a dual-GPU Mac falling back to its other GPU when one fails to start (#651), two fingers dragged on a touch screen panning the canvas (part of #449), the Home screen's Recent Files and a double-clicked New Document preset creating the document (part of #663), quitting no longer crashing on Macs with a Touch Bar (#661), Animated Zoom, Large Tabs, Scale Cursor Proportional to UI and anti-aliased bitmaps in Pixel Preview acting (part of #394), Smart Guides › Spacing Guides (part of #394), Edit Artboards' Properties choosing an artboard's size preset and flipping it between portrait and landscape (#671), Preferences › Type › Additional Fonts Folder loading the fonts of a folder you choose (#683), Canvas Color's light, medium and dark grey (part of #663), a document tab's close box after its title on Windows and Linux, before it on macOS (part of #673), Rearrange All Artboards' layouts (a grid by row or by column, one row, one column) and right-to-left order, one click away in the Properties and Artboards panels (#681), User Interface › Show Tool Group Labels and Cmd+, opening Settings on the Mac (part of #663), the Windows taskbar and Alt+Tab showing VectorCraft's icon, a click with a selection tool making its artboard the active one, and Paste in Place, in Front and in Back pasting onto the active artboard (#693), Photoshop-style raster effects on a pixel-filter pipeline: Effect › Blur › Radial Blur and Smart Blur, Effect › Sharpen › Unsharp Mask (part of gap 2), the Properties panel's number fields all one width (#696), the rotate cursor drawn as a curved double arrow (#701), the Templates folder in the desktop's own documents folder, made when missing (#703), PDF and .ai glyphs whose ToUnicode names no character (U+FFFD) taking their character from the embedded font or keeping their outlines, with a warning (#708), Illustrator EPS and `.ai` files opening from their editing data with their colours, gradients, transparency, images, names and every artboard (part of #637), `.ai` files saved without PDF compatibility opening from their editing data (part of #637), guides left out of raster exports and Fit to Artwork Bounds, hidden art left out of Fit to Artwork Bounds, Illustrator files compared with their page object by object, and `editingData: false` opening only what the page prints (#735), art reaching past a PDF's page clipped to its crop box (#675), Package collecting what placed documents link to (#777), area type, threaded type and type on a path made whole from Illustrator files' text documents (part of #637), the missing-fonts dialog with Find Fonts and a folder search (#792), Effect › Stylize › Glowing Edges (#765), Offset Path's Joins and Zig Zag's Points as dropdowns and Relative/Absolute as radio buttons in the effect dialogs (#828), the control channel's `app.quit` reporting a pending save prompt (#830), blurred type that stays put while the view moves (#755), Windows starting on Direct3D 12 and loading no Vulkan driver unless asked (#806), the Artboard tool naming its artboard once (#824), Save for Web taking typed pixel sizes (#839), rulers ticked over their whole length in a rotated view (#826), the gradient stop popover opening beside the art (#862) and recent colours recolouring the selected stop (#835), every align button following Align To (#789), the Properties panel's Paragraph section with all seven alignments and Hyphenate (#775), isolation mode dimming and locking the art around the isolated group (#833), color books (`.acb`) opening as swatch libraries (#831), files that can't be opened reported in a dialog (#861), `run` and `command_batch` steps using earlier steps' results (#785), ruler guides pulling drawn points with Smart Guides on and Smart Guides labelling centres and anchors on hover (#812), shadows and glows keeping their blend modes in PDF (#827) and `.ai` import skipping layer checks that can't succeed (#758), the Curvature tool editing any selected path (#798), raster exports composited in floating point so translucent edges over opaque art stay opaque (#787), Calligraphic and Bristle Brush Options with pen-pressure Calligraphic brushes (part of #852), a polygon's Polygon Properties in the Properties and Transform panels, Flare Tool Options that last and more tools opening their options on a double-click (part of #812); see [Honest assessment](#honest-assessment-2026-10-05))._ ## Where we are @@ -130,7 +130,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist Clear deletes individual selected compound-path members without deleting their siblings, and explicit object ids work without a selection; Cut still removes the same objects it copies (#786). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Not yet: Update Selection and the Layers panel's saved-selection menu. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; Alt-click or double-click toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. - - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812; the on-canvas pie widget is still to come). + - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812; the on-canvas pie widget is still to come). A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **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). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two straight sides meet at an anchor. Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. @@ -141,7 +141,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist - **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked. - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. - - **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size). + - **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size), and (#812) the Flare tool its Flare Tool Options, the Artboard tool the active artboard's Artboard Options, the graph tools Graph Type for the selected graph, the Symbolism tools the Symbolism Tools Options (Diameter, Intensity, Symbol Set Density) and the Magic Wand tool its panel. - **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638). - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges or its centre is nearest a gridline on each axis, #740; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. - **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 464f40c72..508a0e28a 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -174,6 +174,61 @@ impl LiveShape { spread(radii, *sides as usize); spread(kinds, *sides as usize); } + /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of + /// `xf` (exact while its sides are equal). None for other shapes. + pub fn polygon_radius(&self) -> Option { + let LiveShape::Polygon { radius, xf, .. } = self else { return None }; + Some(radius * xf.determinant().abs().sqrt()) + } + /// A polygon's angle: the counterclockwise degrees in [0, 360) its first vertex is turned by + /// from straight up (the Rotate field's sense). None for other shapes. + pub fn polygon_angle(&self) -> Option { + let LiveShape::Polygon { .. } = self else { return None }; + // No −0° or 360° from rounding: a polygon drawn upright reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True + /// for other shapes. + pub fn polygon_sides_equal(&self) -> bool { + let LiveShape::Polygon { xf, .. } = self else { return true }; + let [a, b, c, d, _, _] = xf.as_coeffs(); + let (sx, sy) = (a.hypot(b), c.hypot(d)); + (sx - sy).abs() <= 1e-9 * sx.max(sy) && (a * c + b * d).abs() <= 1e-9 * sx * sy + } + /// Give a polygon the document radius `r` (centre to vertex, see [`LiveShape::polygon_radius`]). + pub fn set_polygon_radius(&mut self, r: f64) { + let LiveShape::Polygon { radius, xf, .. } = self else { return }; + let k = xf.determinant().abs().sqrt(); + if k > 1e-12 && r.is_finite() { + *radius = r.max(0.0) / k; + } + } + /// The document radius that makes a polygon's sides `side` long (with its sides equal). + pub fn polygon_radius_for_side(&self, side: f64) -> Option { + let LiveShape::Polygon { sides, .. } = self else { return None }; + Some(side / (2.0 * (std::f64::consts::PI / f64::from((*sides).max(3))).sin())) + } + /// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]). + pub fn set_polygon_angle(&mut self, angle: f64) { + let Some(now) = self.polygon_angle() else { return }; + if let LiveShape::Polygon { xf, .. } = self + && angle.is_finite() + { + let centre = *xf * Point::ZERO; + *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; + } + } + /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from + /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. + pub fn make_sides_equal(&mut self) { + let Some(r) = self.polygon_radius() else { return }; + let LiveShape::Polygon { radius, xf, .. } = self else { return }; + let [a, b, _, _, e, f] = xf.as_coeffs(); + let flip = if xf.determinant() < 0.0 { Affine::FLIP_Y } else { Affine::IDENTITY }; + *xf = Affine::translate((e, f)) * Affine::rotate(b.atan2(a)) * flip; + *radius = r; + } /// Apply `a` to the shape. True when the shape is no longer `a` applied to the old path, so /// the caller must regenerate the path with [`LiveShape::to_path`]. /// @@ -253,7 +308,7 @@ impl LiveShape { radii.iter_mut().for_each(|r| *r /= k); true } - /// Rotation angle of the live shape in degrees (shown in the Properties panel). + /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). pub fn angle_deg(&self) -> f64 { match self { LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { @@ -1357,6 +1412,34 @@ mod tests { assert_eq!(path.label(), "Path"); } + #[test] + fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-9; + // A hexagon of radius 10 at (50, 50), drawn 2× and turned 30° clockwise on the page. + let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(2.0); + let mut p = LiveShape::Polygon { radius: 10.0, sides: 6, xf, radii: vec![], kinds: vec![] }; + assert!(close(p.polygon_radius().unwrap(), 20.0) && close(p.polygon_angle().unwrap(), 330.0) && p.polygon_sides_equal()); + p.set_polygon_angle(45.0); + assert!(close(p.polygon_angle().unwrap(), 45.0)); + let centre = p.to_path().bounds().unwrap().center(); + assert!(close(centre.x, 50.0) && close(centre.y, 50.0), "turned about its centre: {centre:?}"); + p.set_polygon_radius(30.0); + assert!(close(p.polygon_radius().unwrap(), 30.0)); + // A hexagon's side is as long as its radius. + assert!(close(p.polygon_radius_for_side(12.0).unwrap(), 12.0)); + // Stretched, its sides differ; Make Sides Equal keeps its centre, angle and mean radius. + p.transform(Affine::scale_non_uniform(2.0, 1.0)); + assert!(!p.polygon_sides_equal()); + let (r, a) = (p.polygon_radius().unwrap(), p.polygon_angle().unwrap()); + p.make_sides_equal(); + assert!(p.polygon_sides_equal() && close(p.polygon_radius().unwrap(), r) && close(p.polygon_angle().unwrap(), a)); + let LiveShape::Polygon { xf, .. } = &p else { panic!("polygon") }; + assert_eq!(*xf * Point::ZERO, Point::new(100.0, 50.0)); + // Other shapes have none of it. + let e = LiveShape::Ellipse { w: 1.0, h: 1.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }; + assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None)); + } + /// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path. fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node { let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), xf }; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 7ef85be91..c083e2d84 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -196,7 +196,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt, kind?: \"round\"|\"invertedRound\"|\"chamfer\", corners?: [i…], sides?: n, pieStart?, pieEnd?: degrees (an ellipse's pie, counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors without handles between two straight sides): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared)", + "{id?, ids?, radius?: pt, kind?: \"round\"|\"invertedRound\"|\"chamfer\", corners?: [i…], sides?: n, polygonAngle?: degrees (counterclockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors without handles between two straight sides): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", has_selection, set_live_shape ), @@ -1095,24 +1095,44 @@ fn set_live_shape(s: &mut Session, p: &Value) -> Result { .transpose()?; let radius = p.get("radius").and_then(Value::as_f64); let sides = p.get("sides").and_then(Value::as_u64); - // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). - let angle = |k: &str| -> Result> { + // A number that must be `what` (None when absent). + let number = |k: &str, ok: fn(f64) -> bool, what: &str| -> Result> { match p.get(k) { None | Some(Value::Null) => Ok(None), Some(v) => v .as_f64() - .filter(|a| a.is_finite()) - .map(|a| Some(a.rem_euclid(360.0))) - .ok_or_else(|| bad("object.setLiveShape", format!("`{k}` must be an angle in degrees, not {v}"))), + .filter(|x| x.is_finite() && ok(*x)) + .map(Some) + .ok_or_else(|| bad("object.setLiveShape", format!("`{k}` must be {what}, not {v}"))), } }; + let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0))); + let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0"); + // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); + // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. + let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); + let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); s.edit("Live Shape", |d, sel| { for id in &ids { let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - if let (Some(l @ LiveShape::Polygon { .. }), Some(n)) = (live.as_mut(), sides) { - l.set_sides(n); + if let Some(l @ LiveShape::Polygon { .. }) = live.as_mut() + && (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal) + { + if let Some(n) = sides { + l.set_sides(n); + } + if equal { + l.make_sides_equal(); + } + if let Some(a) = polygon_angle { + l.set_polygon_angle(a); + } + // A side length sets the radius that gives it (with the new side count). + if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) { + l.set_polygon_radius(r); + } *path = l.to_path(); } if let Some(l @ LiveShape::Ellipse { .. }) = live.as_mut() diff --git a/crates/engine/src/tests_livecorners.rs b/crates/engine/src/tests_livecorners.rs index 023108f89..2e00c7b41 100644 --- a/crates/engine/src/tests_livecorners.rs +++ b/crates/engine/src/tests_livecorners.rs @@ -307,3 +307,42 @@ fn an_ellipse_takes_pie_angles_and_inverts() { assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchor_count(), 4); assert!(s.execute("object.setLiveShape", &json!({"pieStart": "half"})).is_err()); } + +/// #812: a polygon's Polygon Properties: its angle, radius and side length, each one undo step; +/// Make Sides Equal after an uneven scale; bad values are errors. +#[test] +fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = NodeId(s.execute("shape.polygon", &json!({"cx": 200, "cy": 200, "radius": 50, "sides": 6})).unwrap()["id"].as_u64().unwrap()); + let live = |s: &Session| match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(l @ LiveShape::Polygon { .. }), path, .. } => (l.clone(), path.bounds().unwrap()), + k => panic!("{k:?}"), + }; + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + run(&mut s, json!({"polygonAngle": 90})); + let (l, b) = live(&s); + assert!(close(l.polygon_angle().unwrap(), 90.0), "{l:?}"); + // Its first vertex, straight up before, points left now: the hexagon is 100 wide, 86.6 tall. + assert!(close(b.width(), 100.0) && close(b.height(), 86.602_540_378) && close(b.center().x, 200.0), "{b:?}"); + run(&mut s, json!({"polygonRadius": 80})); + assert!(close(live(&s).0.polygon_radius().unwrap(), 80.0)); + // A hexagon's side is as long as its radius; with 4 sides the radius is side / √2. + run(&mut s, json!({"sideLength": 30})); + assert!(close(live(&s).0.polygon_radius().unwrap(), 30.0)); + run(&mut s, json!({"sides": 4, "sideLength": 30})); + assert!(close(live(&s).0.polygon_radius().unwrap(), 30.0 / 2f64.sqrt())); + s.execute("edit.undo", &json!({})).unwrap(); + let LiveShape::Polygon { sides, .. } = live(&s).0 else { panic!("polygon") }; + assert_eq!(sides, 6, "one undo step"); + // Scaled unevenly its sides differ; Make Sides Equal makes them equal again, in place. + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let (l, b) = live(&s); + assert!(!l.polygon_sides_equal() && l.polygon_angle().is_some()); + run(&mut s, json!({"makeSidesEqual": true})); + let (l, after) = live(&s); + assert!(l.polygon_sides_equal() && close(after.center().x, b.center().x) && close(after.center().y, b.center().y), "{b:?} → {after:?}"); + for bad in [json!({"polygonRadius": 0}), json!({"sideLength": -3}), json!({"polygonRadius": "big"}), json!({"polygonAngle": "left"})] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + } +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 259f82566..26b48fbd0 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -397,6 +397,37 @@ fn area_options_fit_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// A live polygon's Polygon Properties with junk values (the fixtures have no polygon), drawn +/// plain, scaled unevenly and flattened to nothing: never a panic, and the document stays sound. +#[test] +fn polygon_properties_junk() { + let mut cases: Vec = vec![json!({"makeSidesEqual": true}), json!({"sides": u64::MAX, "sideLength": 1e-300, "makeSidesEqual": true})]; + for key in ["polygonRadius", "sideLength", "polygonAngle"] { + for v in junk_values() { + cases.push(json!({ key: v })); + } + } + let mut failures = vec![]; + for scale in [None, Some((300.0, 20.0)), Some((1e-300, 100.0))] { + for p in &cases { + let mut s = Fixture::Multi.session(); + let Ok(_) = s.execute("shape.polygon", &json!({"cx": 100, "cy": 100, "radius": 40, "sides": 7, "rotation": 10})) else { continue }; + if let Some((sx, sy)) = scale { + let _ = s.execute("object.scale", &json!({"sx": sx, "sy": sy})); + } + match catch_quiet(|| s.execute("object.setLiveShape", p)) { + Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{scale:?}]: {m}")), + Ok(_) => { + if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("object.setLiveShape {p} [{scale:?}]: {e}")); + } + } + } + } + } + assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); +} + /// After a successful fuzzed call, the document still round-trips and exports. #[test] fn fuzzed_calls_keep_documents_serializable() { diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 1454d6acb..02c35cfe2 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -1,8 +1,9 @@ //! Flare, Reshape, Shaper and Graph tools. //! //! Flare: drag sets the centre and its size (click without dragging opens the Flare Tool Options), -//! then a click sets the end point of the rings. Reshape: drag a point of a selected path; the -//! engine's `path.reshape` adds an anchor there if needed and moves the neighbourhood smoothly. +//! then a click sets the end point of the rings; the rest comes from the tool's options (the Flare +//! Tool Options, which last). Reshape: drag a point of a selected path; the engine's +//! `path.reshape` adds an anchor there if needed and moves the neighbourhood smoothly. use serde_json::{Value, json}; use vectorcraft_geom::{Point, Vec2}; @@ -15,13 +16,35 @@ pub fn create(id: &str) -> Option> { "flare" => Box::new(FlareTool::default()), "reshape" => Box::new(ReshapeTool::default()), "shaper" => Box::new(ShaperTool::default()), - id if vectorcraft_doc::GraphKind::parse(id).is_some() && id.ends_with("Graph") => Box::new(GraphTool::new(id)), + id if is_graph_tool(id) => Box::new(GraphTool::new(id)), _ => return None, }) } +/// Whether `id` is one of the graph tools (`columnGraph`, `pieGraph`…). +pub fn is_graph_tool(id: &str) -> bool { + id.ends_with("Graph") && vectorcraft_doc::GraphKind::parse(id).is_some() +} + +/// The Flare Tool Options as `shape.flare` takes them: (key, default, least, most). The diameter +/// and the rings' path length are in points, the counts whole, the direction in degrees, the +/// rest percentages. +pub const FLARE_OPTIONS: [(&str, f64, f64, f64); 12] = [ + ("diameter", 100.0, 0.0, 1000.0), + ("opacity", 50.0, 0.0, 100.0), + ("brightness", 30.0, 0.0, 100.0), + ("growth", 20.0, 0.0, 300.0), + ("fuzziness", 50.0, 0.0, 100.0), + ("rays", 15.0, 0.0, 50.0), + ("longest", 300.0, 0.0, 1000.0), + ("rayFuzziness", 100.0, 0.0, 100.0), + ("pathLength", 300.0, 0.0, 1000.0), + ("rings", 10.0, 0.0, 50.0), + ("largest", 50.0, 0.0, 250.0), + ("direction", 45.0, 0.0, 360.0), +]; + /// Flare Tool: centre drag, then a click for the rings' end point. -#[derive(Default)] pub struct FlareTool { /// Pressed at (centre) and the current drag point. drag: Option<(Point, Point)>, @@ -29,14 +52,62 @@ pub struct FlareTool { placed: Option<(Point, f64)>, hover: Point, began: bool, - /// Ray count changed with ↑/↓ during the gesture (None = the command's default, 15). + /// Ray count changed with ↑/↓ during the gesture (None = the options' count). rays: Option, + /// The options' values, in [`FLARE_OPTIONS`] order. + values: [f64; 12], + /// Whether the flare has rays and rings (the options' Rays and Rings checkboxes). + rays_on: bool, + rings_on: bool, +} + +impl Default for FlareTool { + fn default() -> Self { + Self { + drag: None, + placed: None, + hover: Point::ZERO, + began: false, + rays: None, + values: FLARE_OPTIONS.map(|(_, default, _, _)| default), + rays_on: true, + rings_on: true, + } + } +} + +/// Whether Flare Tool Options value `key` is a count (whole). +fn is_count(key: &str) -> bool { + matches!(key, "rays" | "rings") +} + +/// Flare Tool Options value `x` of `key` as JSON: a count as a whole number. +fn option_json(key: &str, x: f64) -> Value { + if is_count(key) { json!(x as u64) } else { json!(x) } +} + +/// `shape.flare`'s params for a flare at `c` drawn with the Flare Tool Options `o` (as the tool +/// reports them, [`Tool::options`]): with Rays or Rings off it has none. +pub fn flare_params(o: &Value, c: Point) -> Value { + let mut v = json!({ "cx": c.x, "cy": c.y }); + for (key, default, ..) in FLARE_OPTIONS { + v[key] = o.get(key).cloned().unwrap_or_else(|| option_json(key, default)); + } + for (on, key) in [("raysOn", "rays"), ("ringsOn", "rings")] { + if o.get(on).and_then(Value::as_bool) == Some(false) { + v[key] = json!(0); + } + } + v } impl FlareTool { + /// `shape.flare`'s params: the options, with the dragged centre and diameter, the ray count + /// ↑/↓ chose and the rings' end point once clicked. fn params(&self, c: Point, diameter: f64, end: Option) -> Value { - let mut v = json!({ "cx": c.x, "cy": c.y, "diameter": diameter.max(1.0) }); - if let Some(r) = self.rays { + let mut v = flare_params(&self.options(), c); + v["diameter"] = json!(diameter.max(1.0)); + if let Some(r) = self.rays.filter(|_| self.rays_on) { v["rays"] = json!(r); } if let Some(e) = end { @@ -60,6 +131,7 @@ impl Tool for FlareTool { PointerKind::Down => { if self.placed.is_none() { self.drag = Some((ev.pos, ev.pos)); + self.rays = None; } vec![] } @@ -106,8 +178,8 @@ impl Tool for FlareTool { } fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { // ↑/↓ while drawing add/remove rays. - if matches!(key, ToolKey::Up | ToolKey::Down) && self.began { - let r = self.rays.unwrap_or(15); + if matches!(key, ToolKey::Up | ToolKey::Down) && self.began && self.rays_on { + let r = self.rays.unwrap_or_else(|| self.options()["rays"].as_u64().unwrap_or(0)); self.rays = Some(if key == ToolKey::Up { (r + 1).min(50) } else { r.saturating_sub(1) }); let preview = match (self.drag, self.placed) { (Some((c, p)), _) => self.params(c, 2.0 * p.distance(c), None), @@ -126,7 +198,7 @@ impl Tool for FlareTool { vec![] } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { - // Switching away after the centre drag keeps the flare with its default rings. + // Switching away after the centre drag keeps the flare with the rings its options give. self.drag = None; if self.placed.take().is_some() && std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![] } } @@ -142,6 +214,24 @@ impl Tool for FlareTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + fn options(&self) -> Value { + let mut v = json!({ "raysOn": self.rays_on, "ringsOn": self.rings_on }); + for ((key, ..), x) in FLARE_OPTIONS.iter().zip(self.values) { + v[*key] = option_json(key, x); + } + v + } + fn set_option(&mut self, key: &str, v: &Value) { + match key { + "raysOn" => self.rays_on = v.as_bool().unwrap_or(true), + "ringsOn" => self.rings_on = v.as_bool().unwrap_or(true), + _ => { + let Some((slot, (_, default, lo, hi))) = self.values.iter_mut().zip(FLARE_OPTIONS).find(|(_, (k, ..))| *k == key) else { return }; + let x = v.as_f64().filter(|x| x.is_finite()).unwrap_or(default).clamp(lo, hi); + *slot = if is_count(key) { x.round() } else { x }; + } + } + } } /// Reshape Tool: drag a point on a selected path. @@ -378,6 +468,28 @@ impl Tool for GraphTool { mod tests { use super::*; + /// The Flare Tool Options: kept within their ranges, and what the next drag draws with. + #[test] + fn flare_options_last_and_draw_the_next_flare() { + let mut t = FlareTool::default(); + assert_eq!(t.options()["rays"], json!(15)); + for (k, v) in [("diameter", json!(5000)), ("rays", json!(7.6)), ("opacity", json!("x")), ("ringsOn", json!(false)), ("nope", json!(1))] { + t.set_option(k, &v); + } + let o = t.options(); + assert_eq!( + (o["diameter"].as_f64(), o["rays"].as_u64(), o["opacity"].as_f64(), o["ringsOn"].as_bool()), + (Some(1000.0), Some(8), Some(50.0), Some(false)) + ); + assert!(o.get("nope").is_none()); + // A drag sets the centre and diameter; the options give the rest, rings off. + let p = t.params(Point::new(10.0, 20.0), 40.0, None); + assert_eq!((p["cx"].as_f64(), p["diameter"].as_f64(), p["rays"].as_u64(), p["rings"].as_u64()), (Some(10.0), Some(40.0), Some(8), Some(0))); + assert_eq!(p["longest"].as_f64(), Some(300.0)); + t.set_option("raysOn", &json!(false)); + assert_eq!(t.params(Point::ZERO, 1.0, None)["rays"].as_u64(), Some(0)); + } + #[test] fn create_covers_both() { assert_eq!(create("flare").unwrap().id(), "flare"); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 53bf08175..39471804b 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -14,7 +14,8 @@ type Row = (&'static [&'static str], Option<&'static str>, &'static [&'static st /// The Liquify tools. pub const LIQUIFY: &[&str] = &["warp", "twirl", "pucker", "bloat", "scallop", "crystallize", "wrinkle"]; -const SYMBOLISM: &[&str] = +/// The Symbolism tools. +pub const SYMBOLISM: &[&str] = &["symbolSprayer", "symbolShifter", "symbolScruncher", "symbolSizer", "symbolSpinner", "symbolStainer", "symbolScreener", "symbolStyler"]; const ROWS: &[Row] = &[ @@ -35,6 +36,27 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), (&["freeTransform"], None, &["constrain"]), (&["artboard"], None, &["moveArt", "scaleArt"]), + // Flare Tool Options (`extra::FLARE_OPTIONS` and the Rays and Rings checkboxes). + ( + &["flare"], + None, + &[ + "diameter", + "opacity", + "brightness", + "growth", + "fuzziness", + "raysOn", + "rays", + "longest", + "rayFuzziness", + "ringsOn", + "pathLength", + "rings", + "largest", + "direction", + ], + ), ]; /// The stores `tool`'s persistent options live in, each with the option keys it holds. diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index ec2d05072..b6ce4e0d5 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -1,5 +1,5 @@ -//! Artboard Options (double-click with the Artboard tool): the artboard's fields, sizes parsed -//! with units. +//! Artboard Options (double-click with the Artboard tool, or double-click the tool): the +//! artboard's fields, sizes parsed with units. use serde_json::{Value, json}; @@ -9,6 +9,25 @@ use crate::state::Dialog; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Artboard Options").into(), confirm, ..DialogSpec::FORM }; +/// The dialog kind of Artboard Options. +pub const KIND: &str = "artboardOptions"; + +/// Open Artboard Options for the active artboard: the Artboard tool's while it is in use, else the +/// window's. +pub fn open(app: &mut VectorcraftApp) -> Result { + let index = if app.session.tool_id() == "artboard" { + app.session.tool_options()["active"].as_u64().and_then(|i| usize::try_from(i).ok()).unwrap_or(0) + } else { + app.view().map_or(0, |v| v.artboard) + }; + let st = app.session.active().ok_or("no document")?; + let a = st.doc.artboards.get(index).ok_or("no artboard")?; + let r = a.rect; + let fields = json!({"index": index, "name": a.name, "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()}); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(json!({ "dialog": KIND })) +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut p = Value::Object(d.fields.clone()); for k in ["x", "y", "width", "height"] { diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 14cf1da6c..6924ee166 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -63,12 +63,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { label(ui, tl!("Corner:")); ui.vertical(|ui| { for k in CornerKind::ALL { - let name = match k { - CornerKind::Round => tl!("Round"), - CornerKind::InvertedRound => tl!("Inverted Round"), - CornerKind::Chamfer => tl!("Chamfer"), - }; - if widgets::radio(ui, name, Some(k) == current, true) { + if widgets::radio(ui, kind_label(k), Some(k) == current, true) { d.fields.insert("kind".into(), json!(k)); } } @@ -81,6 +76,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// A corner kind's name, in the UI language. +pub(crate) fn kind_label(k: CornerKind) -> &'static str { + match k { + CornerKind::Round => tl!("Round"), + CornerKind::InvertedRound => tl!("Inverted Round"), + CornerKind::Chamfer => tl!("Chamfer"), + } +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut p = json!({"id": d.fields.get("id"), "corners": d.fields.get("corners")}); if let Some(k) = d.fields.get("kind") { diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs new file mode 100644 index 000000000..44ae5eb58 --- /dev/null +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -0,0 +1,203 @@ +//! Flare Tool Options (double-click the Flare tool, or click with it): the options the Flare tool +//! keeps, which draw the next flare dragged out, last across tool switches and are saved with the +//! preferences. OK sets them with `tool.setOption {tool: "flare", values}`; opened by a click, it +//! then draws a flare there with them (`shape.flare`, on the active perspective plane while the +//! grid shows). +//! +//! Fields: the options (`vectorcraft_tools::extra::FLARE_OPTIONS`): `diameter` and `pathLength` +//! (points), `opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and +//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; and +//! `x`, `y` where a click opened it. + +use serde_json::{Map, Value, json}; +use vectorcraft_geom::Point; +use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; + +use super::document_setup::check; +use super::{DialogResult, DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Flare Tool Options. +pub const KIND: &str = "flareOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Flare Tool Options").into(), body, confirm, min_width: 440.0, ..DialogSpec::FORM }; + +/// Width of the label column and of the fields. +const LABEL_W: f32 = 78.0; +const FIELD_W: f32 = 90.0; + +/// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a +/// flare there on OK. +pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { + let mut fields = match app.session.tool_options_of("flare") { + Value::Object(o) => o, + _ => Map::new(), + }; + if let Some(p) = at { + fields.insert("x".into(), json!(p.x)); + fields.insert("y".into(), json!(p.y)); + } + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +/// A row for option `key`, kept within its range: a distance in `unit`, else a number. +fn field(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit, (key, label): (&str, &str)) { + let Some(&(_, default, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return }; + widgets::label_row(ui, label, LABEL_W, |ui| match key { + "diameter" | "pathLength" => { + if form::length(ui, d, key, unit, FIELD_W) { + let v = d.f64(key, default).clamp(lo, hi); + d.fields.insert(key.into(), json!(v)); + } + } + _ => { + let suffix = match key { + "rays" | "rings" => "", + "direction" => "°", + _ => "%", + }; + if let Some(v) = widgets::range_field(ui, ("flare", key), d.f64(key, default), lo..=hi, suffix, 0, FIELD_W) { + d.fields.insert(key.into(), json!(v)); + } + } + }); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + // Center and Halo, then Rays and Rings, side by side as two rows of groups. + egui::Grid::new("flare-groups").num_columns(2).spacing([28.0, 14.0]).show(ui, |ui| { + ui.vertical(|ui| { + widgets::subheader(ui, tl!("Center")); + for f in [("diameter", tl!("Diameter:")), ("opacity", tl!("Opacity:")), ("brightness", tl!("Brightness:"))] { + field(ui, d, unit, f); + } + }); + ui.vertical(|ui| { + widgets::subheader(ui, tl!("Halo")); + for f in [("growth", tl!("Growth:")), ("fuzziness", tl!("Fuzziness:"))] { + field(ui, d, unit, f); + } + }); + ui.end_row(); + ui.vertical(|ui| { + check(ui, d, "raysOn", tl!("Rays")); + let on = d.bool("raysOn"); + ui.add_enabled_ui(on, |ui| { + for f in [("rays", tl!("Number:")), ("longest", tl!("Longest:")), ("rayFuzziness", tl!("Fuzziness:"))] { + field(ui, d, unit, f); + } + }); + }); + ui.vertical(|ui| { + check(ui, d, "ringsOn", tl!("Rings")); + let on = d.bool("ringsOn"); + ui.add_enabled_ui(on, |ui| { + for f in [("pathLength", tl!("Path:")), ("rings", tl!("Number:")), ("largest", tl!("Largest:")), ("direction", tl!("Direction:"))] { + field(ui, d, unit, f); + } + }); + }); + ui.end_row(); + }); + false +} + +/// OK: set the tool's options; opened by a click, draw a flare there with them. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let mut values: Map = + FLARE_OPTIONS.iter().filter(|(k, ..)| d.fields.contains_key(*k)).map(|(k, default, ..)| (k.to_string(), json!(d.f64(k, *default)))).collect(); + for key in ["raysOn", "ringsOn"] { + values.insert(key.into(), json!(d.bool(key))); + } + let at = d.fields.get("x").and_then(Value::as_f64).zip(d.fields.get("y").and_then(Value::as_f64)).map(|(x, y)| Point::new(x, y)); + let options = run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values }))?; + let Some(at) = at else { return Ok(options) }; + let params = flare_params(&options, at); + match vectorcraft_engine::perspective_click(&app.session, "shape.flare", ¶ms, at) { + Some((id, p)) => app.run(&id, p), + None => app.run("shape.flare", params), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + use vectorcraft_engine::doc::NodeKind; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 600})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + /// The children of the newest flare (a group named Flare), by name. + fn flare_parts(app: &VectorcraftApp) -> Vec { + let doc = &app.session.doc().unwrap().doc; + let flare = doc.layers[0].children().unwrap().iter().rev().find(|n| n.name.as_deref() == Some("Flare")).expect("a flare"); + let NodeKind::Group { children, .. } = &flare.kind else { panic!("a flare is a group") }; + children.iter().filter_map(|c| c.name.clone()).collect() + } + + #[test] + fn the_toolbar_opens_the_options_and_ok_keeps_them_for_the_next_drag() { + let mut app = app(); + app.run("tool.options", json!({"tool": "flare"})).unwrap(); + let text = painted(&mut app); + for label in ["Flare Tool Options", "Center", "Diameter:", "Halo", "Growth:", "Rays", "Longest:", "Rings", "Path:", "Largest:", "Direction:"] + { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.f64("diameter", 0.0), d.f64("rays", 0.0), d.bool("raysOn"), d.f64("direction", 0.0)), (100.0, 15.0, true, 45.0)); + for (k, v) in [("rays", json!(4)), ("ringsOn", json!(false)), ("growth", json!(80))] { + d.fields.insert(k.into(), v); + } + let objects = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(objects(&app), 0, "OK from the toolbar draws nothing"); + let o = app.session.tool_options_of("flare"); + assert_eq!((o["rays"].as_u64(), o["ringsOn"].as_bool(), o["growth"].as_f64()), (Some(4), Some(false), Some(80.0))); + // A drag draws with them: four rays, no rings. + app.select_tool("flare"); + let view = app.view_info(); + for (kind, x, y) in [(PointerKind::Down, 200.0, 200.0), (PointerKind::Drag, 240.0, 200.0), (PointerKind::Up, 240.0, 200.0)] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, x, y), view); + } + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, 400.0, 400.0), view); + } + let parts = flare_parts(&app); + assert!(!parts.iter().any(|p| p == "Ring"), "{parts:?}"); + let doc = &app.session.doc().unwrap().doc; + let flare = doc.layers[0].children().unwrap().last().unwrap(); + let rays = flare.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Rays")).unwrap(); + assert_eq!(rays.path_data().unwrap().subpaths.len(), 4); + } + + #[test] + fn a_click_fills_in_the_options_and_draws_a_flare_there() { + let mut app = app(); + app.run("tool.setOption", json!({"tool": "flare", "values": {"rings": 3}})).unwrap(); + crate::dialogs::open_tool_dialog(&mut app, "flare", json!({"x": 300, "y": 300})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.f64("rings", 0.0), d.f64("x", 0.0)), (KIND, 3.0, 300.0)); + super::super::confirm(&mut app).unwrap(); + let parts = flare_parts(&app); + assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); + // Out-of-range values are kept within the option's range. + app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap(); + let o = app.session.tool_options_of("flare"); + assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); + } +} diff --git a/crates/ui-egui/src/dialogs/mod.rs b/crates/ui-egui/src/dialogs/mod.rs index b3d73eb82..1c62023e8 100644 --- a/crates/ui-egui/src/dialogs/mod.rs +++ b/crates/ui-egui/src/dialogs/mod.rs @@ -8,7 +8,7 @@ mod about; mod all_tools; -mod artboard_options; +pub mod artboard_options; pub mod blend_options; pub mod brush_options; pub mod color_balance; @@ -29,6 +29,7 @@ mod export_as; mod export_for_screens; pub mod eyedropper; pub mod file_info; +pub mod flare_options; pub mod flatten; pub mod flattener_presets; mod form; @@ -78,6 +79,7 @@ pub mod spot_colors; pub(crate) mod svg_options; pub mod swatch_conflict; pub mod swatch_options; +pub mod symbolism_options; mod text_export; pub mod text_import; mod tiff_bmp_tga; @@ -204,7 +206,7 @@ registry! { Transform: ["move", "rotate", "scale", "reflect", "shear"] => transform::SPEC, PathOp: ["average", "offsetPath", "simplify", "splitIntoGrid"] => path_ops::SPEC, DocumentSetup: ["documentSetup"] => document_setup::SPEC, - ArtboardOptions: ["artboardOptions"] => artboard_options::SPEC, + ArtboardOptions: [artboard_options::KIND] => artboard_options::SPEC, AllTools: ["allTools"] => all_tools::SPEC, ExportForScreens: ["exportForScreens"] => export_for_screens::SPEC, Recolor: [recolor::KIND] => recolor::SPEC, @@ -276,6 +278,8 @@ registry! { Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC, LiquifyOptions: [liquify::KIND] => liquify::SPEC, FreehandOptions: [freehand::KIND] => freehand::SPEC, + FlareOptions: [flare_options::KIND] => flare_options::SPEC, + SymbolismOptions: [symbolism_options::KIND] => symbolism_options::SPEC, PerspectiveGridPresets: [perspective_presets::KIND] => perspective_presets::SPEC, PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC, BlendOptions: [blend_options::KIND] => blend_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs new file mode 100644 index 000000000..33d902b90 --- /dev/null +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -0,0 +1,81 @@ +//! Symbolism Tools Options (double-click a Symbolism tool): the brush the eight tools share, which +//! lasts across tool switches and is saved with the preferences. OK sets it with +//! `tool.setOption {tool, values}`. +//! +//! Fields: `tool`; `diameter` (points), `intensity` and `density` (Symbol Set Density), 1–10. + +use serde_json::{Map, Value, json}; + +use super::{DialogResult, DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Symbolism Tools Options. +pub const KIND: &str = "symbolismOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +/// The options the dialog edits. +const KEYS: [&str; 3] = ["diameter", "intensity", "density"]; + +/// Width of the label column. +const LABEL_W: f32 = 130.0; + +/// Open the options of Symbolism tool `tool` (one of `vectorcraft_tools::settings::SYMBOLISM`) +/// with their current values. +pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { + let o = app.session.tool_options_of(tool); + let mut fields: Map = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + fields.insert("tool".into(), json!(tool)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + widgets::label_row(ui, tl!("Diameter:"), LABEL_W, |ui| { + form::length(ui, d, "diameter", unit, 100.0); + }); + for (key, label) in [("intensity", tl!("Intensity:")), ("density", tl!("Symbol Set Density:"))] { + widgets::label_row(ui, label, LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", key), d.f64(key, 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert(key.into(), json!(v)); + } + }); + } + false +} + +/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + #[test] + fn the_symbolism_tools_share_the_options_ok_sets() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + for label in ["Symbolism Tools Options", "Diameter:", "Intensity:", "Symbol Set Density:"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.str("tool"), d.f64("diameter", 0.0), d.f64("intensity", 0.0)), ("symbolSizer".to_string(), 80.0, 5.0)); + for (k, v) in [("diameter", json!(120)), ("intensity", json!(9)), ("density", json!(2))] { + d.fields.insert(k.into(), v); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + // The Sprayer has them too: one brush for the eight tools. + let o = app.session.tool_options_of("symbolSprayer"); + assert_eq!((o["diameter"].as_f64(), o["intensity"].as_f64(), o["density"].as_f64()), (Some(120.0), Some(9.0), Some(2.0))); + } +} diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 8ef0f807f..d62aef85f 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -26,12 +26,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { Ok(v) => Dialog::new("command", json!({"__command": "graph.setData", "__label": "Graph Data", "csv": v["csv"]})), Err(_) => return, }, - // Flare Tool Options (Center / Halo / Rays / Rings), applied through the generic command dialog. - "flare" => Dialog::new( - "command", - json!({"__command": "shape.flare", "__label": "Flare Tool Options", "cx": x, "cy": y, "diameter": 100, "opacity": 50, "brightness": 30, - "growth": 20, "fuzziness": 50, "rays": 15, "longest": 300, "rayFuzziness": 100, "pathLength": 300, "rings": 10, "largest": 50, "direction": 45}), - ), + // A Flare tool click: the Flare Tool Options, with the tool's values; OK draws a flare there. + "flare" => { + super::flare_options::open(app, Some(vectorcraft_geom::Point::new(x, y))); + return; + } "rotate" | "reflect" | "scale" | "shear" | "artboardOptions" => { let mut base = match kind { "rotate" => json!({"angle": 0}), diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a6eb613e4..759cad155 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -228,6 +228,8 @@ Auto-Collapse Iconic Panels Contraer automáticamente los paneles de iconos Ellipse Properties: Propiedades de la elipse: Invert Pie Invertir sector + Side Length: Longitud del lado: + Make Sides Equal Igualar los lados Pie End Angle: Ángulo final del sector: Pie Start Angle: Ángulo inicial del sector: Show Tool Group Labels Mostrar etiquetas de grupos de herramientas @@ -988,6 +990,20 @@ Flare Destello Flare Tool Herramienta Destello Flare Tool Options Opciones de la herramienta Destello + Halo Halo + Rays Rayos + Rings Anillos + Diameter: Diámetro: + Brightness: Brillo: + Growth: Crecimiento: + Fuzziness: Desenfoque: + Number: Número: + Longest: Más largo: + Path: Trazado: + Largest: Más grande: + Direction: Dirección: + Symbolism Tools Options Opciones de las herramientas de símbolos + Symbol Set Density: Densidad del conjunto de símbolos: Flat Image Imagen acoplada Flat Logo Logotipo plano Flatness: Lisura: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 77aaf6562..5e2d72419 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -229,6 +229,8 @@ Auto-Collapse Iconic Panels Réduire automatiquement les panneaux en icônes Ellipse Properties: Propriétés de l’ellipse : Invert Pie Inverser le secteur + Side Length: Longueur du côté : + Make Sides Equal Égaliser les côtés Pie End Angle: Angle de fin du secteur : Pie Start Angle: Angle de début du secteur : Show Tool Group Labels Afficher les libellés des groupes d'outils @@ -987,6 +989,20 @@ Flare Halo Flare Tool Outil Halo Flare Tool Options Options de l’outil Halo + Halo Halo + Rays Rayons + Rings Anneaux + Diameter: Diamètre : + Brightness: Luminosité : + Growth: Croissance : + Fuzziness: Flou : + Number: Nombre : + Longest: Le plus long : + Path: Tracé : + Largest: Le plus grand : + Direction: Direction : + Symbolism Tools Options Options des outils de symbole + Symbol Set Density: Densité du jeu de symboles : Flat Image Image aplatie Flat Logo Logo en aplats Flatness: Planéité : diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a1e421b79..9659a296d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -228,6 +228,8 @@ Auto-Collapse Iconic Panels Comprimi automaticamente i pannelli a icona Ellipse Properties: Proprietà dell’ellisse: Invert Pie Inverti settore + Side Length: Lunghezza del lato: + Make Sides Equal Rendi uguali i lati Pie End Angle: Angolo finale del settore: Pie Start Angle: Angolo iniziale del settore: Show Tool Group Labels Mostra etichette dei gruppi di strumenti @@ -987,6 +989,20 @@ Flare Riflesso Flare Tool Strumento Riflesso Flare Tool Options Opzioni strumento Riflesso + Halo Alone + Rays Raggi + Rings Anelli + Diameter: Diametro: + Brightness: Luminosità: + Growth: Crescita: + Fuzziness: Sfocatura: + Number: Numero: + Longest: Più lungo: + Path: Tracciato: + Largest: Più grande: + Direction: Direzione: + Symbolism Tools Options Opzioni strumenti simboli + Symbol Set Density: Densità del set di simboli: Flat Image Immagine appiattita Flat Logo Logo piatto Flatness: Planarità: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index affac77e5..6b8aa5aea 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -354,6 +354,8 @@ Fill & Stroke 塗りと線 Fill Color カラー (塗り) Invert Pie 扇形を反転 + Side Length: 辺の長さ: + Make Sides Equal 辺の長さをそろえる Opacity 不透明度 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: @@ -2857,6 +2859,20 @@ Fill: click for swatches, Shift-click for the color mixer 塗り: クリックでスウォッチ、Shift キーを押しながらクリックでカラーミキサー Fit in View 表示に合わせる Flare Tool Options フレアツールオプション + Halo ハロー + Rays 光線 + Rings リング + Diameter: 直径: + Brightness: 明るさ: + Growth: 拡大: + Fuzziness: ぼかし: + Number: 数: + Longest: 最長: + Path: パス: + Largest: 最大: + Direction: 方向: + Symbolism Tools Options シンボルツールオプション + Symbol Set Density: シンボルセットの密度: Flattener presets 分割・統合プリセット Focal Fill 焦点の塗り Focal Stroke 焦点の線 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 362bf1702..0fa94d41c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -226,6 +226,8 @@ Auto-Collapse Iconic Panels Автоматически сворачивать значки панелей Ellipse Properties: Свойства эллипса: Invert Pie Инвертировать сектор + Side Length: Длина стороны: + Make Sides Equal Выровнять стороны Pie End Angle: Конечный угол сектора: Pie Start Angle: Начальный угол сектора: Show Tool Group Labels Показывать названия групп инструментов @@ -985,6 +987,20 @@ Flare Блик Flare Tool Инструмент «Блик» Flare Tool Options Параметры инструмента «Блик» + Halo Ореол + Rays Лучи + Rings Кольца + Diameter: Диаметр: + Brightness: Яркость: + Growth: Рост: + Fuzziness: Размытие: + Number: Количество: + Longest: Самый длинный: + Path: Контур: + Largest: Самое большое: + Direction: Направление: + Symbolism Tools Options Параметры инструментов символов + Symbol Set Density: Плотность набора символов: Flat Image Плоское изображение Flat Logo Плоский логотип Flatness: Плоскостность: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 28722a1e9..c2d43030b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -222,6 +222,8 @@ Auto-Collapse Iconic Panels Автоматично згортати значки панелей Ellipse Properties: Властивості еліпса: Invert Pie Інвертувати сектор + Side Length: Довжина сторони: + Make Sides Equal Вирівняти сторони Pie End Angle: Кінцевий кут сектора: Pie Start Angle: Початковий кут сектора: Show Tool Group Labels Показувати назви груп інструментів @@ -981,6 +983,20 @@ Flare Відблиск Flare Tool Інструмент «Відблиск» Flare Tool Options Параметри інструменту «Відблиск» + Halo Ореол + Rays Промені + Rings Кільця + Diameter: Діаметр: + Brightness: Яскравість: + Growth: Зростання: + Fuzziness: Розмиття: + Number: Кількість: + Longest: Найдовший: + Path: Контур: + Largest: Найбільше: + Direction: Напрямок: + Symbolism Tools Options Параметри інструментів символів + Symbol Set Density: Щільність набору символів: Flat Image Плоске зображення Flat Logo Плоский логотип Flatness: Площинність: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a6e65d5fc..5b7889a36 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -211,6 +211,8 @@ Auto-Collapse Iconic Panels 自动折叠图标面板 Ellipse Properties: 椭圆属性: Invert Pie 反转扇形 + Side Length: 边长: + Make Sides Equal 使各边等长 Pie End Angle: 扇形终止角度: Pie Start Angle: 扇形起始角度: Show Tool Group Labels 显示工具组标签 @@ -965,6 +967,20 @@ Flare 光晕 Flare Tool 光晕工具 Flare Tool Options 光晕工具选项 + Halo 光晕 + Rays 射线 + Rings 光环 + Diameter: 直径: + Brightness: 亮度: + Growth: 增大: + Fuzziness: 模糊度: + Number: 数量: + Longest: 最长: + Path: 路径: + Largest: 最大: + Direction: 方向: + Symbolism Tools Options 符号工具选项 + Symbol Set Density: 符号组密度: Flat Image 平面图像 Flatness: 平滑度: Flatten Transparency 拼合透明度 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6892797f2..28d987a7d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -222,6 +222,8 @@ Auto-Collapse Iconic Panels 自動收合圖示面板 Ellipse Properties: 橢圓屬性: Invert Pie 反轉扇形 + Side Length: 邊長: + Make Sides Equal 使各邊等長 Pie End Angle: 扇形終止角度: Pie Start Angle: 扇形起始角度: Show Tool Group Labels 顯示工具組標籤 @@ -988,6 +990,20 @@ Flare 光暈 Flare Tool 光暈工具 Flare Tool Options 光暈工具選項 + Halo 光暈 + Rays 射線 + Rings 光環 + Diameter: 直徑: + Brightness: 亮度: + Growth: 增大: + Fuzziness: 模糊度: + Number: 數量: + Longest: 最長: + Path: 路徑: + Largest: 最大: + Direction: 方向: + Symbolism Tools Options 符號工具選項 + Symbol Set Density: 符號組密度: Flat Image 平面影像 Flatness: 平滑度: Flatten Artwork 將圖稿平面化 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index c9fa48cdc..368c4f517 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -353,7 +353,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient → the Gradient panel (window.panel), eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, closeWithin and editWithin (px, 0 is off), size (pt); OK runs tool.setOption {tool, values})", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height; OK runs artboard.setProps), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x and y, draws one there with them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, closeWithin and editWithin (px, 0 is off), size (pt); OK runs tool.setOption {tool, values})", ), ( "ui.colorGuideOptions", @@ -2964,6 +2964,14 @@ fn to_field(ctx: &egui::Context, field: egui::Id, e: egui::Event) { } /// Invoke a menu/command id with UI side effects (dialogs for "…" commands that need input). +/// Object › Graph › Type… or Data… (`id`): its dialog, with the selected graph's current values +/// (the command's query). +pub(crate) fn graph_dialog(app: &mut VectorcraftApp, id: &str) -> Result { + let v = app.session.execute(id, &json!({})).map_err(|e| e.to_string())?; + let (label, fields) = if id == "graph.setData" { ("Graph Data", json!({"csv": v["csv"]})) } else { ("Graph Type", v) }; + app.run("ui.paramDialog", json!({"command": id, "label": label, "params": fields})).map(|_| json!({ "dialog": "command" })) +} + pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { if waits_for_ime(app, id) { return; @@ -3007,12 +3015,8 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } // Object → Graph → Type… / Data…: dialogs with the selected graph's current values. if matches!(id, "graph.setType" | "graph.setData") && p.as_object().is_none_or(|o| o.is_empty()) { - match app.session.execute(id, &json!({})) { - Ok(v) => { - let (label, fields) = if id == "graph.setData" { ("Graph Data", json!({"csv": v["csv"]})) } else { ("Graph Type", v) }; - let _ = app.run("ui.paramDialog", json!({"command": id, "label": label, "params": fields})); - } - Err(e) => app.status(e.to_string()), + if let Err(e) = graph_dialog(app, id) { + app.status(e); } return; } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index facb4162d..87df16d8e 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -48,6 +48,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{LiveCorners, Node, StrokeLayer}; use vectorcraft_engine::inspect::StrokeMixed; +use vectorcraft_geom::shapes::CornerKind; use crate::theme::Tokens; use crate::widgets::{Live, dim_label}; @@ -61,13 +62,15 @@ pub fn first_selected(app: &VectorcraftApp) -> Option { /// The radius the Live Corners of path `n` show in the panels: that of the corners the panels set /// (the Direct-Selected ones, else every corner), blank when they differ. pub(crate) fn corner_radius(app: &VectorcraftApp, n: &Node) -> Option { + corner_style(app, n).0 +} + +/// The radius and kind of the corners [`corner_radius`] reads, each None when they differ. +pub(crate) fn corner_style(app: &VectorcraftApp, n: &Node) -> (Option, Option) { let partial = app.session.active().and_then(|d| d.selection.partial(n.id)); - let corners = LiveCorners::of(n)?; - corners.style(&corners.picked(partial)).0 + LiveCorners::of(n).map_or((None, None), |c| c.style(&c.picked(partial))) } -/// The Corner Radius field of a live rectangle's or polygon's properties: [`corner_radius`], -/// which a new value sets on those corners. /// The width of a panel's number fields: the Transform fields', two to a row beside the reference /// point, their labels and the W/H link, so every field in the panel is as wide (#696). Measured /// from the full row, before its widgets. @@ -77,17 +80,23 @@ pub(crate) fn field_width(ui: &Ui) -> f32 { ((ui.available_width() - AROUND) / 2.0).clamp(60.0, 110.0) } +/// The Corner Radius field of a live rectangle's properties: [`corner_radius`], which a new value +/// sets on those corners. pub(crate) fn corner_radius_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str) { - let units = app.session.general_unit(); let fw = field_width(ui); ui.horizontal(|ui| { dim_label(ui, tl!("Corner Radius:")); - if let Some(r) = crate::widgets::num_field(ui, id, corner_radius(app, n), units, fw) { - app.run("object.setLiveShape", json!({"radius": r})).ok(); - } + corner_radius_field(app, ui, n, id, fw); }); } +/// [`corner_radius_row`]'s field, `width` wide. +pub(crate) fn corner_radius_field(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: impl std::hash::Hash + std::fmt::Debug, width: f32) { + if let Some(r) = crate::widgets::num_field(ui, id, corner_radius(app, n), app.session.general_unit(), width) { + app.run("object.setLiveShape", json!({"radius": r})).ok(); + } +} + /// Number of selected objects. pub(crate) fn selection_len(app: &VectorcraftApp) -> usize { app.session.active().map(|d| d.selection.len()).unwrap_or(0) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index e69a1d829..ef8f32a99 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -447,16 +447,7 @@ pub fn transform_section(app: &mut VectorcraftApp, ui: &mut Ui) { { match live { vectorcraft_doc::LiveShape::Rectangle { .. } => corner_radius_row(app, ui, &n, "radius"), - vectorcraft_doc::LiveShape::Polygon { sides, .. } => { - let fw = super::field_width(ui); - ui.horizontal(|ui| { - dim_label(ui, tl!("Sides:")); - if let Some(s) = widgets::plain_field(ui, "sides", *sides as f64, "", 0, fw) { - app.run("object.setLiveShape", json!({"sides": s as u32})).ok(); - } - }); - corner_radius_row(app, ui, &n, "radius"); - } + vectorcraft_doc::LiveShape::Polygon { .. } => super::transform::polygon_rows(app, ui, &n, live, "props-polygon"), vectorcraft_doc::LiveShape::Ellipse { pie, .. } => super::transform::pie_rows(app, ui, *pie, "props-pie"), _ => {} } diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index bd3a24d5d..73c8c1eac 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -4,10 +4,12 @@ use egui::Ui; use serde_json::json; -use vectorcraft_doc::NodeKind; +use vectorcraft_doc::{LiveShape, Node, NodeKind}; use vectorcraft_geom::Rect; +use vectorcraft_geom::shapes::CornerKind; use super::{corner_radius_row, first_selected, pstate, set_pstate}; +use crate::dialogs::corners::kind_label as corner_kind; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; use crate::{VectorcraftApp, icons}; @@ -182,15 +184,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { widgets::subheader(ui, tl!("Rectangle Properties:")); corner_radius_row(app, ui, &n, "xfp-radius"); } - vectorcraft_doc::LiveShape::Polygon { sides, .. } => { + vectorcraft_doc::LiveShape::Polygon { .. } => { widgets::subheader(ui, tl!("Polygon Properties:")); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Sides:")); - if let Some(s) = widgets::plain_field(ui, "xfp-sides", *sides as f64, "", 0, 60.0) { - app.run("object.setLiveShape", json!({"sides": s.clamp(3.0, 20.0) as u32})).ok(); - } - }); - corner_radius_row(app, ui, &n, "xfp-radius"); + polygon_rows(app, ui, &n, live, "xfp-polygon"); } vectorcraft_doc::LiveShape::Ellipse { pie, .. } => { widgets::subheader(ui, tl!("Ellipse Properties:")); @@ -231,6 +227,56 @@ pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), i } } +/// A live polygon's Polygon Properties (Transform and Properties panels): its side count, angle +/// (counterclockwise), corner type and radius, radius (centre to vertex) and side length, and Make +/// Sides Equal, which an uneven scale enables. +pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str) { + let LiveShape::Polygon { sides, .. } = live else { return }; + let (units, fw) = (app.session.general_unit(), super::field_width(ui)); + let radius = live.polygon_radius(); + let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin()); + let kind = super::corner_style(app, n).1; + let kinds: Vec<&str> = CornerKind::ALL.iter().map(|k| corner_kind(*k)).collect(); + // The `object.setLiveShape` param an edited field sets. + let mut set = None; + egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + widgets::dim_label(ui, tl!("Sides:")); + if let Some(s) = widgets::plain_field(ui, (id, "sides"), f64::from(*sides), "", 0, fw) { + set = Some(("sides", json!(s.round().max(3.0) as u64))); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Angle:")); + if let Some(a) = widgets::plain_field(ui, (id, "angle"), live.polygon_angle().unwrap_or(0.0), "°", 1, fw) { + set = Some(("polygonAngle", json!(a))); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Corner:")); + if let Some(k) = widgets::dropdown_names(ui, (id, "kind"), kind.map_or("", corner_kind), &kinds, fw).and_then(|i| CornerKind::ALL.get(i)) { + set = Some(("kind", json!(k))); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Corner Radius:")); + super::corner_radius_field(app, ui, n, (id, "cornerRadius"), fw); + ui.end_row(); + widgets::dim_label(ui, tl!("Radius:")); + if let Some(r) = widgets::num_field(ui, (id, "radius"), radius, units, fw) { + set = Some(("polygonRadius", json!(r))); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Side Length:")); + if let Some(l) = widgets::num_field(ui, (id, "side"), side, units, fw) { + set = Some(("sideLength", json!(l))); + } + ui.end_row(); + }); + if ui.add_enabled_ui(!live.polygon_sides_equal(), |ui| widgets::flat_button(ui, tl!("Make Sides Equal"), 130.0)).inner.clicked() { + set = Some(("makeSidesEqual", json!(true))); + } + if let Some((key, v)) = set { + app.run("object.setLiveShape", json!({ key: v })).ok(); + } +} + /// The Control bar's underlined "Transform" link: a click toggles the Transform panel in a /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -335,6 +381,31 @@ mod tests { assert!(shown.iter().any(|t| t == "0°") && !shown.iter().any(|t| t == "100 pt"), "{shown:?}"); } + /// #812: a selected live polygon shows its Polygon Properties in the Transform panel and the + /// Properties panel's Transform section, and Make Sides Equal evens it out after a stretch. + #[test] + fn a_polygon_shows_its_polygon_properties() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 50, "sides": 6})).unwrap(); + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let shown = texts(&mut app, draw); + // A hexagon's side is as long as its radius. + for t in ["Sides:", "6", "Angle:", "0°", "Corner:", "Round", "Corner Radius:", "Radius:", "Side Length:", "50 pt", "Make Sides Equal"] { + assert!(shown.iter().any(|s| s == t), "{t} in {shown:?}"); + } + } + assert!(texts(&mut app, show).iter().any(|s| s == "Polygon Properties:")); + app.run("object.scale", json!({"sx": 200, "sy": 100})).unwrap(); + let live = |app: &VectorcraftApp| match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => l.clone(), + k => panic!("{k:?}"), + }; + assert!(!live(&app).polygon_sides_equal()); + app.run("object.setLiveShape", json!({"makeSidesEqual": true})).unwrap(); + assert!(live(&app).polygon_sides_equal()); + } + #[test] fn the_artboard_tool_shows_the_active_artboard() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e8cfe8c32..54a667904 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -312,8 +312,10 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Ok(json!({ "open": "gradient" })), - "gradient" => app.run("window.panel", json!({ "panel": "gradient" })), + // The Gradient and Magic Wand tools: their panels. + "gradient" | "magicWand" if app.ui.open_panel.as_deref() == Some(tool) => Ok(json!({ "open": tool })), + "gradient" | "magicWand" => app.run("window.panel", json!({ "panel": tool })), + "artboard" => crate::dialogs::artboard_options::open(app), "eyedropper" => { crate::dialogs::eyedropper::open(app); Ok(json!({ "dialog": crate::dialogs::eyedropper::KIND })) @@ -326,12 +328,18 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Ok(crate::dialogs::flare_options::open(app, None)), // A double click on the Print Tiling tool puts the pages back where the placement puts them. "printTiling" => app.run("print.tiling.set", json!({ "reset": true })), // The Liquify tools: their Tool Options (the Global Brush Dimensions and the tool's own). _ if vectorcraft_tools::settings::LIQUIFY.contains(&tool) => crate::dialogs::liquify::open(app, tool), // The freehand tools: their Tool Options (Fidelity, fill, the tolerances, the brush size). _ if crate::dialogs::freehand::TOOLS.contains(&tool) => crate::dialogs::freehand::open(app, tool), + // The Symbolism tools: the brush they share. + _ if vectorcraft_tools::settings::SYMBOLISM.contains(&tool) => Ok(crate::dialogs::symbolism_options::open(app, tool)), + // The graph tools: Graph Type for the selected graph. + _ if vectorcraft_tools::extra::is_graph_tool(tool) => crate::menus::graph_dialog(app, "graph.setType"), _ if vectorcraft_tools::tool_info(tool).is_none() => Err(format!("unknown tool `{tool}`")), _ => Err(format!("the {tool} tool has no options")), } @@ -815,6 +823,38 @@ pub(crate) mod tests { assert_eq!(frame_in(&mut app, &ctx, 8.0, vec![], 500.0)[0], tools[0]); } + /// #812: double-clicking the Artboard tool opens Artboard Options of the active artboard, a + /// graph tool Graph Type for the selected graph, and the Magic Wand tool its panel. + #[test] + fn more_tools_open_their_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + // Without the Artboard tool, the window's artboard. + assert_eq!(open_options(&mut app, "artboard").unwrap()["dialog"], "artboardOptions"); + let d = app.ui.dialog.take().unwrap(); + assert_eq!((d.f64("index", 9.0), d.f64("width", 0.0), d.str("name")), (0.0, 300.0, "Artboard 1".to_string())); + // With it, its active artboard. + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + app.run("tool.select", json!({"tool": "artboard"})).unwrap(); + app.run("tool.setOption", json!({"key": "active", "value": 1})).unwrap(); + open_options(&mut app, "artboard").unwrap(); + let d = app.ui.dialog.take().unwrap(); + assert_eq!((d.f64("index", 9.0), d.f64("x", 0.0), d.f64("width", 0.0)), (1.0, 400.0, 100.0)); + // Graph Type needs a selected graph. + app.run("select.set", json!({"ids": []})).unwrap(); + assert!(open_options(&mut app, "pieGraph").is_err()); + assert!(app.ui.dialog.is_none()); + app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150})).unwrap(); + assert_eq!(open_options(&mut app, "pieGraph").unwrap()["dialog"], "command"); + let d = app.ui.dialog.take().unwrap(); + assert_eq!((d.str("__command"), d.str("type")), ("graph.setType".to_string(), "column".to_string())); + // The Magic Wand panel opens, and stays open on a second double-click. + open_options(&mut app, "magicWand").unwrap(); + assert_eq!(app.ui.open_panel.as_deref(), Some("magicWand")); + assert_eq!(open_options(&mut app, "magicWand").unwrap()["open"], "magicWand"); + assert_eq!(app.ui.open_panel.as_deref(), Some("magicWand")); + } + /// A double-click at `at`, `time` seconds in (a second apart from the last). fn double_click(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, at: Pos2) { let b = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; diff --git a/docs/mcp.md b/docs/mcp.md index 09e8d3562..289cebdc5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1340,6 +1340,19 @@ dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"radius":5}}} ``` +The same command sets the rest of a live shape's properties, as the Properties and Transform panels show them. A +polygon (Polygon Properties): `sides` (3–1000), `polygonAngle` (degrees counterclockwise, its first vertex straight up +at 0), `polygonRadius` (pt, centre to vertex), `sideLength` (pt, which sets the radius) and `makeSidesEqual: true`, +which drops an uneven scale or shear (its sides then differ) and keeps its centre, angle and mean radius; a radius or +length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees +counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. Each call is +one undo step. + +```json +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"sides":8,"polygonAngle":22.5,"sideLength":40}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"makeSidesEqual":true}}} +``` + ## Use Preview Bounds With the preference `usePreviewBounds` on (`prefs.set {key: "usePreviewBounds", value: true}`; also the Align panel @@ -2672,13 +2685,28 @@ active tool, `tool` names another one, and `{}` just reads them; the result is t tool keeps last across tool switches (and documents) and are saved with the preferences (`toolSettings` in `prefs.get`'s full object), as the reference app keeps them: the Liquify tools' brush and tool options, Mirror & Cut's axis and side, Puppet Warp's mesh, the Symbolism brush, the line, grid, pencil, brush and eraser tools' options, -polygon sides and star points. The Liquify tools share one set of Global Brush Dimensions (width, height, angle, +polygon sides and star points, and the Flare Tool Options. The Liquify tools share one set of Global Brush Dimensions (width, height, angle, intensity), and the Symbolism tools one brush. Interaction state (pins, a reference point) starts afresh. ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} ``` +`tool.options {tool}` opens what double-clicking the tool's button opens (its params doc lists every tool), in the +desktop app. The Flare tool's are its Flare Tool Options (dialog `flareOptions`): `diameter` and `pathLength` (pt), +`opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and `largest` (%), `rays`, `rings`, +`direction` (°), and `raysOn` and `ringsOn` (the Rays and Rings checkboxes; off, the flare has none). OK keeps them +(`tool.setOption {tool: "flare", values}`) and the next flare dragged out uses them; a click with the tool opens the +same dialog, and its OK also draws a flare there. The Artboard tool's are the active artboard's Artboard Options +(dialog `artboardOptions`; the Artboard tool's active artboard while it is in use, else the window's), a graph tool's +the selected graph's Graph Type (an error without one), a Symbolism tool's the Symbolism Tools Options (dialog +`symbolismOptions`: `diameter` in points, `intensity` and `density` 1–10, one brush for the eight tools) and the +Magic Wand tool's its panel. + +```json +{"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"flare","values":{"rays":24,"ringsOn":false}}}} +``` + ## Perspective grid The grid is document data (`perspective.grid.set` edits the model directly). `perspective.grid.get` reads it: