Compare commits

...
Author SHA1 Message Date
bflatastic 55cc14e4a8 Merge #687: Rearrange All Artboards layouts, order and one click
# Conflicts:
#	ROADMAP.md
2026-10-09 12:28:10 +07:00
BFlat dce0f8a48d Merge pull request #688 from storytold/fix/673-tab-close-side
Part of #673: a document tab's close box sits where the platform puts it
2026-10-09 12:27:41 +07:00
bflatasticandClaude Opus 5.5 6a39ee0a1c Part of #673: a document tab's close box sits where the platform puts it
Document tabs drew their close box before the title on every platform, the
macOS convention. On Windows, Linux and the web it now comes after the title,
as those platforms' tabs (and Adobe's own apps there) put it; macOS keeps it
before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:24:25 +07:00
bflatasticandClaude Opus 5.5 01df2c730b Fix #681: Rearrange All Artboards layouts, order and one-click access
- artboard.rearrange takes layout (gridByRow, gridByColumn, row, column;
  byColumn stays as an alias of gridByColumn) and order (leftToRight,
  rightToLeft); Columns is the row count of a grid by column and is
  ignored by row and column. It returns {artboards, rows, columns}.
- A Rearrange All Artboards dialog: Layout and Layout Order toggles drawn
  in code (widgets::layout_button, previewing the order), Columns/Rows,
  Spacing, Move Artwork with Artboard and the artboard count.
- One click: Rearrange All in the Properties panel (Document section with
  several artboards, Edit Artboards' Quick Actions); the Artboards panel's
  Rearrange button and menu item now open the dialog too.
- Tests for every layout x order (artboards, art riding along, one undo
  step), the dialog, the Properties button; the command sweep covers the
  new params. Translations for ja, es, it, ru, fr, zh-hans, zh-hant and
  pt-br; ROADMAP updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:22:48 +07:00
BFlat dcc0de7487 Merge pull request #686 from storytold/fix/663-canvas-greys
Part of #663: Canvas Color offers light, medium and dark grey
2026-10-09 12:20:42 +07:00
bflatasticandClaude Opus 5.5 0924bc16ae Part of #663: Canvas Color offers light, medium and dark grey
Preferences > User Interface > Canvas Color offered Match User Interface
Brightness and White only: with a dark interface the first is a high-contrast
dark canvas around the white page, and White hides where the page ends. Light
Gray, Medium Gray and Dark Gray keep the page's edge in view at a gentler
contrast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:14:33 +07:00
BFlat f18cd1c99b Merge pull request #685 from storytold/fix/683-fonts-folder
Fix #683: Preferences › Type › Additional Fonts Folder
2026-10-09 12:11:11 +07:00
bflatasticandClaude Opus 5.5 e92bbdbdac Fix #683: Preferences > Type > Additional Fonts Folder
VectorCraft found fonts only in the system's font folders (and, on Windows,
those font services activate). A new preference names one more folder, read
with its subfolders after the platform's: its fonts are listed in the font
menus and used as if installed, without installing them.

- vectorcraft_text::set_user_font_dirs / user_font_dirs: folders
  system_font_dirs adds to every scan (none on wasm).
- prefs fontsFolder (Type > Options > Additional Fonts Folder), trimmed; when
  it changes after the first scan, the fonts are scanned again at once, so the
  folder's fonts appear (or go) and type in them lays out again.
- The label is translated where Additional Plug-ins Folder is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:05:16 +07:00
BFlat b61089e5c6 Merge pull request #684 from storytold/pr/land-fastmikey
Land #674, #676, #677, #678, #679: raster resolution, Crop Image trim, CMYK TIFF alpha, masked CMYK PDF images, direct ICC CMYK to RGB
2026-10-09 11:56:43 +07:00
bflatasticandClaude Opus 5.5 7bd496b1e2 Images: the web app keeps the decoder's 512 MB limit
#677 lets one image decode take up to 2 GB, so large print sheets open on the
desktop. wasm32 can address only 4 GB and aborts when an allocation fails, so
the web app keeps the decoder's default 512 MB and reports larger images as an
error instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:43:59 +07:00
bflatastic 2b91d7effd Merge #679 2026-10-09 11:43:42 +07:00
bflatastic b062d625cf Merge #678 2026-10-09 11:43:42 +07:00
bflatastic ee7be83ee0 Merge #677 2026-10-09 11:43:41 +07:00
bflatastic 50bb3b2693 Merge #676 2026-10-09 11:43:41 +07:00
bflatastic 2f81b4437b Merge #674 2026-10-09 11:43:40 +07:00
BFlat 23b7c68d90 Merge pull request #680 from storytold/fix/671-artboard-orientation
Fix #671: Edit Artboards' Properties picks a size preset and flips the orientation
2026-10-09 11:42:03 +07:00
bflatasticandClaude Opus 5.5 4176c0f297 Fix #671: Edit Artboards' Properties picks a size preset and flips the orientation
With the Artboard tool, the Properties panel showed the active artboard's name,
position and size but no quick way to turn it between portrait and landscape.
It now has a row with:
- Preset: New Document's saved and built-in presets, by category, matched in
  either orientation (Custom when none matches); choosing one sizes the
  artboard in its current orientation;
- Portrait and Landscape (the New Document toggle): the other one swaps the
  artboard's width and height.
The artboard's top-left corner stays put, so no art moves with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:37:05 +07:00
BFlat 349668a1e6 Merge pull request #672 from storytold/pr/land-394
Land #664, #669: Animated Zoom, Large Tabs, Scale Cursor, anti-aliased bitmaps, Spacing Guides (part of #394)
2026-10-09 11:32:46 +07:00
bflatasticandClaude Opus 5.5 ea07805fdf ROADMAP: Spacing Guides wired (#669) beside #664's preferences
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:26:01 +07:00
bflatastic e29e558810 Merge fix/394-spacing-guides
# Conflicts:
#	ROADMAP.md
2026-10-09 11:25:41 +07:00
bflatastic cc627c75e3 Merge fix/394-prefs-batch
# Conflicts:
#	ROADMAP.md
2026-10-09 11:25:38 +07:00
BFlat 5f4e03f3b3 Merge pull request #670 from storytold/fix/661-touch-bar-quit-int
Fix #661: quitting no longer crashes on Macs with a Touch Bar
2026-10-09 11:24:59 +07:00
fastmikey99andClaude Opus 5.5 f767403673 Crop Image: trim an image to its pixels that aren't fully transparent
object.cropImage {trim: true} cuts the selected image to the box of its pixels
with any alpha, copying them as they are (no re-render, no resampling) and
placing them where they were. An image with nothing to cut is left as it is
and isn't an error (trimmed: false), so a script can trim every image it
opens. Print-ready PNGs usually carry transparent padding; with this, Fit to
Artwork Bounds can size to the art.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:24:04 +13:00
bflatasticandClaude Opus 5.5 90d6785eb5 Part of #394: Animated Zoom, Large Tabs, Scale Cursor and anti-aliased bitmaps act
- Performance › Animated Zoom (with GPU Performance, which dims it when
  off): the Zoom tool dragged sideways zooms about the press (right in,
  left out) and held still zooms on (Alt: out); a click still steps. Off,
  a drag zooms to the area dragged across, now drawn as a marquee. The
  hint bar says which.
- User Interface › Large Tabs: taller document tabs with larger titles.
- User Interface › Scale Cursor Proportional to UI: off, the tool cursors
  keep their size whatever the UI Scaling (OS and painted cursors alike).
- File Handling › Display Bitmaps as Anti-aliased Images in Pixel
  Preview: off (the default), Pixel Preview samples images nearest-pixel
  (`RenderOptions::smooth_images`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:22:43 +07:00
bflatasticandClaude Opus 5.5 1575b14294 Part of #394: Smart Guides › Spacing Guides space a moved selection evenly
A selection moved with the Selection or Direct Selection tool 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, within the snapping tolerance; the equal gaps are marked
with a line and end ticks in the Smart Guides colour. The objects are
taken as wholes on their layers (groups too), and inside a group holding
the selection, its other objects. Off, moves only line up as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:22:22 +07:00
bflatasticandClaude Opus 5.5 f17bac2c64 Fix #661: quitting no longer crashes on Macs with a Touch Bar
On every quit (Cmd+Q, VectorCraft > Quit, the close button) on a MacBook Pro
with a Touch Bar, AppKit threw from -[_NSTouchBarFinderObservation invalidate]
and macOS reported a crash. AccessKit's macOS adapter subclasses the window's
content view and gives it back its own class when the window is torn down;
AppKit's Touch Bar support observes the view under the subclass, so removing
that observation throws (the same cause Zed fixed in zed-industries/zed#65186).

On macOS with accessibility, the app now ends the process at the end of
on_exit, once the preferences are saved, before eframe tears the window down.
Nothing after the window is needed on a normal quit. While the window is still
starting up it doesn't, so a graphics failure still starts the app again on
another adapter (#651).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:20:40 +07:00
BFlat 01ad745e86 Merge pull request #668 from storytold/fix/663-recent-and-preset-dblclick
Part of #663: Home screen Recent Files; a double-clicked preset creates the document
2026-10-09 11:20:12 +07:00
bflatasticandClaude Opus 5.5 d8f6bacddb Part of #663: Home screen Recent Files; a double-clicked preset creates the document
- The Home screen lists the first six of File > Open Recent Files, each by name
  (a click opens it) and folder; one that can't be opened says so in the status
  bar. With none, there is no section.
- In New Document, a double-click on a preset card creates the document from
  it; a click still only chooses it. The Create buttons no longer overwrite a
  create asked for earlier in the frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:17:35 +07:00
fastmikey99andClaude Opus 5.5 2cdf4e3de0 Colour: ICC CMYK converts straight into the RGB profile, with black-point compensation
CMYK went to RGB through display sRGB: CMYK -> sRGB (clamped) -> working RGB.
Into a wider space (Wide Gamut RGB, the 1998 primaries) that clipped every
colour sRGB can't hold - CMYK cyan's red channel landed at 99 instead of 0 -
and the black-point compensation setting had no effect (moxcms leaves it
unimplemented). An ICC CMYK profile now converts directly into the RGB
profile: into its primaries with linear curves, where compensation is a
linear remap from the profile's black (found by sending black through the
profile and reading it back), then onto its own curves. The canvas uses the
same conversion into sRGB, so what shows is what an RGB export writes.

Checked against Ghostscript with the same profiles (relative colorimetric,
compensation on and off): exports into Wide Gamut RGB and the sRGB display
agree within 1 level in 255. The built-in CMYK spaces are unchanged (Generic
CMYK compensates in its own model).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:11:34 +13:00
fastmikey99andClaude Opus 5.5 088495ee17 PDF import: masked CMYK images stay CMYK, their mask an opacity mask
A CMYK image with an /SMask, /Mask or colour key was handed to the
interpreter and stored as an RGB PNG, converted with hayro's own bundled
profile (Perceptual) rather than the working CMYK, so it showed 10-30 levels
lighter than other CMYK images and lost its ink amounts. It now keeps its
inks as other CMYK images do (#320), and its alpha becomes a greyscale
opacity mask. PDF export already writes that as a DeviceCMYK image under a
soft mask, so a round trip keeps the inks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:11:34 +13:00
fastmikey99andClaude Opus 5.5 43db1cdbbf Open CMYK TIFFs with an alpha channel, and rasters past 512 MB
The image decoder can't read a CMYK TIFF with an alpha channel at all
("color type Unknown(0)"); it is now read with the tiff crate, associated
alpha divided back out and the inks converted in the active colour settings.
And a 60 in sheet at 300 ppi (18000 x 6600 px) hit the decoder's 512 MB
default allocation limit; up to 2 GB is now allowed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:11:08 +13:00
fastmikey99andClaude Opus 5.5 ed17166343 Open raster images at the size their resolution declares
An image opened as a document took 1 px = 1 pt whatever its pHYs, JFIF or
EXIF resolution said, so a 300 ppi print file opened at four times its
physical size. It now opens the way Place already sizes it (pt_per_px):
at the resolution it declares, 72 ppi when it declares none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:11:07 +13:00
BFlat fc74389b5a Merge pull request #660 from Haven-King/fix/text-engine-integration
Fix/text engine integration
2026-10-09 10:45:11 +07:00
BFlat 0891ffbf51 Merge pull request #659 from storytold/fix/449-two-finger-pan
Part of #449: two fingers dragged on a touch screen pan the canvas
2026-10-09 10:37:26 +07:00
bflatasticandClaude Opus 5.5 861a0759b0 Part of #449: two fingers dragged on a touch screen pan the canvas
A pinch already zoomed the canvas and a second finger already cancelled the
first finger's press, but dragging two fingers together did nothing: the
canvas only read wheel scrolls, and a touch screen sends touches. The fingers'
movement (egui's multi-touch translation) now scrolls the canvas under either
Zoom with Mouse Wheel setting, and zoom and scroll apply in the same frame, so
a pinch that also slides pans too. Trackpads send scrolls, so nothing counts
twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:34:22 +07:00
haven 992f6a0a4d M7: tests for the text engine features combined
Layout (vectorcraft-text tests_combos): every pair of ligatures under tracking,
the paragraph composer, vertical alignment, Shrink Text to Fit, per-paragraph
attributes and inline graphics, and all six at once. Commands
(vectorcraft-engine tests_textcombos): Auto Size and Shrink Text with inline
art, paragraphs, composer and alignment; editing and undo across them; a save
round trip with everything on.
2026-10-08 20:30:14 -07:00
haven 53e39884fc M7: Auto Size measures vertically aligned area type from the top
auto_height lays the text out in a very tall probe frame; with Center, Bottom
or Justify the lines moved down inside it and the frame grew to tens of
thousands of points.
2026-10-08 20:30:14 -07:00
haven abdc26d8d1 M7: Shrink Text to Fit scales inline art's baseline shift
The fit scaled each run's size, leading and baseline shift but not an inline
graphic's own shift (points), so shrunk symbols sat off the cap-height centre.
2026-10-08 20:30:14 -07:00
haven 56c975465c M7: inline art follows vertically aligned lines
align_vertically moved lines and glyphs but not TextLayout::inlines, so inline
symbols in a centred or bottom-aligned area stayed where top alignment put them.
The reflow path for non-rectangular frames also kept the previous pass's
inlines, drawing each symbol twice.
2026-10-08 20:30:14 -07:00
BFlat 2dcac5b48b Merge pull request #658 from storytold/fix/651-gpu-fallback-int
Fix #651: a dual-GPU Mac falls back to its other GPU
2026-10-09 10:29:33 +07:00
60 changed files with 2978 additions and 148 deletions

No files matched your search

+10 -10
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-09 (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 windoLine truncated
_Last updated: 2026-10-09 (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 windoLine truncated
## Where we are
@@ -109,7 +109,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas.
- Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close).
- Four brightness themes, persistent preferences.
- Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). About 30 stored options still do nothing yet (the rest of #394: Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, Spacing Guides, performance, devices…).
- Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). About 20 stored options still do nothing yet (the rest of #394: Show Font Names in English, Highlight Alternate Glyphs, Display Print Size at 100% Zoom, Identify Objects By, East Asian Type units, Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation, scratch disks, the legacy clipboard, Appearance of Black, Touch Workspace).
- Dialogs move by dragging their heading (the band down from the top edge, as a title bar), stay on screen and keep where they were moved for the session; the form dialogs' choices are dropdowns (Offset Path's Joins, Average's and Shear's and Reflect's axis), and Offset Path lists Offset, Joins, Miter Limit and previews (#423).
- Dialogs open with their first field focused and its value selected: type a value and press Enter (Move, Rotate, Scale…). Number fields in panels, the Control bar and dialogs (preferences too) step with Up/Down, or with the mouse wheel over the focused field (#485: a notch a step; the panel under it then stays put, and an unfocused field leaves the wheel to scrolling) (Shift: ten, Ctrl/Cmd: a tenth of their unit), applied at once.
- Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels. Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off.
@@ -129,13 +129,13 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494).
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path).
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type.
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446), Measure, Type, Hand, Zoom, Rotate View.
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681), Measure, Type, Hand, Zoom, Rotate View.
- **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked.
- **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool.
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) 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"); 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.
- **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; 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).
- **Geometry and effects:**
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
@@ -143,10 +143,10 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, French, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, French, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (`object.cropImage {trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Paint and appearance (M3):**
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl` or CSS, and loaded from `.vcswatches`, `.gpl` and swatch exchange (`.ase`) files (RGB, CMYK, Lab and Gray; global, spot and process; groups). Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike. Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.
- **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects.
@@ -158,7 +158,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
- **Files (M4):**
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask.
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
@@ -216,14 +216,14 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 |
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard presets/rearrange polish (Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
| Guides, grids, smart guides, snapping, rulers | 3 | 84% | global/video rulers, Spacing Guides, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506) | 2–4 |
| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394) | 2–4 |
| File formats | 6 | 85% | DWG (no open spec: DXF instead), PSD placement as layers, EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers and presets are done | 6–10 |
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done) | 1–2 |
| Automation | 3 | 60% | Variables (data merge), scripting surface, batch | 8–12 |
| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 78% | macOS native menu dismissal fixed (M14.8); remaining: Variables, SVG Interactivity, Properties per context, Consolidate All Windows, floating panels outside the app window and docked into any group, context menus beyond the canvas (Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done), about 30 Preferences options stored but not yet acted on (#394: Spacing Guides, Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, performance, devices…) | 14–22 |
| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 78% | macOS native menu dismissal fixed (M14.8); remaining: Variables, SVG Interactivity, Properties per context, Consolidate All Windows, floating panels outside the app window and docked into any group, context menus beyond the canvas (Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done), about 20 Preferences options stored but not yet acted on (#394: Spacing Guides, Show Font Names in English, Highlight Alternate Glyphs, Display Print Size, Open Documents As Tabs, Real-time Drawing, hyphenation, Appearance of Black, devices…) | 14–22 |
| Libraries, Links, Package | 2 | 50% | a local Libraries panel (no cloud by design); Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 5–8 |
| **Feature parity** | **103** | **~75%** | | **~210–330** |
| Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 |
+1 -1
View File
@@ -37,7 +37,7 @@ const HELP: &str =
/// Frames the UI ran before the failure, below which it was still starting up. The failure in
/// #502 came on the first or second frame; later, the adapter has proved itself, and a lost
/// window is something else (such as the compositor restarting).
const STARTUP_FRAMES: u64 = 10;
pub const STARTUP_FRAMES: u64 = 10;
/// The preference used when Preferences say Automatic. Windows and macOS show frames from any GPU
/// (the integrated one avoids the flicker of #306). Elsewhere, the system's own order: Mesa's
+21 -1
View File
@@ -43,10 +43,13 @@ struct App {
graphics_loss: GraphicsLoss,
/// The graphics device was lost and the unsaved changes are kept for Data Recovery.
graphics_lost: bool,
/// Frames the UI has run (see [`end_before_teardown`]).
frames: u64,
}
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.frames = ctx.cumulative_frame_nr();
if let Some(why) = self.graphics_loss.take() {
// eframe can't give a window a new device: the user saves and starts again.
self.graphics_lost = self.app.graphics_lost(&why);
@@ -87,6 +90,7 @@ impl eframe::App for App {
#[cfg(not(feature = "windows7"))]
fn on_exit(&mut self) {
save_prefs(&self.app);
end_before_teardown(self.frames);
}
#[cfg(feature = "windows7")]
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
@@ -94,6 +98,22 @@ impl eframe::App for App {
}
}
/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting,
/// before eframe tears the window down (#661). AccessKit then gives the window's content view back
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit.
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
/// failure then starts the app again on another adapter (#651).
#[allow(unused_variables)]
fn end_before_teardown(frames: u64) {
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
if frames >= gpu::STARTUP_FRAMES {
log::info!("quitting");
log::logger().flush();
std::process::exit(0);
}
}
/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that
/// can't be opened is reported in the status bar and on stderr; the others still open.
fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
@@ -495,7 +515,7 @@ fn main() -> std::process::ExitCode {
#[cfg(not(target_os = "macos"))]
let _ = in_window_menus;
open_files(&mut app, files);
Ok(Box::new(App { app, graphics_loss, graphics_lost: false }))
Ok(Box::new(App { app, graphics_loss, graphics_lost: false, frames: 0 }))
}),
)
});
+86 -1
View File
@@ -1,7 +1,7 @@
//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files,
//! and the profiles exports embed ([`encode_builtin`]), written in code from the CMS.
use std::sync::{Arc, OnceLock};
use std::sync::{Arc, Mutex, OnceLock};
use moxcms::{
ColorProfile, DataColorSpace, Layout, LocalizableString, LutMultidimensionalType, LutStore, LutWarehouse, Matrix3d, ProfileClass, ProfileText,
@@ -27,6 +27,9 @@ fn intent_index(i: Intent) -> usize {
type Xf = Option<Arc<TransformF32Executor>>;
/// A direct transform's cache key: destination name, intent index, black-point compensation.
type DirectKey = (String, usize, bool);
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
pub struct IccProfile {
pub name: String,
@@ -37,6 +40,21 @@ pub struct IccProfile {
srgb: ColorProfile,
to_srgb: [OnceLock<Xf>; 4],
from_srgb: [OnceLock<Xf>; 4],
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
/// and black-point compensation.
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
}
/// A transform from one profile into an RGB profile without passing through sRGB: into the
/// destination's primaries with linear tone curves, where black-point compensation is a linear
/// remap, then onto its own curves.
struct Direct {
to_linear: Arc<TransformF32Executor>,
/// Linear → the destination's curves; `None` when the destination isn't a matrix profile
/// (the first transform goes straight into it, without compensation).
to_dest: Option<Arc<TransformF32Executor>>,
/// The source black's luminance in the linear destination (0: no compensation).
black: f32,
}
impl std::fmt::Debug for IccProfile {
@@ -72,6 +90,7 @@ impl IccProfile {
srgb: ColorProfile::new_srgb(),
to_srgb: Default::default(),
from_srgb: Default::default(),
direct: Mutex::new(Vec::new()),
})
}
@@ -135,6 +154,72 @@ impl IccProfile {
Some(dst.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
}
/// Device values (RGB / CMYK / Gray, 0..1) → `dest`'s RGB, converted directly with `intent`:
/// not through sRGB, so colours outside sRGB keep their place in a wider space. With `bpc`
/// (and an intent other than absolute), this profile's black maps onto the destination's
/// black (black-point compensation, the darkest ink the profile prints becoming RGB 0 rather
/// than a dark grey). `None` when `dest` isn't RGB or no transform can be built.
pub fn to_rgb_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<[f32; 3]> {
let t = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?;
let mut src = v.to_vec();
src.resize(self.channels(), 0.0);
let mut lin = [0.0f32; 3];
t.to_linear.transform(&src, &mut lin).ok()?;
let Some(to_dest) = &t.to_dest else { return Some(lin.map(|x| x.clamp(0.0, 1.0))) };
if t.black > 0.0 {
lin = lin.map(|x| (x - t.black) / (1.0 - t.black));
}
let lin = lin.map(|x| x.clamp(0.0, 1.0));
let mut out = [0.0f32; 3];
to_dest.transform(&lin, &mut out).ok()?;
Some(out.map(|x| x.clamp(0.0, 1.0)))
}
fn direct_xf(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<Arc<Direct>> {
if dest.kind != ProfileKind::Rgb {
return None;
}
let key = (dest.name.clone(), intent_index(intent), bpc);
let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) {
return t.clone();
}
let t = self.build_direct(dest, intent, bpc).map(Arc::new);
cache.push((key, t.clone()));
t
}
fn build_direct(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<Direct> {
let d = &dest.profile;
let matrix = d.red_trc.is_some() && d.green_trc.is_some() && d.blue_trc.is_some();
if !matrix {
let xf = self.profile.create_transform_f32(self.layout(), d, Layout::Rgb, Self::opts(intent)).ok()?;
return Some(Direct { to_linear: xf, to_dest: None, black: 0.0 });
}
let mut linear = d.clone();
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
}
// A coding-independent code point names the transfer curve outright (moxcms's sRGB has
// one) and would override the linear curves.
linear.cicp = None;
let to_linear = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
let to_dest = linear.create_transform_f32(Layout::Rgb, d, Layout::Rgb, Self::opts(Intent::RelativeColorimetric)).ok()?;
// The source black: the darkest colour the profile reproduces, found as lcms does for an
// output profile (black sent into the profile and read back), made neutral.
let black = if bpc && self.kind == ProfileKind::Cmyk {
let inks = self.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
let mut lin = [0.0f32; 3];
to_linear.transform(&inks, &mut lin).ok()?;
let y = |c: &moxcms::Xyzd| c.y as f32;
let lum = lin[0] * y(&d.red_colorant) + lin[1] * y(&d.green_colorant) + lin[2] * y(&d.blue_colorant);
lum.clamp(0.0, 0.5)
} else {
0.0
};
Some(Direct { to_linear, to_dest: Some(to_dest), black })
}
/// Whether transforms can be built for this profile (checked at registration).
pub fn usable(&self) -> bool {
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
+32 -1
View File
@@ -356,10 +356,37 @@ impl Cms {
}
}
/// CMYK in the working space → display sRGB (`absolute` simulates the paper colour).
/// CMYK in the working space → display sRGB (`absolute` simulates the paper colour). An ICC
/// CMYK profile converts as [`Self::cmyk_to_rgb`] does into sRGB (with the settings'
/// black-point compensation), so what shows is what an RGB export writes.
pub fn cmyk_to_srgb(&self, cmyk: [f32; 4], absolute: bool) -> [f32; 3] {
if let (false, CmykSpace::Icc(p)) = (absolute, &self.cmyk)
&& let Some(srgb) = builtin_rgb_cache(SRGB)
&& let Some(v) = p.to_rgb_of(&srgb, &cmyk.map(|v| v.clamp(0.0, 1.0)), Intent::RelativeColorimetric, self.settings.bpc)
{
return v;
}
Self::cmyk_to_srgb_in(&self.cmyk, cmyk, absolute)
}
/// CMYK in the working space → working RGB with `intent`. An ICC CMYK profile converts
/// directly into the RGB profile: not through display sRGB, which would clip colours a wider
/// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the
/// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before
/// (Generic CMYK compensates in its own model).
pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] {
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
let src = match &self.cmyk {
CmykSpace::Icc(p) => Some(p.clone()),
CmykSpace::Generic(_) | CmykSpace::Device => None,
};
let dest = match &self.rgb {
RgbSpace::Icc(p) => Some(p.clone()),
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
};
src.zip(dest)
.and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false)))
}
/// Display sRGB → working CMYK with `intent`.
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
Self::srgb_to_cmyk_in(&self.cmyk, srgb, intent, self.settings.bpc)
@@ -424,6 +451,10 @@ impl Cms {
let [c, m, y, k] = self.to_cmyk(c, intent);
Color::Cmyk { c, m, y, k }
}
(Color::Cmyk { c, m, y, k }, Model::Rgb) => {
let [r, g, b] = self.cmyk_to_rgb([*c, *m, *y, *k], intent);
Color::Rgb { r, g, b }
}
(_, Model::Rgb) => {
let [r, g, b] = self.srgb_to_rgb(self.display_rgb(c));
Color::Rgb { r, g, b }
+51
View File
@@ -60,3 +60,54 @@ fn a_loaded_profile_is_embedded_as_loaded() {
register_icc(&bytes, Some("Embedded As Loaded RGB".into())).unwrap();
assert_eq!(&*icc_bytes("Embedded As Loaded RGB").unwrap(), &bytes[..]);
}
/// Settings with an ICC CMYK profile (Generic CMYK's, loaded as a file is) and Wide Gamut RGB.
fn icc_cmyk(bpc: bool) -> Cms {
let name = register_icc(&icc_bytes(GENERIC_CMYK).unwrap(), Some("Test ICC CMYK".into())).unwrap().name;
Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: name, bpc, ..ColorSettings::default() }).unwrap()
}
#[test]
fn icc_cmyk_converts_into_a_wide_rgb_space_directly_without_clipping_to_srgb() {
let wide = icc_cmyk(true);
let cyan = [1.0, 0.0, 0.0, 0.0];
let direct = wide.cmyk_to_rgb(cyan, Intent::RelativeColorimetric);
// Through sRGB, cyan clips to sRGB's gamut first: in the wider space that reads as a red
// channel well above zero.
let hub = wide.srgb_to_rgb(wide.cmyk_to_srgb(cyan, false));
assert!(direct[0] + 0.15 < hub[0], "direct {direct:?}, through sRGB {hub:?}");
// Same colour either way where sRGB holds it: a mid grey and paper white.
for inks in [[0.0, 0.0, 0.0, 0.5], [0.0; 4]] {
let (d, h) = (wide.cmyk_to_rgb(inks, Intent::RelativeColorimetric), wide.srgb_to_rgb(wide.cmyk_to_srgb(inks, false)));
assert!(d.iter().zip(h).all(|(a, b)| (a - b).abs() < 0.02), "{inks:?}: direct {d:?}, through sRGB {h:?}");
}
// Cms::convert takes the direct route for CMYK.
let Color::Rgb { r, .. } = wide.convert(&Color::Cmyk { c: 1.0, m: 0.0, y: 0.0, k: 0.0 }, Model::Rgb, Intent::RelativeColorimetric) else {
panic!("RGB")
};
assert!((r - direct[0]).abs() < 1e-6);
}
#[test]
fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
let rich = [0.75, 0.68, 0.67, 0.9];
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
// The screen shows what an sRGB conversion writes, compensated alike.
let srgb = |bpc| {
let c = icc_cmyk(bpc);
Cms::new(&ColorSettings { rgb: SRGB.into(), ..c.settings().clone() }).unwrap()
};
for bpc in [true, false] {
let c = srgb(bpc);
assert_eq!(c.cmyk_to_srgb(rich, false), c.cmyk_to_rgb(rich, Intent::RelativeColorimetric), "bpc {bpc}");
}
// White is untouched, and absolute colorimetric never compensates.
let white = icc_cmyk(true).cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric);
assert!(white.iter().all(|v| *v > 0.99), "{white:?}");
let abs = |bpc| icc_cmyk(bpc).cmyk_to_rgb(rich, Intent::AbsoluteColorimetric);
assert_eq!(abs(true), abs(false));
}
+55
View File
@@ -136,10 +136,65 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
Inks::new(w, h, data)
}
/// A CMYK TIFF with an alpha channel (5 samples) as RGBA pixels, each colour converted by `rgb`
/// (ink amounts 0..1 → sRGB 0..1) and associated (premultiplied) alpha divided back out; `None`
/// for other images, planar ones and ones larger than [`MAX_CMYK_PIXELS`]. The image decoder
/// doesn't read these at all; the inks can't be kept with the transparency, so they show as RGB.
pub fn cmyka_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option<image::RgbaImage> {
let (kind, mut d) = tiff(bytes)?;
let (w, h) = d.dimensions().ok()?;
let planar = d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1);
if !matches!(kind, tiff::ColorType::CMYKA(8 | 16)) || planar {
return None;
}
let n = usize::try_from(pixels(w, h)?).ok()?;
// ExtraSamples 1: associated alpha (premultiplied colour); 2 (or none stated): unassociated.
let associated = d.find_tag_unsigned_vec::<u16>(tiff::tags::Tag::ExtraSamples).ok().flatten().is_some_and(|v| v.first() == Some(&1));
let data: Vec<u8> = match d.read_image().ok()? {
tiff::decoder::DecodingResult::U8(v) => v,
tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
_ => return None,
};
if data.len() != n * 5 {
return None;
}
let mut out = Vec::with_capacity(n * 4);
for p in data.as_chunks::<5>().0 {
let a = f32::from(p[4]) / 255.0;
let ink = |v: u8| {
let v = f32::from(v) / 255.0;
if associated && a > 0.0 { (v / a).min(1.0) } else { v }
};
let [r, g, b] = rgb([ink(p[0]), ink(p[1]), ink(p[2]), ink(p[3])]);
out.extend([r, g, b].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8));
out.push(p[4]);
}
image::RgbaImage::from_raw(w, h, out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_cmyk_tiff_with_alpha_reads_as_rgba() {
use tiff::encoder::{TiffEncoder, colortype::CMYKA8};
// 2 × 1: full cyan opaque, then 100% K at half alpha (premultiplied: K 128, alpha 128).
let mut file = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut file).unwrap();
let mut img = enc.new_image::<CMYKA8>(2, 1).unwrap();
img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap();
img.write_data(&[255, 0, 0, 0, 255, 0, 0, 0, 128, 128]).unwrap();
let bytes = file.into_inner();
let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)];
let px = cmyka_tiff_rgba(&bytes, naive).expect("CMYKA reads");
assert_eq!(px.dimensions(), (2, 1));
assert_eq!(px.get_pixel(0, 0).0, [0, 255, 255, 255], "cyan, opaque");
assert_eq!(px.get_pixel(1, 0).0, [0, 0, 0, 128], "the premultiplied K divided back out: black at half alpha");
// Not CMYKA: not this reader's.
assert!(cmyka_tiff_rgba(&ImageBlob::cmyk_tiff(&inks()).unwrap().bytes, naive).is_none());
}
fn inks() -> Inks {
Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap()
}
+26 -10
View File
@@ -282,10 +282,19 @@ pub(super) fn new_from_template(s: &mut Session, p: &Value) -> Result<Value> {
open_template(s, src.name, &src.bytes, src.path)
}
/// The most memory decoding one image may take: a 60 in print sheet at 300 ppi (18000 × 6600 px)
/// is ~475 MB as RGBA, past the decoder's 512 MB default once it is converted. The web app keeps
/// that default: wasm32 has 4 GB to address and aborts when an allocation fails.
const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
/// they are, with their ink amounts ([`ImageBlob::cmyk`]).
/// they are, with their ink amounts ([`ImageBlob::cmyk`]); CMYK TIFFs with an alpha channel, which
/// the decoder can't read, become RGBA in the active colour settings' CMYK.
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
let ppi = super::ppi::resolution(bytes);
@@ -293,7 +302,14 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let (bytes, mime, (width, height)) = if matches!(f.id, "png" | "jpg" | "gif" | "webp") || (f.id == "tiff" && cmyk()) {
(bytes.to_vec(), f.mime, reader.into_dimensions().map_err(err)?)
} else {
let img = reader.decode().map_err(err)?.to_rgba8();
let cmyka = || {
let cms = vectorcraft_color::cms::active();
vectorcraft_doc::cmyk::cmyka_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
};
let img = match (f.id == "tiff").then(cmyka).flatten() {
Some(img) => img,
None => reader.decode().map_err(err)?.to_rgba8(),
};
let size = img.dimensions();
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
@@ -311,16 +327,16 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi })
}
/// An image as a document of its pixel size (1 px = 1 pt), the image named after the file.
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
let RasterImage { key, blob, width, height, .. } = raster_image(bytes)?;
let mut d = Document::new(width as f64, height as f64);
let RasterImage { key, blob, width, height, ppi } = raster_image(bytes)?;
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
let layer = d.layers[0].id;
let id = d.alloc_id();
let mut n = Node::new(
id,
NodeKind::Image(ImageObject { key: key.clone(), width, height, xf: Affine::IDENTITY, link: None, placement: Default::default() }),
);
let xf = Affine::scale_non_uniform(sx, sy);
let mut n = Node::new(id, NodeKind::Image(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default() }));
n.name = Some(name.to_string());
d.images.insert(key, blob);
d.insert(Some(layer), 0, n).map_err(err)?;
+1 -1
View File
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its pixel size), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
always,
load::open
),
@@ -147,3 +147,19 @@ fn the_document_background_is_the_default_export_background() {
assert_eq!(png(&mut s, json!({"format": "png", "background": "transparent"})).get_pixel(0, 0)[3], 0, "the option wins");
assert_eq!(png(&mut s, json!({"format": "webp", "background": "black"})).get_pixel(0, 0).0, [0, 0, 0, 255]);
}
#[test]
fn an_image_opens_at_the_size_its_resolution_declares() {
let mut s = session(72.0, 36.0, 1);
let hi = b64(&s.execute("document.export", &json!({"format": "png", "ppi": 300, "background": "white"})).unwrap());
let lo = b64(&s.execute("document.export", &json!({"format": "png", "background": "white"})).unwrap());
let lo = super::ppi::with_png_resolution(&lo, (72.0, 72.0));
for (png, w, h, what) in [(hi, 72.0, 36.0, "300 ppi: 300 x 150 px is 1 x 0.5 in"), (lo, 72.0, 36.0, "72 ppi: 1 px = 1 pt")] {
s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
let doc = &s.doc().unwrap().doc;
let ab = doc.artboards[0].rect;
assert!((ab.width() - w).abs() < 1e-6 && (ab.height() - h).abs() < 1e-6, "{what}: artboard {ab:?}");
let art = doc.art_bounds().expect("the image");
assert!((art.width() - w).abs() < 1e-6 && (art.height() - h).abs() < 1e-6, "{what}: the image fills it, {art:?}");
}
}
+16 -1
View File
@@ -247,7 +247,7 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
}
}
fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
let db = vectorcraft_text::FontDb::global();
#[cfg(not(target_arch = "wasm32"))]
let faces = db.load_system_fonts();
@@ -283,6 +283,21 @@ fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
mod tests {
use super::*;
/// Type › Options › Additional Fonts Folder (#683) adds its folder to the system font scan,
/// trimmed; clearing it takes the folder out again.
#[test]
fn the_additional_fonts_folder_joins_the_font_scan() {
let mut s = Session::new();
let dir = std::env::temp_dir().join("vectorcraft-fonts-folder-pref");
s.execute("prefs.set", &json!({"key": "fontsFolder", "value": format!(" {} ", dir.display())})).unwrap();
assert_eq!(vectorcraft_text::user_font_dirs(), std::slice::from_ref(&dir));
if !cfg!(target_arch = "wasm32") {
assert!(vectorcraft_text::system_font_dirs().contains(&dir));
}
s.execute("prefs.set", &json!({"key": "fontsFolder", "value": ""})).unwrap();
assert!(vectorcraft_text::user_font_dirs().is_empty() && !vectorcraft_text::system_font_dirs().contains(&dir));
}
#[test]
fn list_flag_missing_replace_and_select() {
let mut s = Session::new();
+78 -10
View File
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Crop Image",
["Object"],
None,
"{rect?: [x, y, width, height]} crop the selected image (default: to the artboard it sits on) → {id, width, height}",
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim)}",
has_image,
crop_image
),
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rearrange All Artboards…",
["Object", "Artboards"],
None,
"{columns?: n (2), spacing?: pt (20), byColumn?: false, moveArtwork?: true (locked and hidden art only with prefs moveLockedWithArtboard)} lay artboards out in a grid",
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (locked and hidden art only with prefs moveLockedWithArtboard)} lay the artboards out in their order, the grid's top-left at the first artboard's → {artboards, rows, columns}",
has_doc,
rearrange_artboards
),
@@ -541,6 +541,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
if p.get("trim").and_then(Value::as_bool) == Some(true) {
return trim_image(s, id, im.clone());
}
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
let rect = match p.get("rect").and_then(Value::as_array) {
Some(a) if a.len() == 4 => {
@@ -594,6 +597,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "width": w, "height": h }))
}
/// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the
/// pixels copied as they are (no resampling) and placed where they were.
fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
const C: &str = "object.cropImage";
let st = s.doc()?;
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
let px = image::load_from_memory(&blob.bytes).map_err(|_| bad(C, "the image's pixels can't be read"))?.to_rgba8();
let (w, h) = px.dimensions();
let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
for (x, y, p) in px.enumerate_pixels() {
if p[3] > 0 {
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
}
}
if x1 <= x0 || y1 <= y0 {
return Err(bad(C, "the image is fully transparent"));
}
if (x0, y0, x1, y1) == (0, 0, w, h) {
// Already trimmed: not an error, so a script can trim every image it opens.
return Ok(json!({ "id": id.0, "width": w, "height": h, "trimmed": false }));
}
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
let mut png = Vec::new();
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?;
let (cw, ch) = (x1 - x0, y1 - y0);
s.edit("Crop Image", |d, _| {
let key = unique_key(d, "crop");
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
if let Some(n) = d.node_mut(id) {
n.kind = NodeKind::Image(ImageObject {
key,
width: cw,
height: ch,
xf: im.xf * Affine::translate((f64::from(x0), f64::from(y0))),
link: None,
placement: Default::default(),
});
}
Ok(())
})?;
Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true }))
}
/// The Control bar's Mask for an image: a clip group of the image and a clipping path on its
/// outline, with that path selected so dragging its handles crops the image.
fn mask_image(s: &mut Session, _: &Value) -> Result<Value> {
@@ -777,10 +823,32 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
}
fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
let n_ab = s.doc()?.doc.artboards.len().max(1);
let cols = (f64_or(p, "columns", 2.0).clamp(1.0, n_ab as f64)) as usize;
const CMD: &str = "artboard.rearrange";
use super::newdoc::ArtboardLayout as L;
// A value given (not null) must be one of the names.
let named = |key: &str| p.get(key).filter(|v| !v.is_null()).map(|v| v.as_str().unwrap_or_default());
let layout = match named("layout") {
Some(l) => L::parse(l).ok_or_else(|| bad(CMD, "layout must be gridByRow, gridByColumn, row or column"))?,
None if bool_or(p, "byColumn", false) => L::GridByColumn,
None => L::GridByRow,
};
let rtl = match named("order") {
None => false,
Some(o) if o.eq_ignore_ascii_case("leftToRight") => false,
Some(o) if o.eq_ignore_ascii_case("rightToLeft") => true,
Some(_) => return Err(bad(CMD, "order must be leftToRight or rightToLeft")),
};
let count = s.doc()?.doc.artboards.len();
let n_ab = count.max(1);
// Columns of a grid by row, rows of a grid by column (NaN casts to 0).
let lines = (f64_or(p, "columns", 2.0).clamp(1.0, n_ab as f64) as usize).max(1);
let (rows, cols) = match layout {
L::GridByRow => (n_ab.div_ceil(lines), lines),
L::GridByColumn => (lines, n_ab.div_ceil(lines)),
L::Row => (1, n_ab),
L::Column => (n_ab, 1),
};
let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5);
let by_col = bool_or(p, "byColumn", false);
let move_art = bool_or(p, "moveArtwork", true);
let locked_and_hidden = s.prefs.move_locked_with_artboard;
let scale_strokes = false;
@@ -788,7 +856,7 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
let rects: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
let Some(first) = rects.first().copied() else { return Ok(()) };
let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect();
let origins = super::newdoc::grid_origins(&sizes, first.origin(), cols, spacing, by_col, false);
let origins = super::newdoc::grid_origins_rc(&sizes, first.origin(), (rows, cols), spacing, layout == L::GridByColumn, rtl);
let deltas: Vec<Vec2> = rects.iter().zip(origins).map(|(r, o)| o - r.origin()).collect();
if move_art {
let tops: Vec<(NodeId, Point)> = d
@@ -800,11 +868,11 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
.filter_map(|n| Some((n.id, n.geometric_bounds()?.center())))
.collect();
for (id, c) in tops {
if let Some(i) = rects.iter().position(|r| r.contains(c))
&& deltas[i] != Vec2::ZERO
if let Some(&dl) = rects.iter().position(|r| r.contains(c)).and_then(|i| deltas.get(i))
&& dl != Vec2::ZERO
&& let Some(n) = d.node_mut(id)
{
n.transform(Affine::translate(deltas[i]), scale_strokes);
n.transform(Affine::translate(dl), scale_strokes);
}
}
}
@@ -818,5 +886,5 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
ok()
Ok(json!({ "artboards": count, "rows": rows, "columns": cols }))
}
+17 -4
View File
@@ -345,9 +345,22 @@ pub fn color_mode_id(m: ColorMode) -> &'static str {
/// each column as wide and each row as tall as its largest artboard; `by_column` fills columns
/// top to bottom first, `rtl` puts the first column at the right.
pub(crate) fn grid_origins(sizes: &[(f64, f64)], origin: Point, columns: usize, spacing: f64, by_column: bool, rtl: bool) -> Vec<Point> {
let n = sizes.len();
let cols = columns.clamp(1, n.max(1));
let rows = n.div_ceil(cols).max(1);
let n = sizes.len().max(1);
let cols = columns.clamp(1, n);
grid_origins_rc(sizes, origin, (n.div_ceil(cols), cols), spacing, by_column, rtl)
}
/// [`grid_origins`] on a grid of `rows` × `cols` cells (at least enough for every artboard when
/// filled the `by_column` way).
pub(crate) fn grid_origins_rc(
sizes: &[(f64, f64)],
origin: Point,
(rows, cols): (usize, usize),
spacing: f64,
by_column: bool,
rtl: bool,
) -> Vec<Point> {
let (rows, cols) = (rows.max(1), cols.max(1));
// Grid cell (row, column) of artboard i.
let cell = |i: usize| {
let (r, c) = if by_column { (i % rows, i / rows) } else { (i / cols, i % cols) };
@@ -362,7 +375,7 @@ pub(crate) fn grid_origins(sizes: &[(f64, f64)], origin: Point, columns: usize,
}
}
let offset = |spans: &[f64], k: usize| spans.iter().take(k).map(|s| s + spacing).sum::<f64>();
(0..n)
(0..sizes.len())
.map(|i| {
let (r, c) = cell(i);
Point::new(origin.x + offset(&col_w, c), origin.y + offset(&row_h, r))
+25 -1
View File
@@ -187,6 +187,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool),
p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool),
p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool),
p!("fontsFolder", "Type", "Options", "Additional Fonts Folder", text),
// Units
p!("unitsGeneral", "Units", "", "General", choice(UNITS)),
p!("unitsStroke", "Units", "", "Stroke", choice(UNITS)),
@@ -260,7 +261,19 @@ pub const PREF_SPECS: &[PrefSpec] = &[
"Brightness",
choice(&[("dark", "Dark"), ("mediumDark", "Medium Dark"), ("mediumLight", "Medium Light"), ("light", "Light")])
),
p!("canvasColor", "User Interface", "", "Canvas Color", choice(&[("matchUi", "Match User Interface Brightness"), ("white", "White")])),
p!(
"canvasColor",
"User Interface",
"",
"Canvas Color",
choice(&[
("matchUi", "Match User Interface Brightness"),
("white", "White"),
("lightGray", "Light Gray"),
("mediumGray", "Medium Gray"),
("darkGray", "Dark Gray")
])
),
p!("autoCollapseIconPanels", "User Interface", "", "Auto-Collapse Iconic Panels", bool),
p!("openDocumentsAsTabs", "User Interface", "", "Open Documents As Tabs", bool),
p!("largeTabs", "User Interface", "", "Large Tabs", bool),
@@ -460,7 +473,18 @@ impl Session {
let grid_changed = p.gridline_every != self.prefs.gridline_every || p.grid_subdivisions != self.prefs.grid_subdivisions;
let history_changed = p.history_states != self.prefs.history_states;
let tile_edge_changed = p.pattern_tile_edge_color != self.prefs.pattern_tile_edge_color;
let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder;
self.prefs = p;
if fonts_folder_changed {
let folder = self.prefs.fonts_folder.trim();
vectorcraft_text::set_user_font_dirs(if folder.is_empty() { vec![] } else { vec![folder.into()] });
// Once the fonts were scanned, scan again now: the folder's fonts appear (or go) in the
// font menus, and type in them lays out again. The first scan reads it anyway.
if vectorcraft_text::FontDb::global().installed_fonts_changed() {
// Its result only counts the faces cataloged.
let _ = super::fonts::rescan(self, &serde_json::Value::Null);
}
}
vectorcraft_render::set_default_threads(u16::try_from(self.prefs.render_threads).ok());
for st in &mut self.docs {
if history_changed {
+2
View File
@@ -147,6 +147,8 @@ fn auto_height(t: &mut TextObject) -> bool {
let col_w = if cols > 1 { ((b.width() - t.area.gutter.max(0.0) * (cols - 1) as f64) / cols as f64).max(1.0) } else { b.width() };
with_size(&mut probe, col_w, tall);
probe.area.columns = 1;
// Measured from the top: aligned in the tall probe the lines would sit far below.
probe.area.vertical_align = vectorcraft_doc::VerticalAlign::Top;
let lay = vectorcraft_text::layout(db, &probe);
let inset = t.area.inset.max(0.0);
let Some(bottom) = lay.lines.iter().map(|l| l.baseline + l.descent).filter(|y| y.is_finite()).reduce(f64::max) else { return false };
+6
View File
@@ -480,6 +480,9 @@ pub struct Prefs {
// Hyphenation
pub hyphenation_language: String,
pub hyphenation_exceptions: String,
/// Type › Options › Additional Fonts Folder: a folder (read with its subfolders) whose fonts
/// are listed and used as if installed (#683); empty for none.
pub fonts_folder: String,
// Performance & Storage (Plug-ins & Scratch Disks)
pub plugins_folder: String,
pub scratch_primary: String,
@@ -696,6 +699,7 @@ impl Default for Prefs {
slice_line_color: s("#ff3f3f"),
hyphenation_language: s("English: USA"),
hyphenation_exceptions: String::new(),
fonts_folder: String::new(),
plugins_folder: String::new(),
scratch_primary: s("Startup"),
scratch_secondary: s("None"),
@@ -1586,6 +1590,8 @@ mod tests_swatchlib;
#[cfg(test)]
mod tests_targeting;
#[cfg(test)]
mod tests_textcombos;
#[cfg(test)]
mod tests_textedit;
#[cfg(test)]
mod tests_textimport;
+32
View File
@@ -1159,3 +1159,35 @@ fn saved_selection_names_are_trimmed_and_capped() {
let list = s.execute("select.savedList", &json!({})).unwrap();
assert_eq!(list[0].as_str().map(|n| n.chars().count()), Some(vectorcraft_doc::SavedSelection::MAX_NAME));
}
#[test]
fn crop_image_trim_cuts_to_the_opaque_pixels_as_they_are() {
// 100 × 80 px, transparent but for a block at (20, 10)–(50, 40) px; placed at 2 pt a pixel.
let mut px = image::RgbaImage::new(100, 80);
for y in 10..40 {
for x in 20..50 {
px.put_pixel(x, y, image::Rgba([x as u8, y as u8, 7, if x == 20 { 1 } else { 255 }]));
}
}
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 30), "{r}");
// Placed where those pixels were: (40, 20) pt, 60 × 60 pt at 2 pt a pixel.
let b = bounds(&s, img);
assert!(close(b.x0, 40.0) && close(b.y0, 20.0) && close(b.width(), 60.0) && close(b.height(), 60.0), "{b:?}");
// Pixel for pixel, a barely visible (alpha 1) edge included.
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
assert_eq!(out, image::imageops::crop_imm(&px, 20, 10, 30, 30).to_image());
assert_eq!(r["trimmed"], true);
// Nothing transparent left to cut: left as it is, and not an error (scripts trim every image).
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64()), (Some(false), Some(30)), "{r}");
assert_eq!(bounds(&s, img), b);
}
+60
View File
@@ -223,3 +223,63 @@ fn rearrange_keeps_its_grid() {
s.execute("artboard.rearrange", &json!({"columns": 2, "spacing": 5})).unwrap();
assert_eq!(boards(&s).iter().map(|r| (r.x0, r.y0)).collect::<Vec<_>>(), [(0.0, 0.0), (105.0, 0.0), (0.0, 55.0)]);
}
/// #681: every layout and order of Rearrange All Artboards, five 100 × 50 artboards 10 pt apart
/// with Columns (the rows of a grid by column) 2: each artboard lands in its (row, column) cell, the
/// art on it rides along, and it all undoes in one step.
#[test]
fn rearrange_lays_out_by_layout_and_order() {
type Cells = [(u32, u32); 5];
let cells: [(&str, &str, Cells); 8] = [
("gridByRow", "leftToRight", [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]),
("gridByRow", "rightToLeft", [(0, 1), (0, 0), (1, 1), (1, 0), (2, 1)]),
("gridByColumn", "leftToRight", [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2)]),
("gridByColumn", "rightToLeft", [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0)]),
("row", "leftToRight", [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)]),
("row", "rightToLeft", [(0, 4), (0, 3), (0, 2), (0, 1), (0, 0)]),
("column", "leftToRight", [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]),
("column", "rightToLeft", [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]),
];
for (layout, order, want) in cells {
// One row, 20 pt apart; a 10 pt square 10 pt into each artboard.
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 5}));
let art: Vec<u64> = boards(&s)
.iter()
.map(|r| {
s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
})
.collect();
let before = boards(&s);
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"layout": layout, "order": order, "columns": 2, "spacing": 10});
let r = s.execute("artboard.rearrange", &p).unwrap();
let (rows, cols) = want.iter().fold((0, 0), |(r, c), (wr, wc)| (r.max(wr + 1), c.max(wc + 1)));
assert_eq!(r, json!({"artboards": 5, "rows": rows, "columns": cols}), "{layout} {order}");
let got: Vec<(f64, f64)> = boards(&s).iter().map(|r| (r.x0, r.y0)).collect();
let cells: Vec<(f64, f64)> = want.iter().map(|&(r, c)| (f64::from(c) * 110.0, f64::from(r) * 60.0)).collect();
assert_eq!(got, cells, "{layout} {order}");
assert!(boards(&s).iter().all(|r| r.width() == 100.0 && r.height() == 50.0));
for (id, (x, y)) in art.iter().zip(&got) {
let b = s.doc().unwrap().doc.node(NodeId(*id)).unwrap().geometric_bounds().unwrap();
assert_eq!((b.x0, b.y0), (x + 10.0, y + 10.0), "{layout} {order}: the art moves with its artboard");
}
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(boards(&s), before);
}
}
/// `byColumn: true` is Grid by Column; without `moveArtwork` the art stays; bad values are errors.
#[test]
fn rearrange_aliases_and_rejects_bad_values() {
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
let id = s.execute("shape.rectangle", &json!({"x": 130, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("artboard.rearrange", &json!({"byColumn": true, "columns": 2, "spacing": 0, "moveArtwork": false})).unwrap();
assert_eq!(boards(&s).iter().map(|r| (r.x0, r.y0)).collect::<Vec<_>>(), [(0.0, 0.0), (0.0, 50.0), (100.0, 0.0)]);
assert_eq!(s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x0, 130.0, "the art stays");
let before = boards(&s);
for p in [json!({"layout": "diagonal"}), json!({"order": "upward"}), json!({"layout": 3}), json!({"order": true})] {
assert!(s.execute("artboard.rearrange", &p).is_err(), "{p}");
}
assert_eq!(boards(&s), before, "nothing moved");
}
+27
View File
@@ -282,6 +282,33 @@ fn snap_to_point_lands_a_dragged_selection_on_anchors() {
assert_eq!(drag(&mut s, ViewInfo { snap_to_point: false, ..v }), (276.5, 76.0), "View › Snap to Point off");
}
/// Smart Guides › Spacing Guides (#394): a square dragged 21 pt to the right of a row of two
/// squares 20 pt apart lands 20 pt from it, with the gaps marked; off, it stays at 21.
#[test]
fn spacing_guides_space_a_dragged_square_like_its_row() {
use vectorcraft_tools::PointerKind::{Down, Drag, Up};
let mut s = new_doc();
square(&mut s, 20.0, 300.0);
square(&mut s, 90.0, 300.0);
let m = square(&mut s, 200.0, 305.0);
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
// `m` grabbed by its centre and dragged so its left edge is 21 pt from the second square.
let drag = |s: &mut Session| {
gesture(s, v, &[(Down, 225.0, 330.0), (Drag, 200.0, 330.0), (Drag, 186.0, 330.0)]);
let marks = s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Line { a, b, .. } if a.y == b.y)).count();
gesture(s, v, &[(Up, 186.0, 330.0)]);
let at = top_left(s, m).0;
s.execute("edit.undo", &json!({})).unwrap();
(at, marks)
};
let (at, marks) = drag(&mut s);
assert_eq!(at, 160.0, "20 pt from it");
assert!(marks >= 2, "both gaps marked");
set_pref(&mut s, "spacingGuides", json!(false));
assert_eq!(drag(&mut s), (161.0, 0), "off: where it was dragged");
}
/// Preferences › Smart Guides (#394): Color, Alignment Guides, Anchor/Path Labels, Measurement
/// Labels, Transform Tools and Snapping Tolerance change what the Selection tool shows while a
/// square is dragged into line with another, and how far the pull reaches; a hidden guide still
+310
View File
@@ -0,0 +1,310 @@
//! The text engine's newer features combined through commands: Auto Size and Shrink Text to Fit
//! with inline graphics, per-paragraph attributes, the paragraph composer and vertical
//! alignment; editing and undo across them; and a save round trip with all of them on.
//! (`vectorcraft_text`'s `tests_combos` covers the layout side.)
use serde_json::{Value, json};
use vectorcraft_doc::text::INLINE_CHAR;
use vectorcraft_doc::{AreaFit, Composer, Justify, NodeKind, TextKind, TextObject, VerticalAlign};
use vectorcraft_geom::Rect;
use super::*;
const STORY: &str = "The quick brown fox jumps over the lazy dog. A second sentence follows the first one here. Then a third one ends it.";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
/// A symbol `name`: a circle `d` points across, its instance deleted.
fn circle_symbol(s: &mut Session, name: &str, d: f64) {
s.execute("shape.ellipse", &json!({"x": 600, "y": 500, "width": d, "height": d})).unwrap();
s.execute("symbol.new", &json!({"name": name})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
}
/// Area type at (40, 40), `w` × `h`, size 12, with `extra` area options; selected.
fn area(s: &mut Session, w: f64, h: f64, text: &str, extra: Value) -> NodeId {
let mut a = json!({"width": w, "height": h});
if let (Some(a), Some(e)) = (a.as_object_mut(), extra.as_object()) {
a.extend(e.clone());
}
let id = NodeId(s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": a, "text": text})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
id
}
fn text(s: &Session, id: NodeId) -> TextObject {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
k => panic!("not text: {k:?}"),
}
}
fn frame(s: &Session, id: NodeId) -> Rect {
match text(s, id).kind {
TextKind::Area { frame } => frame.bounds().unwrap(),
k => panic!("not area type: {k:?}"),
}
}
fn lay(t: &TextObject) -> vectorcraft_text::TextLayout {
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t)
}
/// Auto Size's frame is tight: the text fits, and a point less overflows.
fn assert_tight(s: &Session, id: NodeId, what: &str) {
let t = text(s, id);
assert!(!lay(&t).overflow, "{what}: the frame holds the text");
let b = frame(s, id);
let mut less = t.clone();
less.area.fit = AreaFit::None;
less.kind = TextKind::Area {
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(b.x0, b.y0, b.x1, b.y1 - 1.0), 0.1)),
};
assert!(lay(&less).overflow, "{what}: a point less overflows ({b:?})");
}
fn undo(s: &mut Session) {
s.execute("edit.undo", &json!({})).unwrap();
}
fn redo(s: &mut Session) {
s.execute("edit.redo", &json!({})).unwrap();
}
fn query(s: &mut Session) -> Value {
s.execute("text.areaOptions", &json!({})).unwrap()
}
#[test]
fn auto_height_x_inline_graphics() {
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(&mut s, 200.0, 300.0, "Tap: add one mana.", json!({"fit": "autoHeight"}));
let one = frame(&s, id);
assert_tight(&s, id, "one line");
// Art taller than the line makes the line, and so the frame, taller: in the same undo step.
let n = s.doc().unwrap().history.undo.len();
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 3})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n + 1);
let tall = frame(&s, id);
assert!(tall.height() > one.height() + 5.0, "{one:?} → {tall:?}");
assert_tight(&s, id, "tall art");
// Enough art to wrap: another line.
for _ in 0..12 {
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 1})).unwrap();
}
assert!(lay(&text(&s, id)).lines.len() > 1);
assert_tight(&s, id, "wrapped art");
// Deleting the art shrinks it back; undo restores each step exactly.
let wrapped = frame(&s, id);
let all = text(&s, id).plain_text().rfind(INLINE_CHAR).unwrap() + INLINE_CHAR.len_utf8();
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": all})).unwrap();
assert_eq!(text(&s, id).plain_text(), "Tap: add one mana.");
assert_eq!(frame(&s, id), one);
undo(&mut s);
assert_eq!(frame(&s, id), wrapped);
for _ in 0..13 {
undo(&mut s);
}
assert_eq!(frame(&s, id), one);
redo(&mut s);
assert_eq!(frame(&s, id), tall);
}
#[test]
fn auto_height_x_paragraph_attrs() {
let mut s = session();
let id = area(&mut s, 200.0, 300.0, "One\nTwo", json!({"fit": "autoHeight"}));
let h0 = frame(&s, id).height();
// Space before on the second paragraph only: the frame grows by exactly that.
s.execute("text.setFormat", &json!({"ids": [id.0], "spaceBefore": 30, "start": 4, "end": 4})).unwrap();
let t = text(&s, id);
assert_eq!((t.para_at(0).space_before, t.para_at(1).space_before), (0.0, 30.0));
let h1 = frame(&s, id).height();
assert!((h1 - h0 - 30.0).abs() < 1e-6, "{h0} → {h1}");
assert_tight(&s, id, "space before");
// Return in the spaced paragraph: the new one inherits the spacing, the frame follows.
s.execute("text.editRange", &json!({"id": id.0, "start": 7, "end": 7, "insert": "\nThree"})).unwrap();
let t = text(&s, id);
assert_eq!(t.paragraph_styles().iter().map(|p| p.space_before).collect::<Vec<_>>(), [0.0, 30.0, 30.0]);
assert!(frame(&s, id).height() > h1 + 30.0);
assert_tight(&s, id, "three paragraphs");
// Merging paragraphs: the first one's attributes win, the frame shrinks.
s.execute("text.editRange", &json!({"id": id.0, "start": 3, "end": 4})).unwrap();
let t = text(&s, id);
assert_eq!(t.paragraph_styles().iter().map(|p| p.space_before).collect::<Vec<_>>(), [0.0, 30.0]);
assert_tight(&s, id, "merged");
undo(&mut s);
undo(&mut s);
assert!((frame(&s, id).height() - h1).abs() < 1e-9);
undo(&mut s);
assert!((frame(&s, id).height() - h0).abs() < 1e-9);
assert!(text(&s, id).paras.is_empty(), "back to one style for all");
}
#[test]
fn auto_height_x_composer() {
// Switching the composer of one paragraph rebreaks it; Auto Size follows either way.
let mut s = session();
let story = format!("{STORY} {STORY}\n{STORY}");
let id = area(&mut s, 130.0, 100.0, &story, json!({"fit": "autoHeight"}));
assert_tight(&s, id, "every-line");
for composer in ["singleLine", "everyLine", "singleLine"] {
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": composer, "start": 0, "end": 0})).unwrap();
let t = text(&s, id);
assert_eq!(t.para_at(1).composer, Composer::EveryLine, "the second paragraph keeps its own");
assert_tight(&s, id, composer);
}
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine"})).unwrap();
s.execute("text.setStyle", &json!({"id": id.0, "justify": "justifyAll"})).unwrap();
assert!(text(&s, id).paragraph_styles().iter().all(|p| p.composer == Composer::SingleLine && p.justify == Justify::JustifyAll));
assert_tight(&s, id, "justified");
}
#[test]
fn auto_height_x_vertical_align() {
// An Auto Size frame has no space to spare: every alignment sets the lines as Top does, and
// the frame is as tall as with Top.
let mut s = session();
let id = area(&mut s, 160.0, 100.0, STORY, json!({"fit": "autoHeight"}));
let top_frame = frame(&s, id);
let top = lay(&text(&s, id));
for a in ["center", "bottom", "justify"] {
s.execute("text.areaOptions", &json!({"verticalAlign": a})).unwrap();
assert_eq!(frame(&s, id), top_frame, "{a}");
let l = lay(&text(&s, id));
for (li, l0) in l.lines.iter().zip(&top.lines) {
assert!((li.baseline - l0.baseline).abs() < 1e-6, "{a}: {} vs {}", li.baseline, l0.baseline);
}
assert_tight(&s, id, a);
}
// Editing with the alignment on keeps the frame tight.
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 0, "insert": format!("{STORY} ")})).unwrap();
assert_eq!(text(&s, id).area.vertical_align, VerticalAlign::Justify);
assert_tight(&s, id, "longer, justified");
}
#[test]
fn shrink_text_x_inline_graphics_and_paragraphs() {
let mut s = session();
circle_symbol(&mut s, "Dot", 8.0);
let id = area(&mut s, 160.0, 60.0, "Short rules.\nFlavor.", json!({"fit": "shrinkText", "fitMinPercent": 20}));
assert_eq!(query(&mut s)["fitScale"], 1.0);
// Inline art and per-paragraph spacing push it over; shrinking makes it fit.
s.execute("text.setFormat", &json!({"ids": [id.0], "spaceBefore": 12, "start": 13, "end": 13})).unwrap();
for i in 0..10 {
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Dot", "scale": 1.0 + i as f64 * 0.2})).unwrap();
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 0, "insert": "Add "})).unwrap();
}
let q = query(&mut s);
assert_eq!(q["overflow"], false, "{q}");
let f = q["fitScale"].as_f64().unwrap();
assert!((0.2..1.0).contains(&f), "{f}");
let t = text(&s, id);
assert_eq!(t.paragraph_count(), 2);
assert_eq!(t.para_at(1).space_before, 12.0, "inserting in the first paragraph keeps the second's attributes");
assert_eq!(t.runs[0].style.size, 12.0, "the stored size stays");
let l = lay(&t);
assert_eq!(l.inlines.len(), 10);
assert!(l.inlines.iter().all(|i| i.bounds.height() < 12.0 * 2.8 * f + 1e-6));
// Undo walks the fit back up.
for _ in 0..20 {
undo(&mut s);
}
assert_eq!(query(&mut s)["fitScale"], 1.0);
}
#[test]
fn paragraph_attrs_x_inline_editing() {
// An inline graphic opening a paragraph belongs to it: inserting it keeps the paragraph's
// attributes, deleting it with the paragraph break merges into the paragraph before.
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(&mut s, 300.0, 200.0, "Rules\nFlavor", json!({}));
s.execute("text.setStyle", &json!({"id": id.0, "justify": "center", "start": 6, "end": 6})).unwrap();
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine", "start": 6, "end": 6})).unwrap();
s.execute("text.insertInline", &json!({"id": id.0, "at": 6, "symbol": "Tap"})).unwrap();
let t = text(&s, id);
assert_eq!(t.plain_text(), format!("Rules\n{INLINE_CHAR}Flavor"));
assert_eq!((t.para_at(0).justify, t.para_at(1).justify), (Justify::Auto, Justify::Center));
assert_eq!(t.para_at(1).composer, Composer::SingleLine);
// The art's line is centred.
let l = lay(&t);
let g = &l.glyphs[l.inlines[0].glyph];
let line = &l.lines[g.line];
assert!(((line.x0 + line.x1) * 0.5 - 150.0).abs() < 1e-6, "centred in the 300 pt frame: {line:?}");
assert!((l.inlines[0].bounds.x0 - g.origin.x).abs() < 1e-6);
// Return just before the art: the new paragraph (holding the art) continues the centred one.
s.execute("text.editRange", &json!({"id": id.0, "start": 6, "end": 6, "insert": "Text\n"})).unwrap();
let t = text(&s, id);
assert_eq!(t.paragraph_styles().iter().map(|p| p.justify).collect::<Vec<_>>(), [Justify::Auto, Justify::Center, Justify::Center]);
undo(&mut s);
// Delete the break and the art together: one paragraph, the first one's attributes.
let end = 6 + INLINE_CHAR.len_utf8();
s.execute("text.editRange", &json!({"id": id.0, "start": 5, "end": end})).unwrap();
let t = text(&s, id);
assert_eq!(t.plain_text(), "RulesFlavor");
assert!(t.paras.is_empty() && t.para.justify == Justify::Auto && t.para.composer == Composer::EveryLine);
assert!(t.runs.iter().all(|r| r.inline.is_none()));
undo(&mut s);
let t = text(&s, id);
assert_eq!(t.plain_text(), format!("Rules\n{INLINE_CHAR}Flavor"));
assert_eq!(t.para_at(1).justify, Justify::Center);
assert_eq!(t.runs.iter().filter(|r| r.inline.is_some()).count(), 1);
}
#[test]
fn vertical_align_x_inline_graphics_in_the_document() {
// The art the renderer draws (the layout's inline placements) moves with centred lines.
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(&mut s, 300.0, 200.0, "Add one mana.", json!({}));
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap();
let top = lay(&text(&s, id));
s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap();
let l = lay(&text(&s, id));
let d = l.lines[0].baseline - top.lines[0].baseline;
assert!(d > 50.0, "{d}");
assert!((l.inlines[0].bounds.y0 - top.inlines[0].bounds.y0 - d).abs() < 1e-6, "{:?} vs {:?}", l.inlines[0].bounds, top.inlines[0].bounds);
// The cached bounds (hit testing, selection) include the moved art.
let cached = text(&s, id).cached_bounds.unwrap();
assert!(cached.contains(l.inlines[0].bounds.center()), "{cached:?}");
}
#[test]
fn every_feature_saves_and_reopens() {
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(
&mut s,
220.0,
70.0,
&format!(": Add one mana of any color. {STORY}\n{STORY}"),
json!({"verticalAlign": "center", "fit": "shrinkText", "fitMinPercent": 30}),
);
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 0.8, "shift": 0.5})).unwrap();
let flavor = text(&s, id).plain_text().find('\n').unwrap() + 1;
s.execute("text.setFormat", &json!({"ids": [id.0], "spaceBefore": 8, "composer": "singleLine", "start": flavor, "end": flavor})).unwrap();
s.execute("text.setStyle", &json!({"id": id.0, "justify": "justifyAll", "start": flavor, "end": flavor})).unwrap();
s.execute("text.setStyle", &json!({"id": id.0, "tracking": 20})).unwrap();
let t = text(&s, id);
let l = lay(&t);
assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale);
assert_eq!(l.inlines.len(), 1);
let doc = s.doc().unwrap().doc.clone();
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let NodeKind::Text(t2) = &back.node(id).unwrap().kind else { panic!("not text") };
let mut t2 = (**t2).clone();
// Resolved art bounds and layout caches aren't saved: resolve them as opening does.
back.resolve_text_inline(&mut t2);
assert_eq!(t2.runs, t.runs);
assert_eq!(t2.paragraph_styles(), t.paragraph_styles());
assert_eq!(t2.area, t.area);
let l2 = lay(&t2);
assert_eq!((l2.fit_scale, l2.lines.len()), (l.fit_scale, l.lines.len()));
assert_eq!(l2.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>(), l.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>());
}
+1
View File
@@ -223,6 +223,7 @@ impl Session {
anchor_path_labels: self.prefs.anchor_path_labels,
measurement_labels: self.prefs.measurement_labels,
transform_tools_guides: self.prefs.transform_tools_guides,
spacing_guides: self.prefs.spacing_guides,
snapping_tolerance: self.prefs.snapping_tolerance,
construction_angles: if self.prefs.construction_guides {
vectorcraft_tools::guides::construction_angles(&self.prefs.construction_angles)
+10 -4
View File
@@ -98,13 +98,19 @@ fn known_bug(id: &str, p: &Value) -> bool {
KNOWN_BUGS.iter().any(|(c, k)| *c == id && p.get(*k).is_some())
}
/// Regression: huge column counts used to panic with `capacity overflow`.
/// Regression: huge column counts used to panic with `capacity overflow`; in every layout and
/// order (#681), with huge and negative spacing too.
#[test]
fn artboard_rearrange_huge_columns() {
for fx in Fixture::ALL {
for cols in [json!(u64::MAX), json!(1e308)] {
let p = json!({ "columns": cols });
assert_eq!(probe(fx, "artboard.rearrange", &p), None);
for layout in ["gridByRow", "gridByColumn", "row", "column"] {
for order in ["leftToRight", "rightToLeft"] {
for (cols, spacing) in [(json!(u64::MAX), json!(1e308)), (json!(1e308), json!(-1e308)), (json!(0), json!(0)), (json!(-5), json!(20))]
{
let p = json!({ "layout": layout, "order": order, "columns": cols, "spacing": spacing });
assert_eq!(probe(fx, "artboard.rearrange", &p), None);
}
}
}
}
}
+44 -2
View File
@@ -592,6 +592,8 @@ struct Builder<'p> {
image_keys: HashMap<u128, (String, u32, u32)>,
/// The images kept with their CMYK samples ([`crate::import_image`]).
cmyk_keys: HashSet<u128>,
/// Mask keys of CMYK images whose mask turned out to hide nothing.
opaque: HashSet<u128>,
warnings: Vec<String>,
/// Fonts by cache key → base font name (from [`scan_page`]).
fonts: HashMap<u128, String>,
@@ -743,6 +745,7 @@ impl<'p> Builder<'p> {
images: HashMap::new(),
image_keys: HashMap::new(),
cmyk_keys: HashSet::new(),
opaque: HashSet::new(),
warnings: vec![],
fonts: HashMap::new(),
font_names: HashMap::new(),
@@ -1146,6 +1149,40 @@ impl<'p> Builder<'p> {
}
fn add_image(&mut self, key: u128, make: impl FnOnce() -> Option<(ImageBlob, u32, u32)>, xf: Affine) {
self.add_image_masked(key, make, xf, None);
}
/// An image's alpha (its soft mask, stencil mask or colour key, at its own resolution) as a
/// greyscale image over the image's `w` × `h` pixels (`transform`): its opacity mask. `None`
/// when it masks nothing.
fn alpha_mask(&mut self, key: u128, r: &hayro_interpret::RasterImage<'_>, w: u32, h: u32, transform: Affine) -> Option<OpacityMask> {
let mkey = key ^ 0x5_3a5c;
if self.opaque.contains(&mkey) {
return None;
}
let (k, mw, mh) = if let Some(v) = self.image_keys.get(&mkey).cloned() {
v
} else {
let mut alpha = None;
r.with_rgba(|_, a| alpha = a, None);
let Some(a) = alpha.filter(|a| a.data.iter().any(|v| *v < 255)) else {
self.opaque.insert(mkey);
return None;
};
let mut png = Vec::new();
image::GrayImage::from_raw(a.width, a.height, a.data)?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let blob = ImageBlob::new("image/png", png);
let k = blob.content_key();
self.images.insert(k.clone(), blob);
self.image_keys.insert(mkey, (k.clone(), a.width, a.height));
(k, a.width, a.height)
};
let xf = transform * Affine::scale_non_uniform(f64::from(w) / f64::from(mw.max(1)), f64::from(h) / f64::from(mh.max(1)));
let art = Node::new(self.id(), NodeKind::Image(ImageObject { key: k, width: mw, height: mh, xf, link: None, placement: Default::default() }));
Some(OpacityMask::new(art, true))
}
fn add_image_masked(&mut self, key: u128, make: impl FnOnce() -> Option<(ImageBlob, u32, u32)>, xf: Affine, mask: Option<OpacityMask>) {
let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() {
v
} else {
@@ -1160,7 +1197,9 @@ impl<'p> Builder<'p> {
(k, w, h)
};
let id = self.id();
self.push_node(Node::new(id, NodeKind::Image(ImageObject { key: k, width: w, height: h, xf, link: None, placement: Default::default() })));
let mut n = Node::new(id, NodeKind::Image(ImageObject { key: k, width: w, height: h, xf, link: None, placement: Default::default() }));
n.mask = mask.map(Box::new);
self.push_node(n);
}
/// Mesh shadings filling `region` (document space): gradient meshes, clipped to the region
@@ -1542,7 +1581,10 @@ impl<'a> Device<'a> for Builder<'_> {
};
if known || cmyk.is_some() {
self.cmyk_keys.insert(key);
return self.add_image(key, || cmyk.map(|blob| (blob, w, h)), transform);
// Its mask (read by the interpreter, whatever its kind) becomes an opacity
// mask, so the inks stay as they are.
let mask = if crate::import_image::has_mask(st) { self.alpha_mask(key, &r, w, h, transform) } else { None };
return self.add_image_masked(key, || cmyk.map(|blob| (blob, w, h)), transform, mask);
}
// JPEG passthrough for plain DeviceRGB/DeviceGray DCT images.
let dict = st.dict();
+9 -5
View File
@@ -2,7 +2,9 @@
//! four components. A JPEG whose Decode array inverts its samples (Adobe's CMYK JPEGs, the
//! convention JPEG readers and the PDF writer take a CMYK JPEG to follow) is kept as it is; any
//! other is decoded, its Decode array applied, and stored as a CMYK TIFF
//! ([`ImageBlob::cmyk_tiff`]). Every other image is read as RGB by the interpreter.
//! ([`ImageBlob::cmyk_tiff`]). A mask (`/SMask`, `/Mask`) doesn't change that: the importer
//! carries it as the image's opacity mask ([`has_mask`]). Every other image is read as RGB by the
//! interpreter.
use hayro_syntax::Filter;
use hayro_syntax::object::stream::ImageDecodeParams;
@@ -11,7 +13,6 @@ use vectorcraft_doc::ImageBlob;
use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components};
/// A CMYK image read as RGB: why.
pub(crate) const MASKED: &str = "CMYK images with a mask were imported in RGB";
pub(crate) const UNREAD: &str = "CMYK images whose samples couldn't be read in CMYK were imported in RGB";
/// The Decode array of a JPEG kept as it is.
@@ -57,9 +58,6 @@ pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result<Option<Im
if !cmyk_space(d) {
return Ok(None);
}
if d.contains_key(b"SMask") || d.contains_key(b"Mask") {
return Err(MASKED);
}
let ranges = decode_ranges(d);
let filters = st.filters();
if ranges == INVERTED && matches!(filters.as_slice(), [Filter::DctDecode]) {
@@ -91,3 +89,9 @@ pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result<Option<Im
.collect();
Inks::new(width, height, inks).and_then(|i| ImageBlob::cmyk_tiff(&i)).map(Some).ok_or(UNREAD)
}
/// Does the image carry its own transparency (a soft mask, a stencil mask or a colour key)?
pub(crate) fn has_mask(st: &Stream<'_>) -> bool {
let d = st.dict();
d.contains_key(b"SMask") || d.contains_key(b"Mask") || d.get::<u8>(b"SMaskInData").is_some_and(|v| v != 0)
}
+5
View File
@@ -375,6 +375,11 @@ impl Dest {
};
Color::Cmyk { c, m, y, k }
}
// CMYK straight into the destination RGB (the destination shares the source's CMYK).
(_, Color::Cmyk { c, m, y, k }) => {
let [r, g, b] = self.cms.cmyk_to_rgb([*c, *m, *y, *k], intent);
Color::Rgb { r, g, b }
}
_ => {
let [r, g, b] = self.cms.srgb_to_rgb(source.display_rgb(c));
Color::Rgb { r, g, b }
+84 -7
View File
@@ -212,19 +212,96 @@ fn other_cmyk_images_keep_their_ink_amounts() {
}
#[test]
fn cmyk_images_with_a_mask_or_odd_samples_open_in_rgb_with_a_warning() {
let inks = flat([0, 102, 255, 0], 4);
let mask = stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[255, 128, 255, 128]);
let source = pdf_with_images(&[(cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode"), crate::output::deflate(&inks).unwrap())], &[mask]);
let r = import_with_report(&source, &ImportOptions::default()).unwrap();
assert_eq!(blobs(&r.document)[0].mime, "image/png");
assert!(r.warnings.iter().any(|w| w == crate::import_image::MASKED), "{:?}", r.warnings);
fn cmyk_images_with_odd_samples_open_in_rgb_with_a_warning() {
let four_bits = cmyk_dict(2, 2, "").replace("/BitsPerComponent 8", "/BitsPerComponent 4");
let r = import_with_report(&pdf_with_images(&[(four_bits, vec![0x0F; 8])], &[]), &ImportOptions::default()).unwrap();
assert_eq!(blobs(&r.document)[0].mime, "image/png");
assert!(r.warnings.iter().any(|w| w == crate::import_image::UNREAD), "{:?}", r.warnings);
}
/// An opacity mask's image: its blob and pixel size.
type MaskImage<'d> = (&'d ImageBlob, u32, u32);
/// The image nodes on the first layer: each one's blob and its opacity mask's image, if it has one.
fn masked(d: &Document) -> Vec<(&ImageBlob, Option<MaskImage<'_>>)> {
let NodeKind::Layer { children, .. } = &d.layers[0].kind else { panic!() };
children
.iter()
.filter_map(|n| {
let NodeKind::Image(im) = &n.kind else { return None };
let mask = n.mask.as_ref().map(|m| match &m.art.kind {
NodeKind::Image(a) => (&d.images[&a.key], a.width, a.height),
other => panic!("mask art is an image: {other:?}"),
});
Some((&d.images[&im.key], mask))
})
.collect()
}
#[test]
fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() {
let inks = flat([0, 102, 255, 0], 4);
let z = |data: &[u8]| crate::output::deflate(data).unwrap();
// Object 6 (the first after the two images): a soft mask; image 2 a colour key masking its
// first two pixels.
let smask = stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[255, 128, 255, 128]);
let keyed: Vec<u8> = [[10, 20, 30, 40], [10, 20, 30, 40], [0, 102, 255, 0], [0, 102, 255, 0]].concat();
let images = [
(cmyk_dict(2, 2, "/SMask 7 0 R /Filter /FlateDecode"), z(&inks)),
(cmyk_dict(2, 2, "/Mask [10 10 20 20 30 30 40 40] /Filter /FlateDecode"), z(&keyed)),
];
let source = pdf_with_images(&images, &[smask]);
let r = import_with_report(&source, &ImportOptions::default()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let m = masked(&r.document);
assert_eq!(m.len(), 2);
for ((blob, mask), (want, alpha)) in m.iter().zip([(&inks, [255, 128, 255, 128]), (&keyed, [0, 0, 255, 255])]) {
assert_eq!(blob.mime, "image/tiff");
assert!(close(&blob.cmyk().unwrap().data, want, 0), "the inks as they were");
let (mblob, mw, mh) = mask.expect("an opacity mask");
assert_eq!((mw, mh), (2, 2));
let grey = image::load_from_memory(&mblob.bytes).unwrap().to_luma8();
assert_eq!(grey.into_raw(), alpha, "the mask's values");
}
// The mask art covers the image exactly.
let NodeKind::Layer { children, .. } = &r.document.layers[0].kind else { panic!() };
let img = children.iter().find(|n| matches!(n.kind, NodeKind::Image(_))).unwrap();
assert_eq!(img.geometric_bounds(), img.mask.as_ref().unwrap().art.geometric_bounds());
// Written as CMYK with the mask in grey; it opens with the same inks.
let out = export_with_report(&r.document, &opts(json!({}))).unwrap();
let w = written(&out.bytes);
assert!(w.iter().filter(|w| w.space == "DeviceCMYK").count() == 2 && w.iter().any(|w| w.space == "DeviceGray"), "{w:?}");
let back = import_with_report(&out.bytes, &ImportOptions::default()).unwrap();
let inked: Vec<Vec<u8>> = all_images(&back.document).iter().filter_map(|b| b.cmyk()).map(|i| i.data).collect();
assert!(inked.iter().any(|d| close(d, &inks, 3)) && inked.iter().any(|d| close(d, &keyed, 3)), "{:?}", back.warnings);
// A mask that hides nothing adds none.
let opaque = stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[255; 4]);
let r = import_with_report(
&pdf_with_images(&[(cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode"), z(&inks))], &[opaque]),
&ImportOptions::default(),
)
.unwrap();
assert!(masked(&r.document)[0].1.is_none());
}
/// Every image blob a document's art uses (mask art included).
fn all_images(d: &Document) -> Vec<&ImageBlob> {
let mut keys = vec![];
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
keys.push(im.key.clone());
}
if let Some(m) = &n.mask {
m.art.walk(&mut |a| {
if let NodeKind::Image(im) = &a.kind {
keys.push(im.key.clone());
}
});
}
});
keys.iter().filter_map(|k| d.images.get(k)).collect()
}
/// A document with CMYK image `blob` of `w` × `h` pixels placed 40 pt wide.
fn image_doc(blob: ImageBlob, w: u32, h: u32) -> Document {
let mut d = Document::new_with_mode(100.0, 100.0, ColorMode::Cmyk);
+7 -1
View File
@@ -103,6 +103,9 @@ pub struct RenderOptions {
/// Screen view: Image Trace objects draw as their View asks (outlines, the source image…);
/// off, they draw their tracing result, as exports and printing do.
pub trace_views: bool,
/// Images are sampled smoothly when scaled or rotated; off, each pixel takes its nearest image
/// pixel (Pixel Preview with File Handling › Display Bitmaps as Anti-aliased Images off).
pub smooth_images: bool,
}
/// How edges are rasterized (raster export option).
@@ -169,6 +172,7 @@ impl Default for RenderOptions {
anti_alias: AntiAlias::Art,
progressive_placed: false,
trace_views: false,
smooth_images: true,
}
}
}
@@ -1419,7 +1423,9 @@ impl Renderer {
let pm = if outline { pm } else { self.ink_image(&cache_key, &pm, f.ink, f.doc.images.get(&im.key)) };
let sx = im.width as f64 / pm.width().max(1) as f64;
let sy = im.height as f64 / pm.height().max(1) as f64;
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler: peniko::ImageSampler::default() });
let quality = if f.opts.smooth_images { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low };
let sampler = peniko::ImageSampler { quality, ..Default::default() };
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler });
match area {
Some((bp, rule)) => {
ctx.set_transform(f.view);
+23
View File
@@ -362,3 +362,26 @@ fn invalid_dash_pattern_strokes_solid() {
assert_eq!(img.pixels, solid.pixels, "dash {pattern:?}");
}
}
/// An image drawn larger than its pixels samples smoothly, or with `smooth_images` off each screen
/// pixel takes its nearest image pixel (Pixel Preview with File Handling › Display Bitmaps as
/// Anti-aliased Images off, #394).
#[test]
fn images_take_their_nearest_pixel_without_smoothing() {
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
let img = image::RgbaImage::from_fn(2, 1, |x, _| image::Rgba(if x == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut d = Document::new(40.0, 20.0);
d.images.insert("bw".into(), ImageBlob::new("image/png", png));
let id = d.alloc_id();
let im = ImageObject { key: "bw".into(), width: 2, height: 1, xf: Affine::scale(20.0), link: None, placement: Default::default() };
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(im))).unwrap();
// How many pixels across the image are neither black nor white.
let greys = |smooth_images| {
let r = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &RenderOptions { smooth_images, ..Default::default() });
(0..40).filter(|x| (16..240).contains(&r.pixel(*x, 10)[0])).count()
};
assert!(greys(true) >= 4, "smooth: a ramp from black to white");
assert_eq!(greys(false), 0, "nearest: black, then white");
}
+26
View File
@@ -878,6 +878,31 @@ pub fn set_platform_font_files(list: PlatformFontFiles) {
let _ = list;
}
/// Folders the user adds to the font scan (Preferences › Type › Additional Fonts Folder, #683),
/// read with their subfolders after the platform's.
#[cfg(not(target_arch = "wasm32"))]
static USER_FONT_DIRS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());
/// Have [`system_font_dirs`] also read `dirs` (#683), so the fonts in them are listed and used as
/// if installed. The next check for installed fonts ([`FontDb::installed_fonts_changed`]) then
/// reports the change, and a scan catalogs them.
pub fn set_user_font_dirs(dirs: Vec<PathBuf>) {
#[cfg(not(target_arch = "wasm32"))]
{
*USER_FONT_DIRS.write().unwrap_or_else(std::sync::PoisonError::into_inner) = dirs;
}
#[cfg(target_arch = "wasm32")]
let _ = dirs;
}
/// The folders [`set_user_font_dirs`] added (none on wasm).
pub fn user_font_dirs() -> Vec<PathBuf> {
#[cfg(not(target_arch = "wasm32"))]
return USER_FONT_DIRS.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
#[cfg(target_arch = "wasm32")]
Vec::new()
}
/// The platform's font folders (the system's and the user's) and the font files known to it
/// outside them (on Windows those registered with it, and those [`set_platform_font_files`]
/// lists), scanned by [`FontDb::global`].
@@ -926,6 +951,7 @@ pub fn system_font_dirs() -> Vec<PathBuf> {
let files = fonts_outside(list(), &dirs);
dirs.extend(files);
}
dirs.extend(user_font_dirs());
dirs
}
+21 -4
View File
@@ -206,14 +206,17 @@ fn shrink_to_fit(db: &FontDb, t: &TextObject, opts: &LayoutOptions, min: f64) ->
Some(best.unwrap_or_else(|| at(lo)))
}
/// `t` with every run's size, explicit leading and baseline shift scaled by `f` (auto leading
/// follows the size; paragraph spacing stays).
/// `t` with every run's size, explicit leading and baseline shift scaled by `f`, inline art's own
/// shift included (auto leading and the art's size follow the size; paragraph spacing stays).
fn scaled(t: &TextObject, f: f64) -> TextObject {
let mut s = t.clone();
for r in &mut s.runs {
r.style.size *= f;
r.style.leading = r.style.leading.map(|l| l * f);
r.style.baseline_shift *= f;
if let Some(a) = &mut r.inline {
a.baseline_shift *= f;
}
}
s
}
@@ -595,6 +598,15 @@ fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, re
g.origin.y += d;
}
}
// Inline art moves with its glyph's line.
for i in &mut cx.out.inlines {
let d = cx.out.glyphs.get(i.glyph).and_then(|g| offs.get(g.line)).copied().unwrap_or(0.0);
if d != 0.0 {
let m = Affine::translate((0.0, d));
i.xf = m * i.xf;
i.bounds = m.transform_rect_bbox(i.bounds);
}
}
return;
}
let laid_out = |out: &TextLayout| out.lines.last().map_or(0, |l| l.end);
@@ -624,12 +636,17 @@ fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, re
return;
}
let before = laid_out(&cx.out);
let prev = (std::mem::take(&mut cx.out.glyphs), std::mem::take(&mut cx.out.lines), std::mem::replace(&mut cx.out.overflow, false));
let prev = (
std::mem::take(&mut cx.out.glyphs),
std::mem::take(&mut cx.out.lines),
std::mem::take(&mut cx.out.inlines),
std::mem::replace(&mut cx.out.overflow, false),
);
flow(cx, paras, t, Some(regions));
if laid_out(&cx.out) < before {
// Text no longer fits (lines got narrower, or flow around a wrap object): undo the
// pass and try a smaller step.
(cx.out.glyphs, cx.out.lines, cx.out.overflow) = prev;
(cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.overflow) = prev;
for (r, (shift, gap)) in regions.iter_mut().zip(saved) {
r.shift = shift;
r.gap = gap;
+4 -2
View File
@@ -25,8 +25,8 @@ pub mod thread;
pub use craft_fonts::{CRAFT_FONTS, CraftFont};
pub use features::{LIGATURE_TRACKING_LIMITS, OtFeatures, explicit_ligatures, ligatures_suppressed_by};
pub use fontdb::{
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, set_platform_font_files, style_weight,
system_font_dirs,
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, set_platform_font_files, set_user_font_dirs,
style_weight, system_font_dirs, user_font_dirs,
};
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
pub use layout::{layout, layout_with};
@@ -502,6 +502,8 @@ mod tests;
#[cfg(test)]
mod tests_bidi;
#[cfg(test)]
mod tests_combos;
#[cfg(test)]
mod tests_embed;
#[cfg(test)]
mod tests_fit;
+574
View File
@@ -0,0 +1,574 @@
//! The text engine's newer features combined, two at a time and all together: ligatures under
//! tracking, the paragraph composer, area type vertical alignment, Shrink Text to Fit,
//! per-paragraph attributes and inline graphics. Each feature has its own tests; these check that
//! one doesn't undo or skip another (as vertical alignment once left inline art behind).
use super::*;
use kurbo::Shape;
use vectorcraft_doc::{AreaFit, CharStyle, Composer, InlineArt, Justify, TextKind, TextRun, VerticalAlign};
use vectorcraft_geom::PathData;
const COPY: &str = "Typography is the craft of arranging type to make written language legible, readable and appealing when displayed. \
The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing and letter spacing.";
/// Words full of `fi` (Source Serif 4 ligates it).
const FI: &str = "fine fish finish first in fifty fields of fireflies, a fitting finale for the final fiddler";
/// Two lines that single-line and every-line composers break differently (see
/// `every_line_composer_balances_ragged_lines`).
const RAG: &str = "Destroy all creatures with toughness X or less.";
fn db() -> &'static FontDb {
FontDb::global()
}
fn sans(size: f64) -> CharStyle {
CharStyle { size, ..CharStyle::default() }
}
fn serif(size: f64, tracking: f64) -> CharStyle {
CharStyle { font_family: "Source Serif 4".into(), size, tracking, ..CharStyle::default() }
}
fn run(text: &str, style: CharStyle) -> TextRun {
TextRun::new(text, style)
}
/// A square symbol, `scale` × the run's size tall, raised `shift` points.
fn art(scale: f64, shift: f64) -> InlineArt {
InlineArt { scale, baseline_shift: shift, bounds: Some(Rect::new(-5.0, -5.0, 5.0, 5.0)), ..InlineArt::new("sym") }
}
fn sym(scale: f64, shift: f64, style: CharStyle) -> TextRun {
TextRun::inline(art(scale, shift), style)
}
/// Area type in `frame` holding `runs`.
fn area(runs: Vec<TextRun>, frame: Rect) -> TextObject {
let mut t = TextObject::point(Point::ZERO, "", sans(12.0));
t.runs = runs;
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) };
t.xf = Affine::IDENTITY;
t
}
/// `t` as Shrink Text to Fit lays it out at factor `f`, without fitting: sizes, explicit leading
/// and baseline shifts scaled (inline art's own shift too), paragraph spacing kept.
fn scaled_by(t: &TextObject, f: f64) -> TextObject {
let mut s = t.clone();
s.area.fit = AreaFit::None;
for r in &mut s.runs {
r.style.size *= f;
r.style.leading = r.style.leading.map(|l| l * f);
r.style.baseline_shift *= f;
if let Some(a) = &mut r.inline {
a.baseline_shift *= f;
}
}
s
}
fn line_texts(t: &TextObject, l: &TextLayout) -> Vec<String> {
let text = t.plain_text();
l.lines.iter().map(|li| text[li.start..li.end].trim_end().to_string()).collect()
}
/// Ligature clusters: glyphs standing for more than one character.
fn ligatures(l: &TextLayout) -> usize {
l.glyphs.iter().filter(|g| g.len > 1 && !g.outline.elements().is_empty()).count()
}
/// Every inline graphic drawn once, where its glyph is: left edge on the glyph's origin, the
/// scaled height, centred half the (scaled) cap height above the glyph's baseline plus its own
/// (scaled) shift.
fn assert_inlines_on_their_glyphs(t: &TextObject, l: &TextLayout, what: &str) {
let want = t.runs.iter().filter(|r| r.inline.is_some()).count();
assert_eq!(l.inlines.len(), want, "{what}: one placement per inline run");
let mut glyphs: Vec<usize> = l.inlines.iter().map(|i| i.glyph).collect();
glyphs.dedup();
assert_eq!(glyphs.len(), want, "{what}: no inline drawn twice");
for i in &l.inlines {
let g = &l.glyphs[i.glyph];
assert_eq!(g.run, i.run, "{what}");
let r = &t.runs[i.run];
let a = r.inline.as_ref().unwrap();
let size = r.style.size * l.fit_scale;
let face = db().face(&r.style.font_family, &r.style.font_style).unwrap();
let cap = face.cap_height * size / face.upem;
let b = i.bounds;
assert!((b.height() - a.scale * size).abs() < 1e-6, "{what}: height {} vs {}", b.height(), a.scale * size);
assert!((b.x0 - g.origin.x).abs() < 1e-6, "{what}: {b:?} vs origin {:?}", g.origin);
let centre = g.origin.y - cap * 0.5 - a.baseline_shift * l.fit_scale;
assert!((b.center().y - centre).abs() < 1e-6, "{what}: centre {} vs {centre} (line {})", b.center().y, g.line);
assert!(l.lines[g.line].glyph_start <= i.glyph && i.glyph < l.lines[g.line].glyph_end, "{what}");
assert!(l.bounds.contains(b.center()), "{what}: layout bounds {:?} miss {b:?}", l.bounds);
}
}
/// Space left below the last line of a one-cell frame.
fn slack(l: &TextLayout, frame: Rect) -> f64 {
let last = l.lines.last().unwrap();
frame.y1 - (last.baseline + last.descent)
}
fn baselines(l: &TextLayout) -> Vec<f64> {
l.lines.iter().map(|li| li.baseline).collect()
}
// ---------- ligatures under tracking × … ----------
#[test]
fn ligatures_x_composer() {
// Justified (where every-line spreads word space) and ragged, with tracking inside the limits
// (kept) and letterspaced (dropped), whichever composer breaks the lines.
for justify in [Justify::Left, Justify::JustifyLeft] {
for (tracking, kept) in [(0.0, true), (20.0, true), (100.0, false)] {
let mut counts = vec![];
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut t = area(vec![run(&FI.repeat(3), serif(12.0, tracking))], Rect::new(0.0, 0.0, 170.0, 1000.0));
t.para.justify = justify;
t.para.composer = composer;
let l = layout(db(), &t);
assert!(l.lines.len() > 3, "several lines to compose");
counts.push(ligatures(&l));
}
assert_eq!(counts[0], counts[1], "{justify:?} {tracking}: composers shape alike");
assert_eq!(counts[0] > 0, kept, "{justify:?} {tracking}: {counts:?}");
}
}
}
#[test]
fn ligatures_x_vertical_align() {
let frame = Rect::new(0.0, 0.0, 200.0, 400.0);
for tracking in [20.0, 100.0] {
let mut t = area(vec![run(FI, serif(12.0, tracking))], frame);
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
t.area.vertical_align = a;
let l = layout(db(), &t);
let gids = |l: &TextLayout| l.glyphs.iter().map(|g| (g.gid, g.byte)).collect::<Vec<_>>();
assert_eq!(gids(&l), gids(&top), "{tracking} {a:?}: moving lines doesn't reshape them");
assert!(l.lines[0].baseline > top.lines[0].baseline + 1.0 || a == VerticalAlign::Justify, "{a:?}");
}
}
}
#[test]
fn ligatures_x_shrink_text() {
// Tracking is in 1/1000 em, so scaling the size doesn't move it across the limits.
let frame = Rect::new(0.0, 0.0, 150.0, 60.0);
for (tracking, features, kept) in [(40.0, vec![], true), (100.0, vec![], false), (100.0, vec!["liga".to_string()], true)] {
let st = CharStyle { features, ..serif(14.0, tracking) };
let mut t = area(vec![run(&FI.repeat(2), st)], frame);
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{tracking}: {}", l.fit_scale);
assert_eq!(ligatures(&l) > 0, kept, "{tracking}");
assert_eq!(ligatures(&l), ligatures(&layout(db(), &scaled_by(&t, l.fit_scale))), "{tracking}");
}
}
#[test]
fn ligatures_x_paragraph_attrs() {
// Paragraph attributes don't touch shaping: a centred, indented, every-line paragraph keeps
// its ligatures and a letterspaced run in the next paragraph loses them.
let mut t = area(vec![run(&format!("{FI}\n"), serif(12.0, 10.0)), run(FI, serif(12.0, 120.0))], Rect::new(0.0, 0.0, 240.0, 600.0));
let mut second = t.para.clone();
second.justify = Justify::Center;
second.left_indent = 20.0;
second.space_before = 12.0;
t.set_paragraph_styles(vec![t.para.clone(), second]);
let l = layout(db(), &t);
let split = FI.len() + 1;
let ligs = |first: bool| l.glyphs.iter().filter(|g| g.len > 1 && (g.byte < split) == first).count();
assert!(ligs(true) > 0, "tracking 10 keeps them");
assert_eq!(ligs(false), 0, "tracking 120 drops them");
}
#[test]
fn ligatures_x_inline_graphics() {
// An inline graphic between ligated words neither breaks their ligatures nor takes them: its
// own letterspaced run tracks the art without touching its neighbours.
let st = serif(14.0, 0.0);
let runs = vec![run("fine fish ", st.clone()), sym(1.0, 0.0, serif(14.0, 200.0)), run(" first fifty", st.clone())];
let t = area(runs, Rect::new(0.0, 0.0, 400.0, 100.0));
let l = layout(db(), &t);
let without = area(vec![run("fine fish ", st.clone()), run(" first fifty", st.clone())], Rect::new(0.0, 0.0, 400.0, 100.0));
assert_eq!(ligatures(&l), ligatures(&layout(db(), &without)), "the same ligatures as without the art");
assert!(ligatures(&l) >= 4, "fi in fine, fish, first and fifty");
assert_inlines_on_their_glyphs(&t, &l, "between ligatures");
let g = &l.glyphs[l.inlines[0].glyph];
assert!((g.advance - (14.0 + 200.0 / 1000.0 * 14.0)).abs() < 1e-6, "art width plus its tracking: {}", g.advance);
}
// ---------- composer × … ----------
#[test]
fn composer_x_vertical_align() {
let w = natural_width(RAG, 12.0) * 0.9;
let frame = Rect::new(0.0, 0.0, w, 200.0);
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut t = area(vec![run(RAG, sans(12.0))], frame);
t.para.composer = composer;
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert_eq!(line_texts(&t, &l), line_texts(&t, &top), "{composer:?} {a:?}: the same breaks");
let want = match a {
VerticalAlign::Center => slack(&top, frame) * 0.5,
_ => slack(&top, frame),
};
let moved = l.lines.last().unwrap().baseline - top.lines.last().unwrap().baseline;
assert!((moved - want).abs() < 1e-6, "{composer:?} {a:?}: last line moved {moved}, want {want}");
}
}
// And the two composers still differ there.
let breaks = |c: Composer| {
let mut t = area(vec![run(RAG, sans(12.0))], frame);
t.para.composer = c;
t.area.vertical_align = VerticalAlign::Center;
line_texts(&t, &layout(db(), &t))
};
assert_ne!(breaks(Composer::SingleLine), breaks(Composer::EveryLine));
}
#[test]
fn composer_x_shrink_text() {
// Each composer shrinks to the largest size at which its own breaks fit.
for justify in [Justify::Left, Justify::JustifyLeft] {
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut t = area(vec![run(COPY, sans(14.0))], Rect::new(0.0, 0.0, 180.0, 90.0));
t.para.composer = composer;
t.para.justify = justify;
t.area.fit = AreaFit::ShrinkText { min_percent: 20.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{justify:?} {composer:?}");
let size = 14.0 * l.fit_scale;
assert!(layout(db(), &scaled_by(&t, (size + 0.1) / 14.0)).overflow, "{justify:?} {composer:?}: maximal at {size}");
let same = layout(db(), &scaled_by(&t, l.fit_scale));
assert_eq!(line_texts(&t, &same), line_texts(&t, &l), "{justify:?} {composer:?}");
}
}
}
#[test]
fn composer_x_paragraph_attrs() {
// Each paragraph breaks with its own composer.
let w = natural_width("Destroy all creatures with toughness X or", 12.0) + 2.0;
let mut t = area(vec![run(&format!("{RAG}\n{RAG}\n{RAG}"), sans(12.0))], Rect::new(0.0, 0.0, w, 400.0));
let p = |c: Composer| vectorcraft_doc::ParaStyle { composer: c, ..t.para.clone() };
t.set_paragraph_styles(vec![p(Composer::SingleLine), p(Composer::EveryLine), p(Composer::SingleLine)]);
let l = layout(db(), &t);
let greedy = ["Destroy all creatures with toughness X or", "less."];
let every = ["Destroy all creatures with toughness X", "or less."];
let want: Vec<&str> = [greedy, every, greedy].concat();
assert_eq!(line_texts(&t, &l), want);
// The object-wide override still wins over every paragraph.
let forced = layout_with(db(), &t, &LayoutOptions { composer: Some(Composer::SingleLine), ..Default::default() });
assert_eq!(line_texts(&t, &forced), [greedy, greedy, greedy].concat());
}
#[test]
fn composer_x_inline_graphics() {
// An inline graphic is a word's worth of box to the composers: each one breaks around it as
// around the letter it replaces, and the art follows its glyph to whichever line it lands on.
let st = sans(12.0);
let runs = |x: TextRun| vec![run("Destroy all creatures with toughness ", st.clone()), x, run(" or less.", st.clone())];
let with_art = runs(sym(0.7, 0.0, st.clone()));
let mut probe = area(with_art.clone(), Rect::new(0.0, 0.0, 10_000.0, 100.0));
probe.runs.truncate(2);
probe.runs.push(run(" or", st.clone()));
let w = layout(db(), &probe).lines[0].x1 + 2.0;
let sym_text = INLINE.to_string();
for (composer, first, second) in [
(Composer::SingleLine, format!("Destroy all creatures with toughness {sym_text} or"), "less."),
(Composer::EveryLine, format!("Destroy all creatures with toughness {sym_text}"), "or less."),
] {
let mut t = area(with_art.clone(), Rect::new(0.0, 0.0, w, 200.0));
t.para.composer = composer;
let l = layout(db(), &t);
assert_eq!(line_texts(&t, &l), [first.as_str(), second], "{composer:?}");
assert_inlines_on_their_glyphs(&t, &l, &format!("{composer:?}"));
}
}
const INLINE: char = vectorcraft_doc::text::INLINE_CHAR;
// ---------- vertical alignment × … ----------
#[test]
fn vertical_align_x_shrink_text() {
let frame = Rect::new(0.0, 0.0, 200.0, 100.0);
let mut t = area(vec![run(&COPY.repeat(2), sans(14.0))], frame);
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let top = layout(db(), &t);
assert!(!top.overflow && top.fit_scale < 1.0);
for a in [VerticalAlign::Center, VerticalAlign::Bottom] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert_eq!(l.fit_scale, top.fit_scale, "{a:?}: aligning doesn't change the fit");
assert_eq!(line_texts(&t, &l), line_texts(&t, &top), "{a:?}");
let want = if a == VerticalAlign::Center { slack(&top, frame) * 0.5 } else { slack(&top, frame) };
for (b, b0) in baselines(&l).iter().zip(baselines(&top)) {
assert!((b - b0 - want).abs() < 1e-6, "{a:?}: {b} vs {b0} + {want}");
}
if a == VerticalAlign::Bottom {
assert!(slack(&l, frame).abs() < 1e-6, "the shrunk block sits on the bottom");
}
}
// Still overflowing at the minimum: aligned like any full frame (the same lines, moved by
// less than a line, inside the frame), at the same scale.
let frame = Rect::new(0.0, 0.0, 120.0, 40.0);
let mut t = area(vec![run(&COPY.repeat(4), sans(14.0))], frame);
t.area.fit = AreaFit::ShrinkText { min_percent: 90.0 };
let top = layout(db(), &t);
assert!(top.overflow && (top.fit_scale - 0.9).abs() < 1e-9);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert!(l.overflow && l.fit_scale == top.fit_scale, "{a:?}");
assert_eq!(line_texts(&t, &l), line_texts(&t, &top), "{a:?}");
let first = &top.lines[0];
assert!(l.lines[0].baseline - first.baseline < first.ascent + first.descent, "{a:?}");
assert!(slack(&l, frame) >= -1e-6, "{a:?}");
}
}
#[test]
fn vertical_align_x_paragraph_attrs() {
// Per-paragraph spacing and alignment survive the move: lines keep their x and their
// paragraph gaps, and the block lands where the alignment puts it.
let frame = Rect::new(0.0, 0.0, 260.0, 500.0);
let mut t = area(vec![run(&format!("{COPY}\n{COPY}\n{COPY}"), sans(11.0))], frame);
let mut mid = t.para.clone();
mid.justify = Justify::Center;
mid.space_before = 18.0;
mid.left_indent = 24.0;
let mut last = t.para.clone();
last.justify = Justify::Right;
last.space_before = 6.0;
t.set_paragraph_styles(vec![t.para.clone(), mid, last]);
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert_eq!(line_texts(&t, &l), line_texts(&t, &top));
let d = l.lines[0].baseline - top.lines[0].baseline;
assert!(d > 1.0, "{a:?}");
for (li, l0) in l.lines.iter().zip(&top.lines) {
assert!((li.baseline - l0.baseline - d).abs() < 1e-6, "{a:?}: every line moves alike");
assert!((li.x0 - l0.x0).abs() < 1e-6 && (li.x1 - l0.x1).abs() < 1e-6, "{a:?}: x stays");
}
for (g, g0) in l.glyphs.iter().zip(&top.glyphs) {
assert!((g.origin.x - g0.origin.x).abs() < 1e-6 && (g.origin.y - g0.origin.y - d).abs() < 1e-6);
}
}
// Justify: spacing is shared out on top of each paragraph's own space before, never less.
t.area.vertical_align = VerticalAlign::Justify;
let l = layout(db(), &t);
assert!(slack(&l, frame).abs() < 1e-6, "justified to the bottom");
for (pair, pair0) in l.lines.windows(2).zip(top.lines.windows(2)) {
assert!(pair[1].baseline - pair[0].baseline >= pair0[1].baseline - pair0[0].baseline - 1e-6);
}
}
#[test]
fn vertical_align_x_inline_graphics() {
// Inline art moves with its line however the lines are aligned, in one cell or several, in a
// rectangle or a frame the text flows into again.
let st = sans(12.0);
let mut runs = vec![];
for i in 0..6 {
runs.push(run(&format!("{} ", &COPY[i * 20..i * 20 + 20]), st.clone()));
runs.push(sym(1.0 + i as f64 * 0.1, i as f64 - 2.0, st.clone()));
if i == 2 {
runs.push(run("\n", st.clone()));
}
}
let mut tri = BezPath::new();
tri.move_to((0.0, 0.0));
tri.line_to((600.0, 0.0));
tri.line_to((300.0, 400.0));
tri.close_path();
for (name, frame, columns) in [
("rect", Rect::new(0.0, 0.0, 160.0, 400.0).to_path(0.1), 1),
("columns", Rect::new(0.0, 0.0, 400.0, 300.0).to_path(0.1), 2),
("triangle", tri, 1),
] {
for a in VerticalAlign::ALL {
let mut t = area(runs.clone(), Rect::ZERO);
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) };
t.area.columns = columns;
t.area.vertical_align = a;
let l = layout(db(), &t);
assert!(!l.overflow, "{name} {a:?}");
assert_inlines_on_their_glyphs(&t, &l, &format!("{name} {a:?}"));
}
}
}
// ---------- Shrink Text to Fit × … ----------
#[test]
fn shrink_text_x_paragraph_attrs() {
// Shrinking scales the type, not each paragraph's spacing and indents: the fitted layout is
// the unfitted one at the scaled size.
let mut t = area(vec![run(&format!("{COPY}\n{COPY}"), sans(13.0))], Rect::new(0.0, 0.0, 220.0, 160.0));
let mut second = t.para.clone();
second.space_before = 14.0;
second.left_indent = 30.0;
second.first_line_indent = 12.0;
second.justify = Justify::JustifyLeft;
second.composer = Composer::SingleLine;
t.set_paragraph_styles(vec![t.para.clone(), second]);
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0);
let same = layout(db(), &scaled_by(&t, l.fit_scale));
assert_eq!(baselines(&l), baselines(&same));
assert_eq!(line_texts(&t, &l), line_texts(&t, &same));
// The second paragraph's indents are unscaled points.
let split = COPY.len() + 1;
let first_of_second = l.lines.iter().find(|li| li.start == split).unwrap();
assert!((first_of_second.x0 - 42.0).abs() < 1e-6, "{}", first_of_second.x0);
assert!(l.lines.iter().filter(|li| li.start > split).all(|li| (li.x0 - 30.0).abs() < 1e-6));
// A paragraph's space before alone can make the text overflow; shrinking still finds a fit.
let mut tall = t.clone();
tall.edit_paras(Some(1..2), |p| p.space_before = 100.0);
let l = layout(db(), &tall);
assert!(!l.overflow && l.fit_scale < layout(db(), &t).fit_scale);
}
#[test]
fn shrink_text_x_inline_graphics() {
// Inline art shrinks with the type, its shift included, and stays centred on the cap height.
let st = sans(14.0);
let mut runs = vec![];
for i in 0..8 {
runs.push(run(&COPY[i * 25..i * 25 + 25], st.clone()));
runs.push(sym(1.2, 1.5, st.clone()));
}
let mut t = area(runs, Rect::new(0.0, 0.0, 200.0, 80.0));
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale);
assert_inlines_on_their_glyphs(&t, &l, "shrunk");
let same = layout(db(), &scaled_by(&t, l.fit_scale));
for (i, i0) in l.inlines.iter().zip(&same.inlines) {
assert!((i.bounds.y0 - i0.bounds.y0).abs() < 1e-6 && (i.bounds.x0 - i0.bounds.x0).abs() < 1e-6, "{:?} vs {:?}", i.bounds, i0.bounds);
}
// Large art makes lines taller; shrinking still fits it.
for r in &mut t.runs {
if let Some(a) = &mut r.inline {
a.scale = 3.0;
}
}
let big = layout(db(), &t);
assert!(!big.overflow && big.fit_scale < l.fit_scale);
assert_inlines_on_their_glyphs(&t, &big, "shrunk, big art");
}
// ---------- paragraph attributes × inline graphics ----------
#[test]
fn paragraph_attrs_x_inline_graphics() {
// Inline art in paragraphs of each alignment and indent sits on its glyph, and an inline
// graphic opening a paragraph takes that paragraph's first-line indent.
let st = sans(12.0);
let runs = vec![
run("Left aligned ", st.clone()),
sym(1.0, 0.0, st.clone()),
run(" text.\n", st.clone()),
sym(1.0, 0.0, st.clone()),
run(" centred with art first\nright ", st.clone()),
sym(1.5, -1.0, st.clone()),
run(" aligned\nfull justified text with ", st.clone()),
sym(1.0, 0.0, st.clone()),
run(" in the middle of a long line that wraps", st.clone()),
];
let mut t = area(runs, Rect::new(0.0, 0.0, 200.0, 400.0));
let base = t.para.clone();
let with = |j: Justify, first: f64| vectorcraft_doc::ParaStyle { justify: j, first_line_indent: first, left_indent: 6.0, ..base.clone() };
t.set_paragraph_styles(vec![base.clone(), with(Justify::Center, 0.0), with(Justify::Right, 0.0), with(Justify::JustifyLeft, 18.0)]);
let l = layout(db(), &t);
assert_inlines_on_their_glyphs(&t, &l, "paragraphs");
let opening = &l.glyphs[l.inlines[1].glyph];
let line = &l.lines[opening.line];
assert!((opening.origin.x - line.x0).abs() < 1e-6, "the art opens its line");
assert!(((line.x0 + line.x1) * 0.5 - (6.0 + 200.0) * 0.5).abs() < 1e-6, "the centred paragraph: {line:?}");
let right = &l.lines[l.glyphs[l.inlines[2].glyph].line];
assert!((right.x1 - 200.0).abs() < 1e-6, "{right:?}");
let full = l.lines.iter().find(|li| li.start == t.plain_text().find("full").unwrap()).unwrap();
assert!((full.x0 - 24.0).abs() < 1e-6, "left indent + first-line indent: {full:?}");
}
// ---------- all of them ----------
/// One area type object with everything on: two paragraphs with their own attributes (the first
/// ragged every-line with inline symbols and lightly tracked ligatures, the second single-line,
/// justified and spaced away), centred vertically, shrunk to fit.
#[test]
fn every_feature_at_once() {
let rules = serif(14.0, 15.0);
let flavor = CharStyle { font_style: "Italic".into(), ..serif(14.0, 0.0) };
let mut runs = vec![];
for (i, words) in
["Sacrifice a fine fish", "First strike. When this finishes fighting, draw a card", "Fifty fireflies fill the field"].iter().enumerate()
{
runs.push(sym(0.8, 0.0, rules.clone()));
runs.push(run(&format!(": {words}. "), rules.clone()));
if i == 1 {
runs.push(sym(0.8, 0.5, rules.clone()));
runs.push(run(" Then fight again.", rules.clone()));
}
}
runs.push(run("\nThe finest fishers find their fortune in the fjords, if they first fix their nets.", flavor));
let frame = Rect::new(0.0, 0.0, 240.0, 110.0);
let mut t = area(runs, frame);
let mut flav = t.para.clone();
flav.space_before = 10.0;
flav.justify = Justify::JustifyLeft;
flav.composer = Composer::SingleLine;
t.para.composer = Composer::EveryLine;
t.set_paragraph_styles(vec![t.para.clone(), flav]);
t.area.fit = AreaFit::ShrinkText { min_percent: 30.0 };
let top = layout(db(), &t);
t.area.vertical_align = VerticalAlign::Center;
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale);
assert_eq!(l.fit_scale, top.fit_scale);
// Shrunk: the same as laying out the scaled text, then centring it.
let mut unfit = scaled_by(&t, l.fit_scale);
unfit.area.vertical_align = VerticalAlign::Top;
let plain = layout(db(), &unfit);
assert_eq!(line_texts(&t, &l), line_texts(&t, &plain));
let d = slack(&plain, frame) * 0.5;
assert!(d > 0.0);
for (b, b0) in baselines(&l).iter().zip(baselines(&plain)) {
assert!((b - b0 - d).abs() < 1e-6, "centred: {b} vs {b0} + {d}");
}
// Every symbol on its glyph; ligatures kept at tracking 15.
assert_inlines_on_their_glyphs(&t, &l, "everything");
assert_eq!(l.inlines.len(), 4);
assert!(ligatures(&l) >= 6, "{}", ligatures(&l));
// The flavor paragraph: justified (all but its last line fill the measure) and spaced away.
let split = t.plain_text().find('\n').unwrap() + 1;
let flavor_lines: Vec<&LineInfo> = l.lines.iter().filter(|li| li.start >= split).collect();
assert!(flavor_lines.len() >= 2);
for li in &flavor_lines[..flavor_lines.len() - 1] {
assert!((li.x1 - li.x0 - 240.0).abs() < 0.5, "justified: {li:?}");
}
// Deterministic.
let again = layout(db(), &t);
assert_eq!(baselines(&again), baselines(&l));
assert_eq!(again.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>(), l.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>());
}
/// The natural width of `s` set in one line at `size`.
fn natural_width(s: &str, size: f64) -> f64 {
let l = layout(db(), &TextObject::point(Point::ZERO, s, sans(size)));
l.lines[0].x1 - l.lines[0].x0
}
+30
View File
@@ -296,3 +296,33 @@ fn top_to_top_leading_spaces_inline_art_by_its_run() {
let (tall0, tall1) = lines(3.0);
assert!((small0 - tall0).abs() < 1e-6 && (small1 - tall1).abs() < 1e-6, "{small0} {small1} / {tall0} {tall1}");
}
#[test]
fn inline_art_moves_with_vertically_aligned_lines() {
use vectorcraft_doc::text::{AreaOptions, VerticalAlign};
// A rectangle (lines shift) and a triangle (text flows again lower down).
let rect = Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1);
let mut tri = kurbo::BezPath::new();
tri.move_to((0.0, 0.0));
tri.line_to((800.0, 0.0));
tri.line_to((400.0, 400.0));
tri.close_path();
for frame in [rect, tri] {
for align in [VerticalAlign::Center, VerticalAlign::Bottom] {
let mut t = text("A", art(1.0), "B", 20.0);
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) };
t.area = AreaOptions { vertical_align: align, ..AreaOptions::default() };
let l = layout(db(), &t);
assert_eq!(l.inlines.len(), 1, "{align:?}");
let g = inline_glyph(&l);
let line = &l.lines[g.line];
assert!(line.baseline > 100.0, "{align:?}: not aligned, baseline {}", line.baseline);
// Still centred on the cap height above its (moved) baseline.
let face = db().face("Source Sans 3", "Regular").unwrap();
let cap = face.cap_height * 20.0 / face.upem;
let b = l.inlines[0].bounds;
assert!((b.center().y - (line.baseline - cap * 0.5)).abs() < 1e-6, "{align:?}: {b:?} baseline {}", line.baseline);
assert!((b.x0 - g.origin.x).abs() < 1e-6, "{align:?}: {b:?}");
}
}
}
+185 -7
View File
@@ -79,6 +79,9 @@ pub struct Targets {
segments: Vec<(Rect, PathSeg)>,
/// Ruler guides, which pull a point into line where they run (Snap to Point).
rulers: Vec<Ruler>,
/// The bounds of the objects a moved selection spaces itself evenly with (Spacing Guides):
/// gathered only for moves ([`Self::for_move`]).
boxes: Vec<Rect>,
/// How the guides these targets produce look.
style: GuideStyle,
}
@@ -145,11 +148,47 @@ fn lines_near(lines: &[(f64, Point, Kind)], v: f64, tol: f64) -> &[(f64, Point,
within(lines, |l| l.0, v, tol)
}
/// `r`'s extent along the x axis (`x`) or the y axis.
fn span(r: &Rect, x: bool) -> (f64, f64) {
if x { (r.x0, r.x1) } else { (r.y0, r.y1) }
}
/// The objects a moved selection (`moving`) spaces itself evenly with, by their bounds: each
/// visible object on a layer as a whole (a group too), and inside a group holding some of the
/// moving objects its other objects. At most [`BUDGET`].
fn object_boxes(doc: &Document, moving: &[NodeId]) -> Vec<Rect> {
fn push(nodes: &[Arc<Node>], moving: &HashSet<NodeId>, holders: &HashSet<NodeId>, out: &mut Vec<Rect>) {
for n in nodes.iter().filter(|n| n.visible && !moving.contains(&n.id)) {
if out.len() >= BUDGET {
return;
}
match n.children() {
Some(ch) if n.is_layer() || holders.contains(&n.id) => push(ch, moving, holders, out),
_ => out.extend(n.geometric_bounds()),
}
}
}
let holders: HashSet<NodeId> = moving.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect();
let mut out = vec![];
push(&doc.layers, &moving.iter().copied().collect(), &holders, &mut out);
out
}
impl Targets {
pub fn collect(doc: &Document, exclude: &[NodeId], visible: Option<Rect>) -> Self {
Self::collect_inner(doc, exclude, None, visible, Gather::Bounds)
}
/// Targets for moving the selection of `cx`: [`Self::collect`]'s, styled as `cx` asks, and with
/// Smart Guides › Spacing Guides the objects it spaces itself evenly with ([`Self::snap_rect`]).
pub fn for_move(cx: &ToolContext) -> Self {
let mut t = Self::collect(cx.doc, &cx.selection.objects, None).styled(cx);
if cx.spacing_guides {
t.boxes = object_boxes(cx.doc, &cx.selection.objects);
}
t
}
/// Targets for a drawn point: the art in `visible` (all of it for None) but `exclude`, its
/// anchors, centres, edges and path segments, its anchors in line too. The anchors and
/// segments of `exclude` (the path being drawn, whose bounds grow with it) stay targets.
@@ -508,7 +547,7 @@ impl Targets {
let rects: Vec<Rect> = std::iter::once(Vec2::ZERO).chain(offsets.iter().copied()).map(|o| Rect::from_points(p + o, p + o)).collect();
let (adj, mut ov, aligned) = self.align_rects(&rects, tol);
let out = p + adj;
if aligned {
if aligned.contains(&true) {
ov.extend(self.label(out, "align"));
}
(out, ov)
@@ -520,15 +559,107 @@ impl Targets {
}
/// Snap rectangles that move together (an artboard and its bleed): the edge or centre of any
/// of them nearest a target, per axis. Returns the shift and the guides.
/// of them nearest a target, per axis. A single moved selection with Spacing Guides
/// ([`Self::for_move`]) is spaced evenly along an axis that lines up with nothing
/// ([`Self::even_spacing`]). Returns the shift and the guides.
pub fn snap_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec<Overlay>) {
let (d, ov, _) = self.align_rects(rects, tol);
let (mut d, mut ov, aligned) = self.align_rects(rects, tol);
if let [r] = rects
&& !self.boxes.is_empty()
{
let moved = *r + d;
let mut spaced = false;
for (x, lined_up) in [true, false].into_iter().zip(aligned) {
if let Some((shift, _)) = self.even_spacing(moved, x, tol).filter(|_| !lined_up) {
*(if x { &mut d.x } else { &mut d.y }) += shift;
spaced = true;
}
}
// The equal gaps, marked where the rectangle ends up.
if spaced {
let done = *r + d;
for (x, lined_up) in [true, false].into_iter().zip(aligned) {
let gaps = if lined_up { None } else { self.even_spacing(done, x, tol) };
ov.extend(gaps.into_iter().flat_map(|(_, gaps)| gaps).flat_map(|g| self.gap_marks(g, x, tol)));
}
}
}
(d, ov)
}
/// [`Self::snap_rects`], also saying whether an axis lined up (even with Alignment Guides
/// off, or already in line, when there is no line or shift to tell).
fn align_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec<Overlay>, bool) {
/// Spacing Guides along the x axis (`x`) or the y axis for the moved rectangle `r`, among the
/// objects of its row (column): the shift (within `tol`) that leaves it as far from its
/// neighbour before or after it as two other objects of the row are apart, or as far from both
/// neighbours; and the equal gaps then, as (start, end, where across) along that axis.
fn even_spacing(&self, r: Rect, x: bool, tol: f64) -> Option<(f64, Vec<[f64; 3]>)> {
let (r0, r1) = span(&r, x);
let len = r1 - r0;
let (c0, c1) = span(&r, !x);
// The objects beside it, before or after, overlapping it across, by where they start.
let mut row: Vec<(Rect, f64, f64)> = self
.boxes
.iter()
.map(|b| (*b, span(b, x).0, span(b, x).1))
.filter(|(b, a0, a1)| span(b, !x).0 < c1 && span(b, !x).1 > c0 && (*a1 <= r0 + tol || *a0 >= r1 - tol))
.collect();
row.sort_by(|a, b| a.1.total_cmp(&b.1));
// Where two boxes overlap across: the middle of that (or of the space between them).
let mid = |a: &Rect, b: &Rect| (span(a, !x).0.max(span(b, !x).0) + span(a, !x).1.min(span(b, !x).1)) / 2.0;
// Each object and the nearest one after it, unless the moved rectangle sits between them.
let pairs: Vec<(f64, [f64; 3])> = row
.iter()
.filter_map(|(p, _, p1)| {
let next = row.partition_point(|(_, a0, _)| *a0 < *p1);
let (q, q0, _) = row.get(next)?;
let straddles = *p1 <= r0 + tol && *q0 >= r1 - tol;
(*q0 > *p1 && !straddles).then(|| (q0 - p1, [*p1, *q0, mid(p, q)]))
})
.collect();
let before = row.iter().filter(|(_, _, a1)| *a1 <= r0 + tol).max_by(|a, b| a.2.total_cmp(&b.2));
let after = row.iter().filter(|(_, a0, _)| *a0 >= r1 - tol).min_by(|a, b| a.1.total_cmp(&b.1));
// Where it could start, and the gap it repeats (None: halfway between its neighbours).
let mut starts: Vec<(f64, Option<f64>)> = vec![];
if let (Some(a), Some(b)) = (before, after)
&& b.1 - a.2 > len
{
starts.push(((a.2 + b.1 - len) / 2.0, None));
}
for (g, _) in &pairs {
starts.extend(before.map(|a| (a.2 + g, Some(*g))));
starts.extend(after.map(|b| (b.1 - g - len, Some(*g))));
}
let (start, repeats) =
starts.into_iter().filter(|(t, _)| (t - r0).abs() <= tol).min_by(|a, b| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs()))?;
let at = r + if x { Vec2::new(start - r0, 0.0) } else { Vec2::new(0.0, start - r0) };
let (end, mut gaps) = (start + len, vec![]);
if let Some((a, _, a1)) = before
&& repeats.is_none_or(|g| (start - a1 - g).abs() <= 1e-9)
{
gaps.push([*a1, start, mid(a, &at)]);
}
if let Some((b, b0, _)) = after
&& repeats.is_none_or(|g| (b0 - end - g).abs() <= 1e-9)
{
gaps.push([end, *b0, mid(b, &at)]);
}
if let Some(g) = repeats {
gaps.extend(pairs.iter().filter(|(pg, _)| (pg - g).abs() <= 1e-9).map(|(_, gap)| *gap));
}
Some((start - r0, gaps))
}
/// A Spacing Guides mark: a line across the gap (start, end, where across) along the x axis
/// (`x`) or the y axis, with a tick `tick` long either side of it at each end.
fn gap_marks(&self, [u0, u1, c]: [f64; 3], x: bool, tick: f64) -> [Overlay; 3] {
let pt = |u: f64, c: f64| if x { Point::new(u, c) } else { Point::new(c, u) };
let line = |a: Point, b: Point| Overlay::Line { a, b, color: self.style.color, dashed: false };
[line(pt(u0, c), pt(u1, c)), line(pt(u0, c - tick), pt(u0, c + tick)), line(pt(u1, c - tick), pt(u1, c + tick))]
}
/// [`Self::snap_rects`] before Spacing Guides, also saying whether each axis (x, y) lined up
/// (even with Alignment Guides off, or already in line, when there is no line or shift to
/// tell).
fn align_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec<Overlay>, [bool; 2]) {
let nearest = |targets: &[(f64, Point, Kind)], along: fn(&Rect) -> [f64; 3]| {
rects
.iter()
@@ -553,7 +684,7 @@ impl Targets {
let (x0, x1) = (from.x.min(r.x0), from.x.max(r.x1));
ov.extend(self.line(Point::new(x0, y), Point::new(x1, y)));
}
(d, ov, best_x.is_some() || best_y.is_some())
(d, ov, [best_x.is_some(), best_y.is_some()])
}
/// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for
@@ -1064,6 +1195,53 @@ mod tests {
assert!(anchor(&ov), "{ov:?}");
}
/// Smart Guides › Spacing Guides (#394): a moved selection lands as far from its neighbour as
/// two other objects of its row are apart, or halfway between its two neighbours, and the
/// equal gaps are marked; up and down the same in a column. Off, it stays where it is dragged.
#[test]
fn spacing_guides_space_a_moved_selection_evenly() {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
// A and B 20 apart in a row at y 300–340, C and D 30 apart in a column at x 400–440.
for r in [
Rect::new(20.0, 300.0, 60.0, 340.0),
Rect::new(80.0, 300.0, 120.0, 340.0),
Rect::new(400.0, 20.0, 440.0, 50.0),
Rect::new(400.0, 80.0, 440.0, 110.0),
] {
let id = d.alloc_id();
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), Default::default())).unwrap();
}
let (s, p) = (Selection::default(), paint());
let lines = |ov: &[Overlay]| ov.iter().filter(|o| matches!(o, Overlay::Line { color, .. } if *color == MAGENTA)).count();
let t = Targets::for_move(&cx(&d, &s, &p));
// 21 after B: 20, as A and B, with both gaps marked (a line and two ticks each).
let (dv, ov) = t.snap_rect(Rect::new(141.0, 305.0, 181.0, 345.0), 4.0);
assert_eq!(dv, Vec2::new(-1.0, 0.0));
assert_eq!(lines(&ov), 6, "{ov:?}");
assert!(ov.iter().any(|o| matches!(o, Overlay::Line { a, b, .. } if (a.x, b.x) == (120.0, 140.0) && a.y == b.y)), "{ov:?}");
assert!(ov.iter().any(|o| matches!(o, Overlay::Line { a, b, .. } if (a.x, b.x) == (60.0, 80.0) && a.y == b.y)), "{ov:?}");
// Halfway between B and a box at 220–260: 50 either side.
let mut wide = d.clone();
let id = wide.alloc_id();
wide.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(220.0, 300.0, 260.0, 340.0)), Default::default()))
.unwrap();
let (dv, ov) = Targets::for_move(&cx(&wide, &s, &p)).snap_rect(Rect::new(148.0, 305.0, 188.0, 345.0), 4.0);
assert_eq!(dv, Vec2::new(2.0, 0.0));
assert!(lines(&ov) >= 6, "{ov:?}");
// A column: 28 under D, as C and D are 30 apart.
let (dv, ov) = t.snap_rect(Rect::new(405.0, 138.0, 445.0, 168.0), 4.0);
assert_eq!(dv, Vec2::new(0.0, 2.0));
assert!(ov.iter().any(|o| matches!(o, Overlay::Line { a, b, .. } if (a.y, b.y) == (110.0, 140.0) && a.x == b.x)), "{ov:?}");
// Above C, 32 over it: 30.
let (dv, _) = t.snap_rect(Rect::new(405.0, -42.0, 445.0, -12.0), 4.0);
assert_eq!(dv, Vec2::new(0.0, 2.0));
// Off: nowhere to go, and no marks.
let off = ToolContext { spacing_guides: false, ..cx(&d, &s, &p) };
let (dv, ov) = Targets::for_move(&off).snap_rect(Rect::new(141.0, 305.0, 181.0, 345.0), 4.0);
assert_eq!((dv, lines(&ov)), (Vec2::ZERO, 0));
}
/// Preferences › Smart Guides › Display Options (#394): the colour, and Alignment Guides and
/// Anchor/Path Labels off, change what shows and never where a point lands.
#[test]
+5
View File
@@ -322,6 +322,10 @@ pub struct ToolContext<'a> {
pub measurement_labels: bool,
/// Smart Guides → Transform Tools: the readouts while scaling, rotating and shearing.
pub transform_tools_guides: bool,
/// Smart Guides → Spacing Guides: a moved selection snaps to spacing equal to the gap between
/// two other objects in its row or column, or evenly between its two neighbours, and the
/// equal gaps show.
pub spacing_guides: bool,
/// Smart Guides → Snapping Tolerance (screen pixels): how near a smart guide target pulls the
/// pointer, a dragged edge or a drawn point.
pub snapping_tolerance: f64,
@@ -695,6 +699,7 @@ pub(crate) mod testutil {
anchor_path_labels: true,
measurement_labels: true,
transform_tools_guides: true,
spacing_guides: true,
snapping_tolerance: 4.0,
construction_angles: guides::construction_angles(guides::DEFAULT_CONSTRUCTION_ANGLES),
screen: None,
+1 -1
View File
@@ -87,7 +87,7 @@ impl MoveSnap {
pub(crate) fn new(cx: &ToolContext) -> Self {
Self {
bounds: selection_bounds(cx),
targets: cx.smart_guides.then(|| Targets::collect(cx.doc, &cx.selection.objects, None).styled(cx)),
targets: cx.smart_guides.then(|| Targets::for_move(cx)),
points: Targets::snap_to_point(cx, &cx.selection.objects),
}
}
+246 -30
View File
@@ -69,9 +69,17 @@ enum Drag {
center: Point,
middle: bool,
},
/// A Zoom tool drag without Animated Zoom: the area to zoom to.
ZoomBox {
start: Pos2,
},
/// A Zoom tool press with Animated Zoom ([`animated_zoom`]): dragged sideways it zooms about
/// `start`, held still (for `held` seconds so far) it zooms on, else it's a click.
ZoomScrub {
start: Pos2,
held: f32,
moved: bool,
},
RotateView {
start_angle: f64,
start_rot: f64,
@@ -221,6 +229,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel
// is bigger than a screen pixel (below that the screen render already shows it).
let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: off, images show
// their pixels as they rasterize, hard-edged.
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
let key = CacheKey {
doc: st.uid as usize,
revision: st.revision,
@@ -237,6 +248,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
anti_alias: app.session.prefs.anti_aliased_artwork,
placed: vectorcraft_render::placed_document::generation(),
pixel,
smooth_images,
};
// Placed documents' bitmaps are being made: draw again when they are ready.
if vectorcraft_render::placed_document::busy() {
@@ -285,6 +297,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None },
progressive_placed: true,
trace_views: true,
smooth_images,
..opts
};
// Light documents render synchronously (no lag vs overlays); heavy ones go to the worker.
@@ -438,15 +451,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
// Caps Lock gives precise (crosshair) cursors, like Illustrator; env opt-out for system cursors.
let custom = std::env::var_os("VECTORCRAFT_SYSTEM_CURSORS").is_none();
// User Interface › Scale Cursor Proportional to UI: the glyphs grow with UI Scaling;
// off, they keep their size.
let ui_scale = if app.session.prefs.scale_cursor_with_ui { 1.0 } else { ui.ctx().zoom_factor() };
match ui.input(|i| i.pointer.hover_pos()) {
// An OS cursor: the system moves it at once, where a painted one trails the pointer
// (#444). The system cursor stands in for cursors without a glyph.
Some(_) if custom && crate::cursors::OS_CURSORS => {
let ppp = ui.ctx().native_pixels_per_point().unwrap_or_else(|| ui.ctx().pixels_per_point());
let ppp = ui.ctx().pixels_per_point() / ui_scale;
ui.ctx().set_cursor_image(app.canvas.cursors.get(c, ppp));
cursor_icon(c)
}
Some(hp) if custom && crate::cursors::paint(&painter, c, hp) => egui::CursorIcon::None,
Some(hp) if custom && crate::cursors::paint(&painter, c, hp, 1.0 / ui_scale) => egui::CursorIcon::None,
_ => cursor_icon(c),
}
} else {
@@ -516,17 +532,15 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
prev.is_some_and(|prev| prev != m)
});
// Zoom around the pointer, or scroll ([`wheel`]).
// Zoom around the pointer, and scroll ([`wheel`]): fingers pinching on a touch screen may also
// slide.
if resp.hovered() {
if (factor - 1.0).abs() > 1e-6 {
if let (Some(p), Some(vm)) = (hover, app.view_mut()) {
let before = xf.to_doc(p);
vm.zoom = (vm.zoom * factor).clamp(0.0313, 640.0);
let nx = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() };
let after = nx.to_doc(p);
vm.center += before - after;
}
} else if scroll != egui::Vec2::ZERO
if (factor - 1.0).abs() > 1e-6
&& let (Some(p), Some(vm)) = (hover, app.view_mut())
{
zoom_about(vm, rect, p, vm.zoom * factor);
}
if scroll != egui::Vec2::ZERO
&& let Some(vm) = app.view_mut()
{
let d = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() }.delta_to_doc(scroll);
@@ -550,7 +564,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
ui.ctx().memory_mut(|mem| mem.stop_text_input());
app.ui.flyout = None;
let d = if zoom_mode {
Drag::ZoomBox { start: p }
if animated_zoom(&app.session.prefs) { Drag::ZoomScrub { start: p, held: 0.0, moved: false } } else { Drag::ZoomBox { start: p } }
} else if pan_mode {
Drag::Pan { start: p, center: v.center, middle: false }
} else if tool == "rotateView" {
@@ -597,7 +611,26 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
vm.rotation = vectorcraft_geom::normalize_deg(deg);
}
}
Drag::ZoomBox { .. } | Drag::Art | Drag::Gesture => {}
Drag::ZoomBox { start } => marquee(ui.painter(), egui::Rect::from_two_pos(start, p)),
Drag::ZoomScrub { start, held, moved } => {
let dt = ui.input(|i| i.unstable_dt).min(0.25);
let (held, moved) = (held + dt, moved || (p - start).length() > SCRUB_SLOP);
// Dragged sideways it zooms with the pointer, held still it zooms on (Alt: out).
let exponent = if moved {
f64::from(pointer.delta().x) * SCRUB_ZOOM
} else if held > HOLD_DELAY {
f64::from(dt) * HOLD_ZOOM * if m.alt { -1.0 } else { 1.0 }
} else {
0.0
};
if exponent != 0.0
&& let Some(vm) = app.view_mut()
{
zoom_about(vm, rect, start, vm.zoom * exponent.exp());
}
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::ZoomScrub { start, held, moved }));
}
Drag::Art | Drag::Gesture => {}
Drag::Tool if drag_art_out(app, ui, resp, p, view) => {
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art));
}
@@ -630,13 +663,17 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
vm.center = Point::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
vm.zoom = (rect.width() as f64 / (b.x - a.x)).min(rect.height() as f64 / (b.y - a.y)).clamp(0.0313, 640.0);
} else {
let before = xf.to_doc(p);
vm.zoom = crate::state::next_zoom(vm.zoom, !m.alt);
let nx = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() };
vm.center += before - nx.to_doc(p);
zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt));
}
}
}
// A click (not held, not dragged) steps the zoom as with the marquee.
Drag::ZoomScrub { held, moved: false, .. } if held <= HOLD_DELAY => {
if let Some(vm) = app.view_mut() {
zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt));
}
}
Drag::ZoomScrub { .. } => {}
Drag::Tool => {
let ev = PointerEvent { kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, false) };
dispatch(app, &ev, view);
@@ -672,14 +709,46 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
/// How much one point of wheel motion zooms (as `exp(points × WHEEL_ZOOM)`).
const WHEEL_ZOOM: f64 = 0.01;
/// Animated Zoom: how much one point of sideways drag zooms (100 points to the right double it).
const SCRUB_ZOOM: f64 = std::f64::consts::LN_2 / 100.0;
/// Animated Zoom: how far the pointer moves before a press is a drag, in points.
const SCRUB_SLOP: f32 = 3.0;
/// Animated Zoom: how long a press is held still before it zooms on, in seconds…
const HOLD_DELAY: f32 = 0.3;
/// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second).
const HOLD_ZOOM: f64 = std::f64::consts::LN_2;
/// What the wheel and a pinch did over the canvas this frame: a zoom factor (about the pointer)
/// and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option
/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms
/// as it is dragged sideways or held, instead of zooming to the area dragged across.
pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool {
p.animated_zoom && p.gpu_performance
}
/// Zoom view `vm` of the canvas `rect` to `zoom` (clamped to the zoom range), keeping the document
/// point under screen point `p` where it is.
fn zoom_about(vm: &mut View, rect: egui::Rect, p: Pos2, zoom: f64) {
let before = Xf::new(rect, vm).to_doc(p);
vm.zoom = zoom.clamp(0.0313, 640.0);
vm.center += before - Xf::new(rect, vm).to_doc(p);
}
/// A dashed marquee around screen rectangle `r`.
fn marquee(p: &egui::Painter, r: egui::Rect) {
let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()];
for w in pts.windows(2) {
p.extend(Shape::dashed_line(&[w[0], w[1]], Stroke::new(1.0, Color32::from_gray(90)), 3.0, 3.0));
}
}
/// What the wheel, a pinch and a two-finger drag on a touch screen did over the canvas this frame:
/// a zoom factor (about the pointer) and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option
/// on the Mac) zoom. With General › Zoom with Mouse Wheel (`wheel_zooms`) the wheel and Alt-wheel
/// zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. `line` and `page`: points
/// per wheel line and page. `alt_turn`: the last wheel turn was an Alt-wheel one (kept by the
/// caller across frames).
fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f32, alt_turn: &mut bool) -> (f64, egui::Vec2) {
// Fingers on a touch screen pan the content with them (a trackpad sends scrolls instead).
let pan = i.multi_touch().map_or(egui::Vec2::ZERO, |t| t.translation_delta);
if !wheel_zooms {
// egui makes Cmd-wheel (and a pinch) its zoom and the rest a scroll it spreads over a few
// frames: the rest of an Alt-wheel turn zooms too, however soon Alt is let go.
@@ -688,14 +757,14 @@ fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f32, alt_turn
}
let (zoom, scroll) = (f64::from(i.zoom_delta()), i.smooth_scroll_delta);
return if *alt_turn && scroll != egui::Vec2::ZERO {
(zoom * (f64::from(scroll.x + scroll.y) * WHEEL_ZOOM).exp(), egui::Vec2::ZERO)
(zoom * (f64::from(scroll.x + scroll.y) * WHEEL_ZOOM).exp(), pan)
} else {
(zoom, scroll)
(zoom, scroll + pan)
};
}
// The wheel events themselves: egui's own handling turns Cmd-wheel into a zoom.
let mut zoom = i.multi_touch().map_or(1.0, |t| f64::from(t.zoom_delta));
let mut scroll = egui::Vec2::ZERO;
let mut scroll = pan;
for e in &i.events {
match e {
egui::Event::MouseWheel { unit, delta, modifiers, .. } => {
@@ -1631,13 +1700,7 @@ fn names_an_artboard(text: &str) -> bool {
fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: &Tokens, look: HandleLook) {
for o in overlays {
match o {
Overlay::Marquee(r) => {
let sr = xf.rect_to_screen(*r);
let pts = [sr.left_top(), sr.right_top(), sr.right_bottom(), sr.left_bottom(), sr.left_top()];
for w in pts.windows(2) {
p.extend(Shape::dashed_line(&[w[0], w[1]], Stroke::new(1.0, Color32::from_gray(90)), 3.0, 3.0));
}
}
Overlay::Marquee(r) => marquee(p, xf.rect_to_screen(*r)),
Overlay::Path { path, color, width, dashed } => {
let s = Stroke::new(*width, c32(*color));
if *dashed {
@@ -1719,6 +1782,7 @@ fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
app.run("file.open", json!({})).ok();
}
});
recent(app, ui);
ui.add_space(28.0);
ui.label(egui::RichText::new(tl!("Quickly start a new file")).font(theme::semibold(14.0)).color(t.text));
ui.add_space(10.0);
@@ -1739,6 +1803,35 @@ fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
crate::community::links(app, ui);
}
/// The Home screen's Recent Files (#663): the first of File › Open Recent Files, each its name and
/// folder; a click opens it. Nothing when there are none.
fn recent(app: &mut VectorcraftApp, ui: &mut Ui) {
const SHOWN: usize = 6;
let files: Vec<String> = crate::io::recent_files(app).iter().take(SHOWN).cloned().collect();
if files.is_empty() {
return;
}
let t = Tokens::get(ui.ctx());
ui.add_space(28.0);
ui.label(egui::RichText::new(tl!("Recent Files")).font(theme::semibold(14.0)).color(t.text));
ui.add_space(8.0);
for path in files {
let p = std::path::Path::new(&path);
let name = p.file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
ui.horizontal(|ui| {
crate::icons::icon(ui, "history", 16.0, t.icon);
let r = ui.add(egui::Button::new(egui::RichText::new(&name).color(t.accent).size(13.0)).frame(false)).on_hover_text(&path);
ui.add(egui::Label::new(egui::RichText::new(&folder).size(12.0).color(t.text_dim)).truncate());
if r.clicked()
&& let Err(e) = crate::io::open_path(app, &path)
{
app.status(e);
}
});
}
}
fn kurbo_flatten(p: &BezPath, tol: f64, f: &mut impl FnMut(PathEl)) {
vectorcraft_geom::kurbo::flatten(p.elements().iter().copied(), tol, f);
}
@@ -2376,6 +2469,28 @@ mod tests {
assert!(partial(&alphas(&mut app).expect("re-rendered")) > 50, "smooth again");
}
/// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (#394): off, Pixel
/// Preview draws images with each pixel taking its nearest image pixel; on, smoothly, as the
/// canvas always does out of Pixel Preview.
#[test]
fn pixel_preview_smooths_bitmaps_only_when_asked() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
let ctx = egui::Context::default();
let smooth = |app: &mut VectorcraftApp| {
let (_, mut delta) = frame_output(app, &ctx);
delta.clear();
app.canvas.key.as_ref().map(|k| k.smooth_images).unwrap()
};
assert!(smooth(&mut app), "out of Pixel Preview");
app.ui.view.pixel_preview = true;
app.view_mut().unwrap().zoom = 8.0;
assert!(!smooth(&mut app), "Pixel Preview, off by default");
app.run("prefs.set", json!({"key": "antiAliasedBitmaps", "value": true})).unwrap();
assert!(smooth(&mut app), "Pixel Preview, on");
}
/// Guides & Grid › Show Pixel Grid (Above 600% Zoom) (#394): in Pixel Preview at 600% zoom and
/// above, a line at every document pixel over the art; none below 600%, out of Pixel Preview,
/// or with the option off.
@@ -2658,6 +2773,107 @@ mod tests {
assert!((zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, "on: Cmd-wheel scrolls sideways ({zoom}, {scroll:?})");
}
/// Two fingers dragged together on a touch screen pan the canvas with them, under either
/// Zoom with Mouse Wheel setting, and draw nothing (#449).
#[test]
fn two_fingers_dragged_together_pan_the_canvas() {
for wheel_zooms in [false, true] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": wheel_zooms})).unwrap();
app.select_tool("rectangle");
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let c = app.canvas_rect.unwrap().center();
let touch = |n: u64, phase, pos| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(n), phase, pos, force: None };
let fingers = |phase, d: egui::Vec2| vec![touch(1, phase, c - vec2(40.0, 0.0) + d), touch(2, phase, c + vec2(40.0, 0.0) + d)];
let before = *app.view().unwrap();
// egui-winit moves the pointer with the first finger, as here.
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(c - vec2(40.0, 0.0))]);
frame(&mut app, &ctx, fingers(egui::TouchPhase::Start, Vec2::ZERO));
for k in 1..=3 {
frame(&mut app, &ctx, fingers(egui::TouchPhase::Move, vec2(10.0, 8.0) * k as f32));
}
frame(&mut app, &ctx, fingers(egui::TouchPhase::End, vec2(30.0, 24.0)));
let after = *app.view().unwrap();
let moved = (after.center - before.center) * after.zoom;
assert!((after.zoom / before.zoom - 1.0).abs() < 1e-9, "no zoom: {wheel_zooms}");
assert!((moved.x + 30.0).abs() < 0.5 && (moved.y + 24.0).abs() < 0.5, "the content follows the fingers ({wheel_zooms}): {moved:?}");
assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 0, "nothing drawn");
}
}
/// Performance › Animated Zoom (#394): the Zoom tool dragged sideways zooms about where it was
/// pressed (right in, left out), held still it zooms on, and a click still steps. Off, or with
/// GPU Performance off, a drag zooms to the area dragged across.
#[test]
fn animated_zoom_scrubs_and_holds_else_the_zoom_tool_zooms_to_an_area() {
use egui::Event;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.select_tool("zoom");
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let at = rect.center() - vec2(100.0, 50.0);
let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Press at `at`, move by `by` and hold for `frames` frames (a 60th of a second each), let go.
let press = |app: &mut VectorcraftApp, by: egui::Vec2, frames: usize| {
frame(app, &ctx, vec![Event::PointerMoved(at)]);
frame(app, &ctx, vec![button(at, true)]);
frame(app, &ctx, vec![Event::PointerMoved(at + by)]);
for _ in 0..frames {
frame(app, &ctx, vec![]);
}
frame(app, &ctx, vec![button(at + by, false)]);
};
let doc_at = |app: &VectorcraftApp, p: Pos2| Xf::new(rect, app.view().unwrap()).to_doc(p);
let pinned = doc_at(&app, at);
let z0 = app.view().unwrap().zoom;
press(&mut app, vec2(100.0, 0.0), 0);
let z1 = app.view().unwrap().zoom;
assert!((z1 / z0 - 2.0).abs() < 1e-6, "100 points right doubles the zoom: {z0} → {z1}");
assert!(doc_at(&app, at).distance(pinned) < 1e-6, "about the press");
press(&mut app, vec2(-100.0, 0.0), 0);
assert!((app.view().unwrap().zoom - z0).abs() < 1e-6, "and back to the left");
press(&mut app, vec2(0.0, 0.0), 0);
assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true), "a click steps");
let z2 = app.view().unwrap().zoom;
press(&mut app, vec2(0.0, 0.0), 40);
assert!(app.view().unwrap().zoom > z2 * 1.2, "held, it zooms on");
assert!(doc_at(&app, at).distance(pinned) < 1e-6, "about the press");
// Off (or without GPU Performance): the area dragged across fills the view.
for key in ["animatedZoom", "gpuPerformance"] {
app.run("prefs.reset", json!({})).unwrap();
app.run("prefs.set", json!({"key": key, "value": false})).unwrap();
app.view_mut().unwrap().zoom = z0;
press(&mut app, vec2(100.0, 50.0), 0);
let z = app.view().unwrap().zoom;
assert!((z - z0 * (rect.width() / 100.0).min(rect.height() / 50.0) as f64).abs() < 1e-6, "{key} off: {z0} → {z}");
}
}
/// User Interface › Large Tabs (#394): the document tabs are taller, so the canvas starts lower.
#[test]
fn large_tabs_make_the_document_tabs_taller() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let canvas_top = |app: &mut VectorcraftApp| {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
crate::chrome::doc_tabs(app, ui);
show(app, ui);
});
out.textures_delta.clear();
app.canvas_rect.unwrap().top()
};
let small = canvas_top(&mut app);
app.run("prefs.set", json!({"key": "largeTabs", "value": true})).unwrap();
assert_eq!(canvas_top(&mut app) - small, 9.0, "44 points instead of 35");
}
#[test]
fn cmd_space_zooms_and_space_pans_whatever_the_tool() {
use egui::{Event, Modifiers};
+100 -9
View File
@@ -319,10 +319,16 @@ fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool) -> Stri
format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom).replace('%', " %"))
}
/// Document tab strip: "Name* @ 66.67% (RGB/Preview)".
/// Whether a document tab's × comes before its title (macOS) rather than after it (Windows,
/// Linux and the web).
const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos");
/// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs
/// taller, with larger titles.
pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), 35.0), Sense::hover());
let (height, title_size) = if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) };
let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
ui.painter().rect_filled(strip, 0.0, t.tab_strip);
ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border));
let mut x = strip.left();
@@ -334,7 +340,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
let title = tab_title(d, zoom, app.ui.view.outline);
// On the Home screen no tab is the current one.
let is_active = Some(i) == active && app.ui.home.is_none();
let galley = ui.painter().layout_no_wrap(title, theme::semibold(12.5), if is_active { t.text_strong } else { t.text_dim });
let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), if is_active { t.text_strong } else { t.text_dim });
let w = galley.size().x + 50.0;
let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(w, strip.height() - 1.0));
let resp = ui.interact(r, ui.id().with(("tab", i)), Sense::click());
@@ -344,11 +350,13 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.4));
}
ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border));
// × at the left like Illustrator.
let xr = egui::Rect::from_center_size(egui::pos2(r.left() + 16.0, r.center().y), vec2(12.0, 12.0));
// The × where each platform puts a tab's: before the title on macOS, after it elsewhere
// (#673).
let (x_center, title_left) = if CLOSE_BEFORE_TITLE { (r.left() + 16.0, r.left() + 32.0) } else { (r.right() - 16.0, r.left() + 14.0) };
let xr = egui::Rect::from_center_size(egui::pos2(x_center, r.center().y), vec2(12.0, 12.0));
let xresp = ui.interact(xr.expand(3.0), ui.id().with(("tabx", i)), Sense::click());
icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text });
ui.painter().galley(egui::pos2(r.left() + 32.0, r.center().y - galley.size().y / 2.0), galley, t.text);
ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley, t.text);
if xresp.clicked() {
close = Some(i);
} else if resp.clicked() {
@@ -517,6 +525,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
/// Contextual hint for the active tool: segments of (text, bold). Keys in bold segments are
/// written as shortcuts are ("Alt+Click"); [`hint_segments`] names them for the platform.
/// The hint of the Zoom tool with Performance › Animated Zoom on.
const ANIMATED_ZOOM_HINT: &str = "zoom.animated";
fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
Some(match tool {
"selection" => &[
@@ -588,6 +599,16 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
("Drag", true),
(" to zoom into an area", false),
],
ANIMATED_ZOOM_HINT => &[
("Click", true),
(" to zoom in | ", false),
("Alt+Click", true),
(" to zoom out | ", false),
("Drag", true),
(" right or left to zoom in or out | ", false),
("Hold", true),
(" to keep zooming", false),
],
"eyedropper" => &[
("Click", true),
(" an object to copy its attributes | ", false),
@@ -674,8 +695,8 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
/// can insist a complete language covers them.
pub fn hint_strings() -> Vec<&'static str> {
let mut v = Vec::new();
for tool in vectorcraft_tools::catalog::all_tools() {
for &(text, bold) in hint_for(tool.id).unwrap_or(&[]) {
for tool in vectorcraft_tools::catalog::all_tools().map(|t| t.id).chain([ANIMATED_ZOOM_HINT]) {
for &(text, bold) in hint_for(tool).unwrap_or(&[]) {
let text = if bold { text.rsplit_once('+').map_or(text, |(_, k)| k) } else { text };
if !text.is_empty() && !text.chars().all(|c| c.is_ascii_digit()) && !v.contains(&text) {
v.push(text);
@@ -729,7 +750,10 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, "?", theme::semibold(11.0), t.text);
ui.add_space(6.0);
let mut job = egui::text::LayoutJob::default();
for (txt, bold) in hint_segments(app.session.tool_id()) {
let tool = app.session.tool_id();
// The Zoom tool's drag zooms to an area, or with Animated Zoom zooms as it goes.
let hint = if tool == "zoom" && crate::canvas::animated_zoom(&app.session.prefs) { ANIMATED_ZOOM_HINT } else { tool };
for (txt, bold) in hint_segments(hint) {
let font = if bold { theme::semibold(12.5) } else { egui::FontId::proportional(12.5) };
job.append(&txt, 0.0, egui::TextFormat { font_id: font, color: if bold { t.text_strong } else { t.text }, ..Default::default() });
}
@@ -764,6 +788,44 @@ mod tests {
}
}
/// A document tab's × sits where the platform puts it (#673): after the title on Windows,
/// Linux and the web, before it on macOS; clicking it closes that document.
#[test]
fn a_tabs_close_box_sits_where_the_platform_puts_it() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 200.0));
let frame = |app: &mut crate::VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::doc_tabs(app, ui));
out.textures_delta.clear();
let mut titles = vec![];
for c in &out.shapes {
// The titles, not the × icons.
if let egui::Shape::Text(t) = &c.shape
&& t.visual_bounding_rect().width() > 30.0
{
titles.push(t.visual_bounding_rect());
}
}
titles.sort_by(|a, b| a.left().total_cmp(&b.left()));
titles
};
let titles = frame(&mut app, vec![]);
assert_eq!(titles.len(), 2, "{titles:?}");
// The first tab's ×: 20 pt past its title's end, or 16 pt before its start.
let first = titles[0];
let x = if super::CLOSE_BEFORE_TITLE { first.left() - 16.0 } else { first.right() + 20.0 };
let at = egui::pos2(x, first.center().y);
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
frame(&mut app, vec![press(false)]);
assert_eq!(app.session.documents().len(), 1, "the × closed the first document");
assert!(super::CLOSE_BEFORE_TITLE == cfg!(target_os = "macos"));
}
/// One headless frame of the status bar; returns the artboard navigator's buttons, left to
/// right: first, previous, next, last.
fn navigator(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<egui::Rect> {
@@ -832,4 +894,33 @@ mod tests {
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
assert!(title(&s).ends_with("(RGB/Preview)"));
}
/// The Zoom tool's hint follows Performance › Animated Zoom (#394): a drag zooms as it goes,
/// or (off) zooms into the area dragged across.
#[test]
fn the_zoom_hint_follows_animated_zoom() {
fn texts(s: &egui::Shape, out: &mut String) {
match s {
egui::Shape::Text(t) => out.push_str(t.galley.text()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.select_tool("zoom");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let hint = |app: &mut crate::VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::hint_bar(app, ui));
out.textures_delta.clear();
let mut shown = String::new();
out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown));
shown
};
let on = hint(&mut app);
assert!(on.contains(" right or left to zoom in or out") && on.contains("Hold"), "{on}");
app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap();
let off = hint(&mut app);
assert!(off.contains(" to zoom into an area") && !off.contains("Hold"), "{off}");
}
}
+50 -4
View File
@@ -288,10 +288,19 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Some(std::mem::take(&mut ink.0))
}
/// Paint cursor `c` at `p` on the given (foreground) painter, where the window can't show it as an
/// OS cursor ([`OS_CURSORS`]). Returns false for cursors that stay system cursors.
pub fn paint(painter: &Painter, c: Cursor, p: Pos2) -> bool {
glyph(c, p).map(|shapes| painter.extend(shapes)).is_some()
/// Paint cursor `c` at `p`, `scale` times its size, on the given (foreground) painter, where the
/// window can't show it as an OS cursor ([`OS_CURSORS`]). Returns false for cursors that stay
/// system cursors.
pub fn paint(painter: &Painter, c: Cursor, p: Pos2, scale: f32) -> bool {
let place = egui::emath::TSTransform::new(p.to_vec2(), scale);
glyph(c, Pos2::ZERO)
.map(|shapes| {
painter.extend(shapes.into_iter().map(|mut s| {
s.transform(place);
s
}))
})
.is_some()
}
/// Does the window show the glyphs as OS cursors ([`Images`])? Not on macOS, which sizes a cursor
@@ -555,6 +564,43 @@ mod tests {
assert!(off.platform_output.cursor_image.is_none());
}
/// User Interface › Scale Cursor Proportional to UI (#394): off, the tool cursors keep their
/// size whatever the UI Scaling; on, they grow with it.
#[test]
fn tool_cursors_scale_with_the_ui_only_when_asked() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("prefs.set", json!({"key": "uiScaling", "value": 2.0})).unwrap();
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
assert_eq!(ctx.zoom_factor(), 2.0);
let over = app.canvas_rect.unwrap().center();
let shown =
|app: &mut VectorcraftApp, d: f32| frame(app, &ctx, vec![egui::Event::PointerMoved(over + vec2(d, 0.0))]).platform_output.cursor_image;
if OS_CURSORS {
assert_eq!(shown(&mut app, 0.0).unwrap(), app.canvas.cursors.get(Cursor::Arrow, 1.0).unwrap(), "off: its own size");
app.run("prefs.set", json!({"key": "scaleCursorWithUi", "value": true})).unwrap();
assert_eq!(shown(&mut app, 4.0).unwrap(), app.canvas.cursors.get(Cursor::Arrow, 2.0).unwrap(), "on: twice as big");
}
// Painted into the window (macOS, the web), the glyph is drawn at the scale asked for, its
// hotspot where the pointer is.
let painted = |scale: f32| {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("probe"));
assert!(paint(&ui.ctx().layer_painter(layer), Cursor::Arrow, pos2(100.0, 100.0), scale));
});
out.textures_delta.clear();
out.textures_delta.clear();
out.shapes.iter().fold(egui::Rect::NOTHING, |r, c| r.union(c.shape.visual_bounding_rect()))
};
let (full, half) = (painted(1.0), painted(0.5));
assert!((half.height() * 2.0 - full.height()).abs() < 1.5 && full.height() > 15.0, "{full:?} {half:?}");
assert!(full.contains(pos2(100.0, 100.0)) && half.contains(pos2(100.0, 100.0)), "{full:?} {half:?}");
}
#[test]
fn arrow_hotspot_is_tip() {
let pts = arrow_points(pos2(10.0, 20.0));
-1
View File
@@ -24,7 +24,6 @@ fn lengths(command: &str) -> &'static [&'static str] {
match command {
"graph.create" => &["width", "height"],
"shape.flare" => &["diameter", "pathLength"],
"artboard.rearrange" => &["spacing"],
"perspective.grid.set" => &["cell", "distance"],
"object.repeat.options" => &["radius", "hSpacing", "vSpacing"],
"text.areaOptions" => &["width", "height", "gutter", "inset", "firstBaselineMin"],
+3
View File
@@ -60,6 +60,7 @@ pub mod print;
pub mod print_presets;
mod psd_options;
pub mod raster_effects;
pub mod rearrange_artboards;
pub mod recolor;
mod recovery;
pub mod saturate;
@@ -94,6 +95,7 @@ pub use export_for_screens::open as open_export_for_screens;
pub(crate) use export_for_screens::{
KIND as EXPORT_FOR_SCREENS, formats as screen_formats, open_assets as open_export_for_screens_assets, saved_rows as screen_saved_rows,
};
pub(crate) use new_document::preset_name;
pub use new_document::{open as open_new_document, preset_card};
pub use png_options::open as open_raster_options;
pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset};
@@ -277,6 +279,7 @@ registry! {
PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC,
LayerOptions: [layer_options::KIND] => layer_options::SPEC,
LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC,
RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC,
}
/// The button labels the shared dialog frame can show (OK, discard and the fixed Cancel/Close),
+58 -8
View File
@@ -190,7 +190,7 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.vertical(|ui| {
ui.set_width(640.0);
ui.set_min_height(HEIGHT - 32.0);
presets(app, ui, &mut d);
b.create |= presets(app, ui, &mut d);
});
});
egui::Frame::NONE.fill(t.panel_darker).inner_margin(egui::Margin::same(18)).show(ui, |ui| {
@@ -205,8 +205,9 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
b.finish(app, ctx, d);
}
/// The category tabs and the chosen category's preset cards.
fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
/// The category tabs and the chosen category's preset cards: a click chooses one, a double-click
/// also creates it (true then).
fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
let names: Vec<&str> = newdoc::category_names().collect();
let cat = names.iter().position(|n| n.eq_ignore_ascii_case(&d.str("category"))).unwrap_or(0);
@@ -227,20 +228,24 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
if list.is_empty() {
let hint = if cat == 1 { tl!("Presets you save with the Save Preset button appear here.") } else { tl!("Documents you create appear here.") };
ui.label(egui::RichText::new(hint).color(t.text_dim));
return;
return false;
}
let mut create = false;
egui::ScrollArea::vertical().id_salt(("newdoc-presets", cat)).max_height(HEIGHT - 110.0).auto_shrink([false, false]).show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(12.0, 12.0);
let (w, h, preset) = (d.f64("width", 0.0), d.f64("height", 0.0), d.str("preset"));
for s in &list {
let selected = d.fields.contains_key(APPLIED) && s.name == preset && s.width == w && s.height == h;
if preset_card(ui, s, selected).clicked() {
let card = preset_card(ui, s, selected);
if card.clicked() || card.double_clicked() {
apply(d, s);
}
create |= card.double_clicked();
}
});
});
create
}
/// Is `name` a built-in preset's? Those are ours (translated); Recent and Saved hold the names of
@@ -250,7 +255,7 @@ fn is_builtin_preset(name: &str) -> bool {
}
/// A preset's name as shown: a built-in one translated, the user's as it is.
fn preset_name(name: &str) -> &str {
pub(crate) fn preset_name(name: &str) -> &str {
if is_builtin_preset(name) { tl!(name) } else { name }
}
@@ -345,7 +350,7 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut
// Close and Create at the bottom right.
ui.add_space((HEIGHT - (ui.cursor().top() - top) - 28.0).max(12.0));
ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 28.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
b.create = widgets::primary_button(ui, tl!("Create")).clicked();
b.create |= widgets::primary_button(ui, tl!("Create")).clicked();
ui.add_space(8.0);
b.close = widgets::secondary_button(ui, tl!("Close")).clicked();
});
@@ -558,7 +563,7 @@ fn show_more(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.horizontal(|ui| {
templates = widgets::secondary_button(ui, tl!("Templates…")).on_hover_text(tl!("New from Template")).clicked();
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
b.create = widgets::primary_button(ui, tl!("Create Document")).clicked();
b.create |= widgets::primary_button(ui, tl!("Create Document")).clicked();
ui.add_space(8.0);
// Cancel goes back to New Document.
if widgets::secondary_button(ui, tl!("Cancel")).clicked() {
@@ -610,6 +615,51 @@ mod tests {
app.ui.dialog.as_ref().unwrap().fields.get(k).cloned().unwrap_or_default()
}
/// A double-click on a preset card creates the document from it (#663); a click only chooses it.
#[test]
fn a_double_clicked_preset_creates_the_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.newDialog", json!({})).unwrap();
set(&mut app, "category", json!("Mobile"));
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
// Frames 50 ms apart, so two clicks a frame apart make a double-click.
let mut time = 0.0;
let mut run = |app: &mut VectorcraftApp, events| {
time += 0.05;
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
out.textures_delta.clear();
out
};
run(&mut app, vec![]);
// The first card of the category, found by its size line.
let card = |app: &mut VectorcraftApp, run: &mut dyn FnMut(&mut VectorcraftApp, Vec<egui::Event>) -> egui::FullOutput| {
let out = run(app, vec![]);
let mut texts = vec![];
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
texts.into_iter().find(|(t, _)| t.starts_with("Phone 393")).map(|(_, r)| r.center()).unwrap()
};
let at = card(&mut app, &mut run);
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
run(&mut app, vec![press(false)]);
assert!(app.ui.dialog.is_some() && app.session.documents().is_empty(), "a click only chooses it");
assert!(field(&app, "preset").as_str().is_some_and(|p| p == "Phone 393×852"), "{:?}", field(&app, "preset"));
run(&mut app, vec![press(true)]);
run(&mut app, vec![press(false)]);
assert!(app.ui.dialog.is_none(), "the double-click created it: {:?}", app.ui.status);
assert_eq!(app.session.documents().len(), 1);
}
#[test]
fn a_preset_fills_the_details_and_create_makes_the_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
@@ -0,0 +1,208 @@
//! Object → Artboards → Rearrange All Artboards (also the Artboards panel's button and menu, and
//! the Properties panel's Rearrange All): Layout (a grid by row or by column, one row or one
//! column), Layout Order (left to right or right to left), Columns (Rows for a grid by column),
//! Spacing and Move Artwork with Artboard, with the document's artboard count. OK runs
//! `artboard.rearrange` as one undo step (#681).
//!
//! Fields: `layout` (`gridByRow` | `gridByColumn` | `row` | `column`), `order` (`leftToRight` |
//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt) and `moveArtwork`.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::newdoc::ArtboardLayout;
use super::{DialogSpec, form, run_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of Rearrange All Artboards.
pub const KIND: &str = "rearrangeArtboards";
const CMD: &str = "artboard.rearrange";
/// Width of the label column.
const LABEL_W: f32 = 96.0;
pub(super) const SPEC: DialogSpec =
DialogSpec { heading: |_| tl!("Rearrange All Artboards").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
/// The fields a fresh dialog starts with.
pub fn fields() -> Value {
json!({"layout": "gridByRow", "order": "leftToRight", "columns": 2, "spacing": 20, "moveArtwork": true})
}
/// A layout's toggle: its tooltip and its artboards' cells (column, row) in their order, left to
/// right.
fn layout_glyph(l: ArtboardLayout) -> (&'static str, &'static [(u8, u8)]) {
match l {
ArtboardLayout::GridByRow => (tl!("Grid by Row"), &[(0, 0), (1, 0), (0, 1), (1, 1)]),
ArtboardLayout::GridByColumn => (tl!("Grid by Column"), &[(0, 0), (0, 1), (1, 0), (1, 1)]),
ArtboardLayout::Row => (tl!("Arrange by Row"), &[(0, 0), (1, 0), (2, 0)]),
ArtboardLayout::Column => (tl!("Arrange by Column"), &[(0, 0), (0, 1), (0, 2)]),
}
}
/// `cells` mirrored left to right when `rtl` (the order the layout toggles preview).
fn mirrored(cells: &[(u8, u8)], rtl: bool) -> Vec<(u8, u8)> {
let last = cells.iter().map(|c| c.0).max().unwrap_or(0);
cells.iter().map(|&(x, y)| (if rtl { last - x } else { x }, y)).collect()
}
/// `artboard.rearrange` parameters from the fields.
fn params(d: &Dialog) -> Value {
json!({
"layout": d.str("layout"), "order": d.str("order"), "columns": d.f64("columns", 2.0),
"spacing": d.f64("spacing", 20.0), "moveArtwork": d.bool("moveArtwork"),
})
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let unit = app.session.general_unit();
let n = app.session.active().map_or(0, |doc| doc.doc.artboards.len());
let layout = ArtboardLayout::parse(&d.str("layout")).unwrap_or_default();
let rtl = d.str("order") == "rightToLeft";
widgets::label_row(ui, tl!("Layout:"), LABEL_W, |ui| {
ui.spacing_mut().item_spacing.x = 2.0;
for l in ArtboardLayout::ALL {
let (tip, cells) = layout_glyph(l);
if widgets::layout_button(ui, &mirrored(cells, rtl), layout == l, tip) {
d.fields.insert("layout".into(), json!(l.id()));
}
}
});
ui.add_space(4.0);
widgets::label_row(ui, tl!("Layout Order:"), LABEL_W, |ui| {
ui.spacing_mut().item_spacing.x = 2.0;
// One column reads the same either way.
ui.add_enabled_ui(layout != ArtboardLayout::Column, |ui| {
for (value, cells, tip) in [
("leftToRight", [(0, 0), (1, 0)], tl!("Change to Left-to-Right Layout")),
("rightToLeft", [(1, 0), (0, 0)], tl!("Change to Right-to-Left Layout")),
] {
if widgets::layout_button(ui, &cells, (value == "rightToLeft") == rtl, tip) {
d.fields.insert("order".into(), json!(value));
}
}
});
});
ui.add_space(4.0);
// The rows of a grid by column; one row or column has no count to set.
let label = if layout == ArtboardLayout::GridByColumn { tl!("Rows:") } else { tl!("Columns:") };
widgets::label_row(ui, label, LABEL_W, |ui| {
let grid = matches!(layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn);
ui.add_enabled_ui(grid, |ui| {
let most = n.max(1) as f64;
if let Some(v) = widgets::spin_plain(ui, "rearrange-columns", d.f64("columns", 2.0), "", 0, 76.0, 1.0, 1.0, &[]) {
d.fields.insert("columns".into(), json!(v.round().clamp(1.0, most)));
}
});
});
ui.add_space(4.0);
widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| {
form::length(ui, d, "spacing", unit, 100.0);
});
ui.add_space(4.0);
widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| {
form::check(ui, d, "moveArtwork", tl!("Move Artwork with Artboard"));
});
ui.add_space(8.0);
widgets::dim_label(ui, &crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &n.to_string())]));
false
}
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
run_and_close(app, CMD, params(d))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
/// A frame of the open dialog with `events` → the texts painted. The dialog measures itself on
/// its first frame, so a fresh context needs two.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<String> {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect()
}
fn context() -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
ctx
}
fn origins(app: &VectorcraftApp) -> Vec<(f64, f64)> {
app.session.active().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect()
}
/// #681: the menu item opens the dialog with the artboard count; Columns reads Rows for a grid
/// by column; OK lays the artboards out right to left, as one undo step.
#[test]
fn opens_from_the_menu_and_rearranges_by_layout_and_order() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
// The menu item has no params of its own: it opens this dialog, not the generic one.
let (id, p) = crate::menus::click_target("Rearrange All Artboards…", CMD, &Value::Null);
crate::menus::invoke(&mut app, &id, p);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND));
let ctx = context();
frame(&mut app, &ctx, vec![]);
let texts = frame(&mut app, &ctx, vec![]);
for want in ["Rearrange All Artboards", "Layout:", "Layout Order:", "Columns:", "Spacing:", "Move Artwork with Artboard", "Artboards: 3"] {
assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}");
}
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("layout".into(), json!("gridByColumn"));
let texts = frame(&mut app, &ctx, vec![]);
assert!(texts.iter().any(|t| t == "Rows:") && !texts.iter().any(|t| t == "Columns:"), "{texts:?}");
// One row, right to left, 10 pt apart.
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("layout".into(), json!("row"));
d.fields.insert("order".into(), json!("rightToLeft"));
d.fields.insert("spacing".into(), json!(10));
frame(&mut app, &ctx, vec![]);
let undo = app.session.doc().unwrap().history.undo.len();
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(origins(&app), [(220.0, 0.0), (110.0, 0.0), (0.0, 0.0)]);
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
}
/// Clicking the layout and order toggles sets the fields (the toggles' rects from the frame).
#[test]
fn the_toggles_set_layout_and_order() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 4})).unwrap();
app.run("ui.menuDialog", json!({ "command": CMD })).unwrap();
let ctx = context();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
// The 26-point toggles, left to right then top to bottom: four layouts, then two orders.
let toggles: Vec<egui::Rect> = ctx.viewport(|vp| {
let mut r: Vec<egui::Rect> = vp
.prev_pass
.widgets
.layers()
.flat_map(|(_, w)| w.iter())
.filter(|w| w.sense.senses_click() && w.rect.width() == 26.0 && w.rect.height() == 26.0)
.map(|w| w.rect)
.collect();
r.sort_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left())));
r
});
assert_eq!(toggles.len(), 6, "{toggles:?}");
for (i, key, want) in [(3, "layout", "column"), (1, "layout", "gridByColumn"), (5, "order", "rightToLeft")] {
let at = toggles[i].center();
let b = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), b(true)]);
frame(&mut app, &ctx, vec![b(false)]);
assert_eq!(app.ui.dialog.as_ref().unwrap().str(key), want);
// A frame for the order toggles to follow the layout (one column greys them).
frame(&mut app, &ctx, vec![]);
}
crate::dialogs::confirm(&mut app).unwrap();
// Two rows (Columns 2 reads Rows for a grid by column), the first column at the right.
assert_eq!(origins(&app), [(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)]);
}
}
+17 -1
View File
@@ -76,6 +76,7 @@
Add to Swatches Agregar a muestras
Add Used Colors Agregar colores usados
Additional Plug-ins Folder Carpeta de plugins adicionales
Additional Fonts Folder Carpeta de fuentes adicionales
Adjust Adjoining Width Points Ajustar puntos de anchura contiguos
Adjust Color Balance… Ajustar equilibrio de color…
Adjust Colors Ajustar colores
@@ -1399,6 +1400,9 @@
Marks and Bleed Marcas y sangrado
Marks and Bleeds Marcas y sangrados
Match User Interface Brightness Igualar brillo de la interfaz de usuario
Light Gray Gris claro
Medium Gray Gris medio
Dark Gray Gris oscuro
Materials… Materiales…
Matte Mate
Matte: Mate:
@@ -1954,7 +1958,16 @@
Rating: Clasificación:
Real World: Mundo real:
Real-time Drawing and Editing Dibujo y edición en tiempo real
Rearrange All Artboards (on the roadmap) Reorganizar todas las mesas de trabajo (en la hoja de ruta)
Rearrange All Artboards Reorganizar todas las mesas de trabajo
Rearrange All Reorganizar todo
Layout Order: Orden de diseño:
Change to Left-to-Right Layout Cambiar a diseño de izquierda a derecha
Grid by Row Cuadrícula por filas
Grid by Column Cuadrícula por columnas
Arrange by Row Organizar en una fila
Arrange by Column Organizar en una columna
Move Artwork with Artboard Mover la ilustración con la mesa de trabajo
Artboards: {n} Mesas de trabajo: {n}
Rearrange All Artboards… Reorganizar todas las mesas de trabajo…
Recall Selection Recuperar selección
RECENT RECIENTES
@@ -2987,6 +3000,9 @@
to zoom in | para acercar |
to zoom out | para alejar |
to zoom into an area para acercar un área
Hold Mantener pulsado
right or left to zoom in or out | a la derecha o a la izquierda para acercar o alejar |
to keep zooming para seguir haciendo zoom
an object to copy its attributes | en un objeto para copiar sus atributos |
to apply the selection's to it | para aplicarle los de la selección |
to sample a color para muestrear un color
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17 -1
View File
@@ -77,6 +77,7 @@
Add to Swatches Ajouter au nuancier
Add Used Colors Ajouter les couleurs utilisées
Additional Plug-ins Folder Dossier de modules externes supplémentaires
Additional Fonts Folder Dossier de polices supplémentaires
Adjust Adjoining Width Points Ajuster les points de largeur adjacents
Adjust Color Balance… Régler la balance des couleurs…
Adjust Colors Régler les couleurs
@@ -1398,6 +1399,9 @@
Marks and Bleed Marques et fond perdu
Marks and Bleeds Marques et fonds perdus
Match User Interface Brightness Adapter à la luminosité de l’interface
Light Gray Gris clair
Medium Gray Gris moyen
Dark Gray Gris foncé
Materials… Matériaux…
Matte Détourage
Matte: Détourage :
@@ -1951,7 +1955,16 @@
Rating: Classement :
Real World: Monde réel :
Real-time Drawing and Editing Dessin et édition en temps réel
Rearrange All Artboards (on the roadmap) Réorganiser tous les plans de travail (prévu)
Rearrange All Artboards Réorganiser tous les plans de travail
Rearrange All Tout réorganiser
Layout Order: Ordre de disposition :
Change to Left-to-Right Layout Passer à la disposition de gauche à droite
Grid by Row Grille par ligne
Grid by Column Grille par colonne
Arrange by Row Disposer en ligne
Arrange by Column Disposer en colonne
Move Artwork with Artboard Déplacer l’illustration avec le plan de travail
Artboards: {n} Plans de travail : {n}
Rearrange All Artboards… Réorganiser tous les plans de travail…
Recall Selection Rappeler la sélection
RECENT RÉCENTS
@@ -2984,6 +2997,9 @@
to zoom in | pour effectuer un zoom avant |
to zoom out | pour effectuer un zoom arrière |
to zoom into an area pour zoomer sur une zone
Hold Maintenir
right or left to zoom in or out | vers la droite ou la gauche pour effectuer un zoom avant ou arrière |
to keep zooming pour continuer le zoom
an object to copy its attributes | sur un objet pour copier ses attributs |
to apply the selection's to it | pour lui appliquer ceux de la sélection |
to sample a color pour prélever une couleur
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17 -1
View File
@@ -76,6 +76,7 @@
Add to Swatches Aggiungi ai campioni
Add Used Colors Aggiungi colori usati
Additional Plug-ins Folder Cartella plug-in aggiuntivi
Additional Fonts Folder Cartella font aggiuntivi
Adjust Adjoining Width Points Regola punti di larghezza adiacenti
Adjust Color Balance… Regola bilanciamento colore…
Adjust Colors Regola colori
@@ -1399,6 +1400,9 @@
Marks and Bleed Segni e abbondanza
Marks and Bleeds Segni e abbondanze
Match User Interface Brightness Adatta alla luminosità dell'interfaccia utente
Light Gray Grigio chiaro
Medium Gray Grigio medio
Dark Gray Grigio scuro
Materials… Materiali…
Matte Colore alone
Matte: Colore alone:
@@ -1954,7 +1958,16 @@
Rating: Valutazione:
Real World: Mondo reale:
Real-time Drawing and Editing Disegno e modifica in tempo reale
Rearrange All Artboards (on the roadmap) Ridisponi tutte le tavole da disegno (in programma)
Rearrange All Artboards Ridisponi tutte le tavole da disegno
Rearrange All Ridisponi tutto
Layout Order: Ordine del layout:
Change to Left-to-Right Layout Passa al layout da sinistra a destra
Grid by Row Griglia per righe
Grid by Column Griglia per colonne
Arrange by Row Disponi in una riga
Arrange by Column Disponi in una colonna
Move Artwork with Artboard Sposta la grafica con la tavola da disegno
Artboards: {n} Tavole da disegno: {n}
Rearrange All Artboards… Ridisponi tutte le tavole da disegno…
Recall Selection Richiama selezione
RECENT RECENTI
@@ -2987,6 +3000,9 @@
to zoom in | per ingrandire |
to zoom out | per ridurre |
to zoom into an area per ingrandire un'area
Hold Tieni premuto
right or left to zoom in or out | a destra o a sinistra per ingrandire o ridurre |
to keep zooming per continuare lo zoom
an object to copy its attributes | su un oggetto per copiarne gli attributi |
to apply the selection's to it | per applicargli quelli della selezione |
to sample a color per campionare un colore
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17 -1
View File
@@ -675,6 +675,9 @@
to transform | :変形 |
to zoom in | :拡大 |
to zoom into an area :範囲を拡大
Hold 長押し
right or left to zoom in or out | :右で拡大、左で縮小 |
to keep zooming :拡大または縮小し続ける
to zoom out | :縮小 |
while dragging to move perpendicular to the plane | :ドラッグ中に面と垂直に移動 |
(closest) (最も近い)
@@ -721,6 +724,7 @@
Add to Selection 選択範囲に追加
Add to Swatches スウォッチに追加
Additional Plug-ins Folder 追加プラグインフォルダー
Additional Fonts Folder 追加フォントフォルダー
Adjust Adjoining Width Points 隣接する幅ポイントを調整
Adjust Colors カラーを調整
Adjust Options: 調整オプション:
@@ -1573,6 +1577,9 @@
Mark as trapped トラップ済みとしてマーク
Marks トンボ
Match User Interface Brightness ユーザーインターフェイスの明るさに合わせる
Light Gray ライトグレー
Medium Gray ミディアムグレー
Dark Gray ダークグレー
Matte: マット:
Maximize 最大化
Maximum Editability 編集機能を最大限に保持
@@ -1981,7 +1988,16 @@
Rating: 評価:
Real World: 実寸:
Real-time Drawing and Editing リアルタイム描画および編集
Rearrange All Artboards (on the roadmap) すべてのアートボードを再配置 (今後対応予定)
Rearrange All Artboards すべてのアートボードを再配置
Rearrange All すべて再配置
Layout Order: レイアウト順序:
Change to Left-to-Right Layout 左から右のレイアウトに変更
Grid by Row 行ごとのグリッド
Grid by Column 列ごとのグリッド
Arrange by Row 1 行に配置
Arrange by Column 1 列に配置
Move Artwork with Artboard アートボードと一緒にアートワークを移動
Artboards: {n} アートボード: {n}
Recall Selection 選択範囲を呼び出し
Recent Colors 最近使用したカラー
Recent Files 最近使ったファイル
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17 -1
View File
@@ -78,6 +78,9 @@
to transform | para transformar |
to zoom in | para ampliar |
to zoom into an area para ampliar uma área
Hold Manter pressionado
right or left to zoom in or out | para a direita ou a esquerda para ampliar ou reduzir |
to keep zooming para continuar o zoom
to zoom out | para reduzir |
while dragging to move perpendicular to the plane | ao arrastar para mover perpendicularmente ao plano |
(closest) (mais próximo)
@@ -135,6 +138,7 @@
Add to Selection Adicionar à Seleção
Add to Swatches Adicionar às Amostras
Additional Plug-ins Folder Pasta Adicional de Plug-ins
Additional Fonts Folder Pasta Adicional de Fontes
Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes
Adjust Color Balance… Ajustar Equilíbrio de Cores…
Adjust Colors Ajustar Cores
@@ -1258,6 +1262,9 @@
Marker… Marcador…
Marks Marcas
Match User Interface Brightness Corresponder ao Brilho da Interface do Usuário
Light Gray Cinza Claro
Medium Gray Cinza Médio
Dark Gray Cinza Escuro
Materials… Materiais…
Matte: Fosco:
Maximize Maximizar
@@ -1743,7 +1750,16 @@
Rating: Avaliação:
Real World: Mundo Real:
Real-time Drawing and Editing Desenho e Edição em Tempo Real
Rearrange All Artboards (on the roadmap) Reorganizar Todas as Mesas de Trabalho (no roadmap)
Rearrange All Artboards Reorganizar Todas as Mesas de Trabalho
Rearrange All Reorganizar Tudo
Layout Order: Ordem do Layout:
Change to Left-to-Right Layout Mudar para Layout da Esquerda para a Direita
Grid by Row Grade por Linha
Grid by Column Grade por Coluna
Arrange by Row Organizar em Linha
Arrange by Column Organizar em Coluna
Move Artwork with Artboard Mover Arte com a Mesa de Trabalho
Artboards: {n} Mesas de Trabalho: {n}
Rearrange All Artboards… Reorganizar Todas as Mesas de Trabalho…
Recall Selection Relembrar Seleção
Recent Colors Cores Recentes
Can't render this file because it contains an unexpected character in line 6 and column 47.
+17 -1
View File
@@ -74,6 +74,7 @@
Add to Swatches Добавить в образцы
Add Used Colors Добавить использованные цвета
Additional Plug-ins Folder Папка дополнительных модулей
Additional Fonts Folder Папка дополнительных шрифтов
Adjust Adjoining Width Points Настроить смежные точки ширины
Adjust Color Balance… Настроить цветовой баланс…
Adjust Colors Настроить цвета
@@ -1397,6 +1398,9 @@
Marks and Bleed Метки и вылет
Marks and Bleeds Метки и вылеты
Match User Interface Brightness Согласовать с яркостью интерфейса
Light Gray Светло-серый
Medium Gray Средне-серый
Dark Gray Тёмно-серый
Materials… Материалы…
Matte Мат
Matte: Мат:
@@ -1950,7 +1954,16 @@
Rating: Рейтинг:
Real World: Реальный мир:
Real-time Drawing and Editing Рисование и редактирование в реальном времени
Rearrange All Artboards (on the roadmap) Переставить все монтажные области (в плане развития)
Rearrange All Artboards Переставить все монтажные области
Rearrange All Переставить все
Layout Order: Порядок макета:
Change to Left-to-Right Layout Переключить на макет слева направо
Grid by Row Сетка по строкам
Grid by Column Сетка по столбцам
Arrange by Row Расположить в строку
Arrange by Column Расположить в столбец
Move Artwork with Artboard Перемещать иллюстрацию вместе с монтажной областью
Artboards: {n} Монтажные области: {n}
Rearrange All Artboards… Переставить все монтажные области…
Recall Selection Восстановить выделение
RECENT ПОСЛЕДНИЕ
@@ -2983,6 +2996,9 @@
to zoom in | для увеличения |
to zoom out | для уменьшения |
to zoom into an area для увеличения области
Hold Удерживать
right or left to zoom in or out | вправо или влево для увеличения или уменьшения |
to keep zooming для непрерывного масштабирования
an object to copy its attributes | в объект для копирования его атрибутов |
to apply the selection's to it | для применения атрибутов выделения к нему |
to sample a color для взятия образца цвета
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17 -1
View File
@@ -79,6 +79,7 @@
Add to Swatches 添加到色板
Add Used Colors 添加已用颜色
Additional Plug-ins Folder 附加增效工具文件夹
Additional Fonts Folder 附加字体文件夹
Adjust Adjoining Width Points 调整相邻宽度点
Adjust Color Balance… 调整色彩平衡…
Adjust Colors 调整颜色
@@ -1381,6 +1382,9 @@
Marks and Bleed 标记和出血
Marks and Bleeds 标记和出血
Match User Interface Brightness 匹配用户界面亮度
Light Gray 浅灰色
Medium Gray 中灰色
Dark Gray 深灰色
Materials… 材质…
Matte 杂边
Matte: 杂边:
@@ -1928,7 +1932,16 @@
Rating: 等级:
Real World: 真实世界:
Real-time Drawing and Editing 实时绘图和编辑
Rearrange All Artboards (on the roadmap) 重新排列所有画板 (规划中)
Rearrange All Artboards 重新排列所有画板
Rearrange All 全部重新排列
Layout Order: 布局顺序:
Change to Left-to-Right Layout 更改为由左至右版面配置
Grid by Row 按行网格排列
Grid by Column 按列网格排列
Arrange by Row 排成一行
Arrange by Column 排成一列
Move Artwork with Artboard 随画板移动图稿
Artboards: {n} 画板:{n}
Rearrange All Artboards… 重新排列所有画板…
Recall Selection 召回选区
RECENT 最近使用
@@ -2927,6 +2940,9 @@
to zoom in | 以放大 |
to zoom out | 以缩小 |
to zoom into an area 以放大指定区域
Hold 按住
right or left to zoom in or out | 向右以放大、向左以缩小 |
to keep zooming 以持续缩放
an object to copy its attributes | 选择对象以复制其属性 |
to apply the selection's to it | 以将所选对象属性应用到它 |
to sample a color 以取样颜色
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17 -1
View File
@@ -87,6 +87,7 @@
Add to Swatches 新增至色票
Add Used Colors 新增使用中的顏色
Additional Plug-ins Folder 額外的增效模組資料夾
Additional Fonts Folder 額外的字體資料夾
Adjust Adjoining Width Points 調整相鄰寬度點
Adjust Color Balance… 調整色彩平衡…
Adjust Colors 調整顏色
@@ -1417,6 +1418,9 @@
Marks and Bleed 標記與出血
Marks and Bleeds 標記與出血
Match User Interface Brightness 符合使用者介面亮度
Light Gray 淺灰色
Medium Gray 中灰色
Dark Gray 深灰色
Materials… 材質…
Matte 邊緣色
Matte: 遮色:
@@ -1974,7 +1978,16 @@
Rating: 評等:
Real World: 真實世界:
Real-time Drawing and Editing 即時繪圖與編輯
Rearrange All Artboards (on the roadmap) 重新排列所有工作區域 (規劃中)
Rearrange All Artboards 重新排列所有工作區域
Rearrange All 全部重新排列
Layout Order: 版面配置順序:
Change to Left-to-Right Layout 變更為由左至右版面配置
Grid by Row 依列格狀排列
Grid by Column 依欄格狀排列
Arrange by Row 排成一列
Arrange by Column 排成一欄
Move Artwork with Artboard 隨工作區域移動圖稿
Artboards: {n} 工作區域:{n}
Rearrange All Artboards… 重新排列所有工作區域…
Recall Selection 叫出選取範圍
RECENT 最近使用
@@ -3012,6 +3025,9 @@
to zoom in | 可放大 |
to zoom out | 可縮小 |
to zoom into an area 可放大至指定區域
Hold 按住
right or left to zoom in or out | 向右可放大、向左可縮小 |
to keep zooming 可持續縮放
an object to copy its attributes | 物件可複製其屬性 |
to apply the selection's to it | 可將選取範圍的屬性套用至該物件 |
to sample a color 可取樣顏色
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -291,6 +291,8 @@ pub struct CacheKey {
/// View › Pixel Preview: the document pixels rendered (x0, y0, x1, y1), one per point, shown
/// with hard edges. None: the art is rendered for the screen.
pub pixel: Option<[i64; 4]>,
/// Images sampled smoothly ([`vectorcraft_render::RenderOptions::smooth_images`]).
pub smooth_images: bool,
}
#[derive(Clone, Copy, Debug, Default)]
+3 -2
View File
@@ -473,7 +473,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|object.path.offsetPath|object.path.simplify|object.path.splitIntoGrid|object.vectorHalftone|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, envelopeWarp, envelopeMesh, envelopeOptions; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|object.path.offsetPath|object.path.simplify|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, envelopeWarp, envelopeMesh, envelopeOptions; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
),
(
"ui.widthPointEdit",
@@ -2196,7 +2196,7 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<Item>)> {
"Artboards",
vec![
c("Convert to Artboards", "artboard.convertToArtboards"),
cp("Rearrange All Artboards…", "artboard.rearrange", json!({"columns": 2, "spacing": 20, "moveArtwork": true})),
c("Rearrange All Artboards…", "artboard.rearrange"),
Sep,
c("Fit to Artwork Bounds", "artboard.fitToArt"),
c("Fit to Selected Art", "artboard.fitToSelection"),
@@ -2870,6 +2870,7 @@ fn menu_dialog(id: &str) -> Option<(&'static str, Value)> {
"object.path.simplify" => ("simplify", json!({"tolerance": "1 pt"})),
"object.path.splitIntoGrid" => ("splitIntoGrid", json!({"rows": 2, "columns": 2, "gutter": "12 pt"})),
"object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()),
"artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::fields()),
_ => return None,
})
}
+11 -2
View File
@@ -113,7 +113,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
});
let n = abs.len();
widgets::bottom_bar(ui, |ui| {
widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards (on the roadmap)"), false, false, 24.0);
if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards"), false, n > 1, 24.0).clicked() {
open_rearrange(app);
}
ui.add_space((ui.available_width() - 4.0 * 28.0).max(0.0));
if widgets::icon_button_enabled(ui, "dc-arrow-up", tl!("Move Up"), false, sel > 0, 24.0).clicked()
&& app.run("artboard.reorder", json!({"index": sel, "to": sel - 1})).is_ok()
@@ -140,6 +142,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
});
}
/// Open Rearrange All Artboards (#681).
pub(crate) fn open_rearrange(app: &mut VectorcraftApp) {
app.run("ui.menuDialog", json!({ "command": "artboard.rearrange" })).ok();
}
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let n = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0);
let sel = selected(app, n);
@@ -161,7 +168,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
if menu_item(ui, tl!("Artboard Options…"), n > 0, false) {
app.select_tool("artboard");
}
menu_item(ui, tl!("Rearrange All Artboards…"), false, false);
if menu_item(ui, tl!("Rearrange All Artboards…"), n > 1, false) {
open_rearrange(app);
}
ui.separator();
if menu_item(ui, tl!("Fit to Artwork Bounds"), n > 0, false) {
app.run("artboard.fitToArt", json!({"index": sel})).ok();
+127 -4
View File
@@ -3,6 +3,7 @@
use egui::Ui;
use serde_json::json;
use vectorcraft_doc::{LiveShape, NodeKind, Unit};
use vectorcraft_engine::cmd::newdoc;
use super::{corner_radius_row, first_selected, pstate, set_pstate};
use crate::theme::Tokens;
@@ -196,8 +197,9 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool {
}
}
/// Edit Artboards (the Artboard tool): the active artboard's name, position and size, New Artboard
/// and Delete Artboard, and Exit back to the Selection tool (#530).
/// Edit Artboards (the Artboard tool): the active artboard's name, position and size, its preset and
/// orientation (#671), New Artboard and Delete Artboard, and Quick Actions: Rearrange All (#681) and
/// Exit back to the Selection tool (#530).
fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
let units = app.session.general_unit();
let n = app.session.active().map_or(0, |d| d.doc.artboards.len());
@@ -220,6 +222,7 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.end_row();
}
});
artboard_size_row(app, ui, i, ab.rect.width(), ab.rect.height());
}
ui.add_space(4.0);
let w = (ui.available_width() - 6.0) / 2.0;
@@ -233,8 +236,67 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
});
divider(ui);
section_header(ui, tl!("Quick Actions"));
if widgets::flat_button(ui, tl!("Exit"), w).clicked() {
app.select_tool("selection");
ui.horizontal(|ui| {
rearrange_button(app, ui, n, w);
if widgets::flat_button(ui, tl!("Exit"), w).clicked() {
app.select_tool("selection");
}
});
}
/// Rearrange All (#681): opens Rearrange All Artboards; disabled with fewer than two artboards.
fn rearrange_button(app: &mut VectorcraftApp, ui: &mut Ui, artboards: usize, w: f32) {
if ui.add_enabled_ui(artboards > 1, |ui| widgets::flat_button(ui, tl!("Rearrange All"), w)).inner.clicked() {
super::artboards::open_rearrange(app);
}
}
/// Artboard `i`'s size preset (New Document's saved and built-in presets, by category, either way
/// round; Custom when its `w` × `h` points match none) and its orientation. A preset sizes it in its
/// current orientation; the other orientation swaps its width and height. Its top-left corner stays
/// put either way.
fn artboard_size_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, w: f64, h: f64) {
let landscape = w > h;
// A preset `pw` × `ph` turned to the artboard's orientation.
let turned = |pw: f64, ph: f64| if (pw > ph) == landscape || pw == ph { (pw, ph) } else { (ph, pw) };
let same = |s: &newdoc::DocSettings| {
let (pw, ph) = turned(s.width, s.height);
(pw - w).abs() < 0.01 && (ph - h).abs() < 0.01
};
// Recent holds documents made, not presets.
let cats: Vec<(&str, Vec<newdoc::DocSettings>)> = newdoc::category_names()
.filter(|c| !c.eq_ignore_ascii_case("Recent"))
.filter_map(|c| Some((c, newdoc::category(&app.session, c)?)))
.filter(|(_, l)| !l.is_empty())
.collect();
let current = cats.iter().flat_map(|(_, l)| l).find(|s| same(s)).map_or(tl!("Custom"), |s| crate::dialogs::preset_name(&s.name)).to_string();
let mut size = None;
ui.horizontal(|ui| {
dim_label(ui, tl!("Preset:"));
size = widgets::combo(ui, "ab-preset", &current, 140.0, false, |ui| {
let mut chosen = None;
for (cat, list) in &cats {
ui.menu_button(tl!(cat), |ui| {
widgets::menu_scroll(ui, |ui| {
for s in list {
if widgets::menu_item_name(ui, crate::dialogs::preset_name(&s.name), true, same(s)) {
chosen = Some(turned(s.width, s.height));
}
}
});
});
}
chosen
});
ui.spacing_mut().item_spacing.x = 2.0;
for (is_landscape, tip) in [(false, tl!("Portrait")), (true, tl!("Landscape"))] {
if widgets::orientation_button(ui, is_landscape, landscape == is_landscape, tip) && landscape != is_landscape {
size = Some((h, w));
}
}
});
if let Some((width, height)) = size {
app.run("artboard.setProps", json!({"index": i, "width": width, "height": height})).ok();
}
}
@@ -257,6 +319,10 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
app.select_tool("artboard");
}
});
let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len());
if artboards > 1 {
rearrange_button(app, ui, artboards, w);
}
divider(ui);
section_header(ui, tl!("Appearance"));
fill_stroke_rows(app, ui);
@@ -520,4 +586,61 @@ mod tests {
click(&mut app, &ctx, &texts, "Exit");
assert_eq!(app.session.tool_id(), "selection");
}
/// #681: Rearrange All opens Rearrange All Artboards in one click, from the Document section
/// (only with several artboards) and from Edit Artboards' Quick Actions.
#[test]
fn rearrange_all_opens_the_dialog() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let ctx = egui::Context::default();
assert!(!frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Rearrange All"), "one artboard: nothing to rearrange");
app.run("artboard.new", json!({})).unwrap();
let texts = frame(&mut app, &ctx, vec![]);
click(&mut app, &ctx, &texts, "Rearrange All");
let kind = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| d.kind.clone());
assert_eq!(kind(&app).as_deref(), Some(crate::dialogs::rearrange_artboards::KIND));
app.ui.dialog = None;
app.select_tool("artboard");
let texts = frame(&mut app, &ctx, vec![]);
click(&mut app, &ctx, &texts, "Rearrange All");
assert_eq!(kind(&app).as_deref(), Some(crate::dialogs::rearrange_artboards::KIND));
}
/// #671: Edit Artboards shows the artboard's preset (Custom when it matches none) and its
/// orientation; the other orientation swaps its width and height, its corner staying put.
#[test]
fn edit_artboards_shows_the_preset_and_flips_the_orientation() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"preset": "Letter"})).unwrap();
app.run("artboard.setProps", json!({"index": 0, "x": 10, "y": 20})).unwrap();
app.select_tool("artboard");
let ctx = egui::Context::default();
let texts = frame(&mut app, &ctx, vec![]);
assert!(texts.iter().any(|(t, _)| t == "Preset:") && texts.iter().any(|(t, _)| t == "Letter"), "{texts:?}");
// The row's clickable widgets, left to right: the preset combo, Portrait, Landscape.
let row = texts.iter().find(|(t, _)| t == "Preset:").map(|(_, r)| *r).unwrap();
let buttons: Vec<Rect> = ctx.viewport(|vp| {
let mut r: Vec<Rect> = vp
.prev_pass
.widgets
.layers()
.flat_map(|(_, w)| w.iter())
.filter(|w| w.sense.senses_click() && w.rect.y_range().contains(row.center().y) && w.rect.left() > row.right())
.map(|w| w.rect)
.collect();
r.sort_by(|a, b| a.left().total_cmp(&b.left()));
r
});
let landscape = buttons.last().unwrap().center();
let press = |pressed| Event::PointerButton { pos: landscape, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![Event::PointerMoved(landscape), press(true)]);
frame(&mut app, &ctx, vec![press(false)]);
let rect = app.session.active().unwrap().doc.artboards[0].rect;
assert_eq!((rect.x0, rect.y0, rect.width(), rect.height()), (10.0, 20.0, 792.0, 612.0), "landscape, same corner");
let texts = frame(&mut app, &ctx, vec![]);
assert!(texts.iter().any(|(t, _)| t == "Letter"), "still Letter, turned: {texts:?}");
app.run("artboard.setProps", json!({"index": 0, "width": 333})).unwrap();
assert!(frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Custom"));
}
}
+43 -4
View File
@@ -80,13 +80,26 @@ pub fn restore(app: &mut VectorcraftApp) {
#[derive(Clone, Copy, PartialEq)]
struct Applied {
brightness: Brightness,
white_canvas: bool,
/// User Interface › Canvas Color, unless it matches the interface brightness.
canvas: Option<egui::Color32>,
threads: i32,
tool_tips: bool,
scrub: bool,
bare_points: bool,
}
/// User Interface › Canvas Color: the canvas around the artboards, or `None` to match the
/// interface brightness. The greys keep the white page's edge in view (#663).
fn canvas_color(key: &str) -> Option<egui::Color32> {
match key {
"white" => Some(egui::Color32::WHITE),
"lightGray" => Some(egui::Color32::from_gray(0xc8)),
"mediumGray" => Some(egui::Color32::from_gray(0x96)),
"darkGray" => Some(egui::Color32::from_gray(0x5a)),
_ => None,
}
}
/// Per frame: push UI-side preferences into egui / the renderer when they change.
pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
let p = &app.session.prefs;
@@ -97,7 +110,7 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
let want = Applied {
brightness: app.ui.brightness,
white_canvas: p.canvas_color == "white",
canvas: canvas_color(&p.canvas_color),
threads: p.render_threads,
tool_tips: p.show_tool_tips,
scrub: p.scrub_numeric_fields,
@@ -113,9 +126,9 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
ctx.global_style_mut(|s| s.interaction.tooltip_delay = delay);
crate::scrub::set_enabled(ctx, want.scrub);
crate::widgets::set_bare_numbers_are_points(ctx, want.bare_points);
if want.white_canvas {
if let Some(c) = want.canvas {
let mut t = Tokens::get(ctx);
t.pasteboard = egui::Color32::WHITE;
t.pasteboard = c;
ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t));
}
if prev.is_some_and(|pr| pr.threads != want.threads) {
@@ -244,6 +257,10 @@ fn category_fields(ui: &mut egui::Ui, d: &mut Dialog, cat: &str) {
PrefKind::Bool if sp.key == "numbersWithoutUnitsArePoints" => {
ui.add_enabled_ui(picas_in_use(d), |ui| bool_row(ui, d, sp.key, sp.label));
}
// Performance › Animated Zoom needs GPU Performance: dimmed while it is off.
PrefKind::Bool if sp.key == "animatedZoom" => {
ui.add_enabled_ui(d.bool("gpuPerformance"), |ui| bool_row(ui, d, sp.key, sp.label));
}
PrefKind::Bool => bool_row(ui, d, sp.key, sp.label),
PrefKind::Num { min, max, unit } => {
labeled(ui, sp.label, |ui| {
@@ -361,6 +378,28 @@ mod tests {
use crate::Services;
use vectorcraft_engine::Session;
/// User Interface › Canvas Color (#663): White and the three greys paint the canvas around the
/// artboards; Match User Interface Brightness keeps the theme's.
#[test]
fn canvas_color_choices_paint_the_pasteboard() {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
apply_runtime(&mut app, &ctx);
let themed = Tokens::get(&ctx).pasteboard;
for (key, want) in [
("white", egui::Color32::WHITE),
("lightGray", egui::Color32::from_gray(0xc8)),
("mediumGray", egui::Color32::from_gray(0x96)),
("darkGray", egui::Color32::from_gray(0x5a)),
("matchUi", themed),
] {
app.run("prefs.set", serde_json::json!({"key": "canvasColor", "value": key})).unwrap();
apply_runtime(&mut app, &ctx);
assert_eq!(Tokens::get(&ctx).pasteboard, want, "{key}");
}
assert!(app.run("prefs.set", serde_json::json!({"key": "canvasColor", "value": "pink"})).is_err());
}
fn app() -> VectorcraftApp {
VectorcraftApp::new(Session::new(), Services::default())
}
+43
View File
@@ -90,3 +90,46 @@ fn cmd_n_opens_the_new_document_dialog() {
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("newDocument"));
assert_eq!(app.session.documents().len(), 1, "no document is made until the dialog's OK");
}
/// One Home screen frame (no document open) with `events`: the texts drawn and where.
fn home_texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let raw =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 900.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| canvas::show(app, ui));
out.textures_delta.clear();
let mut texts = vec![];
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
texts
}
/// The Home screen lists the first recent files (#663), each by name and folder; a click opens it,
/// and one that can't be opened says so. With none, there is no Recent Files section.
#[test]
fn home_lists_recent_files_and_a_click_opens_one() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let has = |texts: &[(String, egui::Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
assert!(!has(&home_texts(&mut app, &ctx, vec![]), "Recent Files"), "none: no section");
let dir = std::env::temp_dir().join("vectorcraft-home-recent");
let missing = dir.join("Gone.svg").to_string_lossy().into_owned();
app.ui.recent_files = (0..9).map(|i| dir.join(format!("Drawing {i}.svg")).to_string_lossy().into_owned()).collect();
app.ui.recent_files.insert(0, missing);
let texts = home_texts(&mut app, &ctx, vec![]);
assert!(has(&texts, "Recent Files") && has(&texts, "Gone.svg") && has(&texts, "Drawing 4.svg"), "{texts:?}");
assert!(!has(&texts, "Drawing 5.svg"), "the first six only");
assert!(has(&texts, &dir.to_string_lossy()), "with its folder");
let at = texts.iter().find(|(t, _)| t == "Gone.svg").map(|(_, r)| r.center()).unwrap();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
home_texts(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(true)]);
home_texts(&mut app, &ctx, vec![press(false)]);
assert!(app.session.documents().is_empty());
assert!(!app.ui.status.is_empty(), "a file that can't be opened says so");
}
+1 -1
View File
@@ -78,7 +78,7 @@ fn slice_tool_cursors_are_drawn_in_code() {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(Default::default(), |ui| {
for c in [vectorcraft_tools::Cursor::Slice, vectorcraft_tools::Cursor::SliceSelect] {
assert!(crate::cursors::paint(ui.painter(), c, egui::pos2(50.0, 50.0)), "{c:?}");
assert!(crate::cursors::paint(ui.painter(), c, egui::pos2(50.0, 50.0), 1.0), "{c:?}");
}
});
out.textures_delta.clear();
+1 -1
View File
@@ -12,7 +12,7 @@ fn the_width_tool_has_its_own_cursors() {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter().clone();
for c in [Cursor::Width, Cursor::WidthAdd, Cursor::WidthPoint] {
assert!(crate::cursors::paint(&painter, c, egui::pos2(50.0, 50.0)), "{c:?} is drawn");
assert!(crate::cursors::paint(&painter, c, egui::pos2(50.0, 50.0), 1.0), "{c:?} is drawn");
}
});
out.textures_delta.clear();
+45
View File
@@ -1694,6 +1694,51 @@ pub fn orientation_button(ui: &mut Ui, landscape: bool, selected: bool, tip: &st
resp.on_hover_text(tl!(tip)).clicked()
}
/// An artboard-layout toggle drawn in code (Rearrange All Artboards): small artboards in the grid
/// cells `tiles` (column, row), tinted, and over them their order as a line from a dot on the first
/// to an arrowhead on the last; accent-drawn in a pressed well when `selected`, greyed in a disabled
/// `ui`. `tip` is shown as it is (the caller translates it). Returns clicked.
pub fn layout_button(ui: &mut Ui, tiles: &[(u8, u8)], selected: bool, tip: &str) -> bool {
let t = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(Vec2::splat(26.0), Sense::click());
let enabled = ui.is_enabled();
let bg = if selected {
t.tool_active
} else if resp.hovered() && enabled {
t.hover
} else {
Color32::TRANSPARENT
};
ui.painter().rect_filled(rect, CornerRadius::same(3), bg);
let color = if !enabled {
t.text_disabled
} else if selected {
t.accent
} else {
t.icon
};
// Cells at most 10 points a side in a 20-point square: a row's artboards stand tall, a
// column's lie flat.
let (cols, rows) = tiles.iter().fold((1u8, 1u8), |(c, r), &(x, y)| (c.max(x.saturating_add(1)), r.max(y.saturating_add(1))));
let cell = vec2((20.0 / f32::from(cols)).min(10.0), (20.0 / f32::from(rows)).min(10.0));
let origin = rect.center() - vec2(f32::from(cols) * cell.x, f32::from(rows) * cell.y) / 2.0;
let centre = |&(x, y): &(u8, u8)| origin + vec2((f32::from(x) + 0.5) * cell.x, (f32::from(y) + 0.5) * cell.y);
for tile in tiles {
ui.painter().rect_filled(Rect::from_center_size(centre(tile), cell - vec2(2.0, 2.0)), 1.0, color.gamma_multiply(0.35));
}
let path: Vec<Pos2> = tiles.iter().map(centre).collect();
if let ([first, ..], [.., from, to]) = (path.as_slice(), path.as_slice()) {
let (first, from, to) = (*first, *from, *to);
let dir = (to - from).normalized();
let side = dir.rot90() * 2.5;
let head = vec![to + dir * 1.5, to - dir * 2.5 + side, to - dir * 2.5 - side];
ui.painter().circle_filled(first, 1.6, color);
ui.painter().add(egui::Shape::line(path, Stroke::new(1.2, color)));
ui.painter().add(egui::Shape::convex_polygon(head, color, Stroke::NONE));
}
resp.on_hover_text(tip).clicked()
}
/// `region` of `doc` rendered on white, its longest side `px` pixels, as a texture named `name`
/// (artboard and page thumbnails).
pub fn region_texture(