Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 4099ebf3c9 Fix #787: raster exports keep translucent edges over opaque art opaque
The renderer composited in 8-bit integers, so where a partly transparent
anti-aliased edge crossed opaque art (or a background colour) the result
came out at alpha 254 on some pixels, and PNG, TIFF and WebP files were
written with an alpha channel. Raster exports (and Save for Web) now
composite in floating point (vello_cpu's f32 pipeline, enabled as a
feature), offscreen groups, masks and patterns included; the canvas keeps
the faster 8-bit path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 11:12:13 +07:00
bflatasticandClaude Opus 5.5 1db82cbc02 Fix #798: the Curvature tool edits any selected path
The Curvature tool only edited the path it was drawing. It now edits any
selected path, whatever drew it, keeping its shape except where edited:
a click on a point makes it the current (direct-selected) point and a
drag moves it, re-curving only its two segments (the neighbours keep
their handle directions); Alt-click or double-click toggles it smooth or
corner and Delete removes it; a click on a segment adds a smooth point
without changing the shape, and a drag moves it in the same undo step.
With an end of an open path current, clicks go on from it (the old
segments keep their shape) and a click on the other end closes it.

The edits go through a new path.curvatureEdit command (move, insert,
extend, close), path.convertAnchor and path.removeAnchor, one undo step
each. The tool now claims Delete/Backspace while it has a point to
remove, so the key no longer deletes the whole path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 11:12:10 +07:00
bflatasticandClaude Opus 5.5 898c4f7677 Docs: ROADMAP for the 2026-10-10 fixes; Other Library lists color books
The ROADMAP's last-updated line names this batch's fixes and the two
community PRs that didn't add themselves (#792, #765); the platforms
paragraph says Windows starts on Direct3D 12 and loads no Vulkan driver
unless asked (#806); the guides row has ruler guides with Smart Guides
on and the hover labels (#812). Window › Swatch Libraries › Other
Library's description lists .acb color books (#831).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:52:27 +07:00
BFlat 6b42a9100c Merge pull request #887 from storytold/fix/812-hover-labels
Part of #812: Smart Guides label an object's centre and anchors on hover
2026-10-10 10:46:53 +07:00
BFlat 1b398978ba Merge pull request #884 from storytold/fix/827-raster-effect-blend
Fix #827: shadows and glows keep their blend modes in PDF
2026-10-10 10:46:45 +07:00
BFlat 449387a62e Merge pull request #883 from storytold/fix/812-guides-snap
Part of #812: ruler guides pull drawn points with Smart Guides on
2026-10-10 10:46:28 +07:00
BFlat 0782972b88 Merge pull request #882 from storytold/fix/785-step-references
Part of #785: run and command_batch steps can use earlier results
2026-10-10 10:46:10 +07:00
BFlat 07708f6cca Merge pull request #881 from storytold/fix/861-open-error-dialog
Part of #861: a file the user can't open is reported in a dialog
2026-10-10 10:46:01 +07:00
BFlat 5b26fd4d01 Merge pull request #879 from storytold/fix/831-acb-color-books
Fix #831: color books (.acb) open as swatch libraries
2026-10-10 10:45:54 +07:00
BFlat a05a6d06bf Merge pull request #878 from storytold/fix/833-isolation-locks-outside
Fix #833: isolation mode locks and dims the art around the group
2026-10-10 10:45:48 +07:00
BFlat fd59778c8f Merge pull request #877 from storytold/fix/775-properties-paragraph
Fix #775: the Properties panel's Paragraph section justifies and hyphenates
2026-10-10 10:45:43 +07:00
BFlat 06d61296f5 Merge pull request #876 from storytold/fix/789-align-to-everywhere
Fix #789: every align button aligns to the Align To choice
2026-10-10 10:45:36 +07:00
BFlat fb4b84c4b9 Merge pull request #875 from storytold/fix/835-gradient-stop-recent
Fix #835: a recent colour recolours the selected gradient stop
2026-10-10 10:45:30 +07:00
BFlat 9c0eccb067 Merge pull request #874 from storytold/fix/862-stop-popover-beside-art
Fix #862: the gradient stop popover opens beside the art
2026-10-10 10:45:22 +07:00
BFlat 2b01ebcc9e Merge pull request #873 from storytold/fix/826-rotated-rulers
Fix #826: rulers cover their length in a rotated view
2026-10-10 10:45:15 +07:00
BFlat 447fe10edf Merge pull request #872 from storytold/fix/839-sfw-pixel-size
Fix #839: Save for Web accepts a typed width or height
2026-10-10 10:45:09 +07:00
BFlat 9cc0ca866d Merge pull request #871 from storytold/fix/824-artboard-label
Fix #824: the Artboard tool names its artboard once
2026-10-10 10:45:03 +07:00
BFlat 56b3119288 Merge pull request #870 from storytold/fix/806-no-vulkan-on-windows
Fix #806: Windows doesn't load Vulkan drivers unless asked
2026-10-10 10:44:58 +07:00
BFlat 0b249c5257 Merge pull request #869 from storytold/fix/758-skip-hopeless-prune
Part of #758: .ai import doesn't weigh text objects when the layers can't be used
2026-10-10 10:44:52 +07:00
BFlat c1bcd0afeb Merge pull request #863 from storytold/fix/755
Fix #755: blurred type no longer shifts as the view moves
2026-10-10 10:44:41 +07:00
BFlat 5d5db434ea Merge pull request #860 from storytold/fix/830-app-quit-pending
Fix #830: the control channel's app.quit says when it asks first
2026-10-10 10:44:34 +07:00
BFlat 84ae8e90c3 Merge pull request #859 from storytold/fix/828-effect-dropdowns
Fix #828: Offset Path's Joins and Zig Zag's Points are dropdowns
2026-10-10 10:44:27 +07:00
BFlat 71d8881186 Merge pull request #753 from storytold/feat/637-type-from-text-document
Part of #637: area type, threaded type and type on a path from the text document
2026-10-10 10:44:20 +07:00
bflatasticandClaude Opus 5.5 fdb7d7a183 Part of #812: Smart Guides label an object's centre and anchors on hover
With Smart Guides on, hovering the Selection tool near an object's centre
or one of its anchors now labels it ("center", "anchor"), as
Illustrator does, and a press there grabs the object by that point, so
the point follows the pointer and snaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:38 +07:00
bflatasticandClaude Opus 5.5 99671cabd8 Fix #827: shadows and glows keep their blend modes in PDF
A raster effect painted below its object (Drop Shadow, Outer Glow) is
written as an image under the object's vector art. The image was
rendered over nothing and placed with Normal blending, so a Screen glow
or a Multiply shadow came out as Normal in the PDF. Each image is now
composited with its effects' blend mode, one image per mode when an
object's shadows and glows use several.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:04 +07:00
bflatasticandClaude Opus 5.5 522c1dabd6 Part of #812: ruler guides pull drawn points with Smart Guides on
Drawing with Smart Guides on ignored the ruler guides: only with Smart
Guides off did Snap to Point use them (a vertical guide seemed to work
when it lay on the artboard's centre line, which Smart Guides follow).
With Snap to Point on, the ruler guides now pull drawn and dragged
points with Smart Guides on too, also while a point slides along a
construction guide or Shift's angle, as in Illustrator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:03 +07:00
bflatasticandClaude Opus 5.5 b767e850ed Part of #785: run and command_batch steps can use earlier results
A run (vectorcraft-cli run, the MCP command_batch tool) had no way to use
an id an earlier step returned. A parameter string that is exactly
$N.path or $last.path now takes that value from step N's result
(0-based), e.g. {"id":"$1.id"}; $$ starts a literal $, and a
reference to nothing fails the step. Objects given to a command are now
used as given: an ids element or id that isn't an object id (or an
unresolved reference) fails instead of the command acting on the
selection. text.setRangeStyle styles the selected type object when no
id is given, as text.setStyle does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:03 +07:00
bflatasticandClaude Opus 5.5 c19873e220 Part of #861: a file the user can't open is reported in a dialog
Opening a file that fails (File › Open, Open Recent, the Home screen, a
drop, the Finder or the command line) only set the status bar's
message, which is easily missed: it looked as if nothing happened. A
dialog now says "Can't open “name”." with the reason, as well. An
agent's file.open {path} still just answers with the error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:59 +07:00
bflatasticandClaude Opus 5.5 9a0183a02d Fix #831: color books (.acb) open as swatch libraries
Color books such as the Pantone books a user owns (.acb) couldn't be
opened. They are now read (never written), from public descriptions of
the format: their RGB, CMYK or Lab colors, named with the book's prefix
and suffix ("PANTONE 185 C"), as spot colors unless the book marks
them as process colors, leaving out the pages' unnamed padding. They
open from Window › Swatch Libraries › Other Library…, File › Open and
the user library folder like .ase files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:58 +07:00
bflatasticandClaude Opus 5.5 b426859b15 Fix #833: isolation mode locks and dims the art around the group
While a group or layer was isolated, clicks, hovers and drags still
reached the art outside it, and that art drew as usual. Now only the
isolated container's contents hit: the art around it is locked and
clicks pass through it. On the canvas it draws at half opacity, above
the group as well as below, each run of it as one dimmed layer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:57 +07:00
bflatasticandClaude Opus 5.5 61d372bb7f Fix #775: the Properties panel's Paragraph section justifies and hyphenates
With type selected, the Properties panel's Paragraph section had only
Align Left, Center and Right. It now has the Paragraph panel's seven
alignments (the justified ones too), its Hyphenate checkbox and a "…"
button that opens the Paragraph panel, as Illustrator's does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:56 +07:00
bflatasticandClaude Opus 5.5 82dc5f8182 Fix #789: every align button aligns to the Align To choice
Align to Key Object and Align to Artboard worked only from the Align
panel's own buttons: the Control bar's and the Properties panel's align
buttons always aligned to the selection (one object to the artboard).
They are now one set of buttons that follow Align To (and the key
object), and the Properties panel's Align section gets the "…" button
that opens the Align panel for Distribute and Align To.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:54 +07:00
bflatasticandClaude Opus 5.5 79c81d754c Fix #835: a recent colour recolours the selected gradient stop
In the gradient stop popover (and the Color panel), clicking a recent
colour replaced the whole gradient with that colour, while the sliders,
spectrum and Black and White chips recoloured the selected stop. The
recent colours now go through the Color panel's target like the chips.
The Swatches panel's recent colours still paint the fill or stroke, as
its swatches do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:54 +07:00
bflatasticandClaude Opus 5.5 97318c188b Fix #862: the gradient stop popover opens beside the art
Opened from a stop on the Gradient tool's annotator, the colour popover
appeared just below and right of the stop, over the very art whose
colour it changes. It now opens beside the selected art, on the first
side with room for it (right, left, below, above), and beside the stop
only when there is none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:53 +07:00
bflatasticandClaude Opus 5.5 94141eca82 Fix #826: rulers cover their length in a rotated view
With Rotate View, each ruler measured document x (or y) along a line
that crossed both axes: its ticks covered only a short stretch and the
numbers bunched up. Each ruler now measures along its own edge in the
canvas's coordinates turned with the view, so it is ticked over its
whole length at every angle, and reads x and y as before at 0°.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:53 +07:00
bflatasticandClaude Opus 5.5 5df4ddd4b6 Fix #839: Save for Web accepts a typed width or height
The dialog's W and H fields send decimal numbers (300.0) and the settings
wanted a whole u32, so the preview failed with "invalid type: floating
point". Pixel sizes now take any number and round it to whole pixels;
negative, huge and non-numeric sizes are still refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:52 +07:00
bflatasticandClaude Opus 5.5 021a9474f8 Fix #824: the Artboard tool names its artboard once
With the Artboard tool, the active artboard's name was drawn twice: by
the canvas, as for every artboard, and by the tool, in blue and a little
higher. The canvas now leaves that one to the tool, which draws it where
the canvas names the others.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:52 +07:00
bflatasticandClaude Opus 5.5 de564bc24f Fix #806: Windows doesn't load Vulkan drivers unless asked
Creating a Vulkan instance loads every installed Vulkan driver into the
process, and a faulty one (Intel's igvk64.dll) crashed VectorCraft
before its window appeared. On Windows the window now starts with
Direct3D 12, falling back to OpenGL, as PdfCraft does; WGPU_BACKEND
(e.g. vulkan) still chooses others.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:51 +07:00
bflatasticandClaude Opus 5.5 495694e1ac Part of #758: .ai import doesn't weigh text objects when the layers can't be used
Before deciding to use the layers of an Illustrator file, the import
drew them again for each text object made from the file's text
document, to see whether the page draws it. When the layers differ from
the page by more than the check allows even with every such object
gone (taking one out only changes what is drawn in its box), the
layers aren't used whatever is taken out: that weighing is now
skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:50 +07:00
bflatasticandClaude Opus 5.5 584f08ae70 Fix #755: blurred type no longer shifts as the view moves
Gaussian Blur and Feather drew through a filter layer whose blur works on
a coarser grid tied to the canvas: the blurred art moved by up to about
a pixel, and its steps showed, as the view moved by parts of a pixel
(scrolling, zooming about the pointer). They now blur the content's own
pixels on the CPU, as the Photoshop-style effects already do: the same
look wherever the view is, cached while only the view moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:49 +07:00
bflatasticandClaude Opus 5.5 db8be89052 Fix #830: the control channel's app.quit says when it asks first
Raw app.quit closed the window and answered null at once, so a client
couldn't tell that a save prompt was waiting. It now runs the menu's
Quit: {"pending": "saveChanges"} while a modified document is asked
about, as file.close and file.closeAll answer and the protocol
documentation says; otherwise null, and the window closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:47 +07:00
bflatasticandClaude Opus 5.5 1ba987ee7a Fix #828: Offset Path's Joins and Zig Zag's Points are dropdowns
The effect versions of Offset Path, Zig Zag and Roughen showed Joins and
Points as free text fields. They now pick Miter, Round or Bevel and
Smooth or Corner, as Object > Path > Offset Path does. A size's
Relative / Absolute (Roughen, Zig Zag, Tweak) is a pair of radio
buttons, and the effect dialogs' other on/off options are checkboxes
that show when they are off too (they were invisible unchecked).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:46 +07:00
bflatasticandClaude Opus 5.5 3198abe2fd Part of #637: area type, threaded type and type on a path from the text document
Illustrator EPS and .ai type is made whole from the file's text
document, shown or hidden: point type, area type (a story in several
frames as threaded type that flows when the file opens) and type on a
path, with its fonts, size, leading, tracking, scaling, baseline shift,
fill and stroke colours (grey, RGB or CMYK), alignment, indents and
paragraph spacing. The page's drawing of that type, often in pieces, is
left out; where the text document can't say, type that shows still
comes from the page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:46 +07:00
BFlat 1c19c27fef Merge pull request #765 from vbasky/pr/raster-effect-gallery
Add Stylize > Glowing Edges raster effect
2026-10-10 10:17:44 +07:00
bflatasticandClaude Opus 5.5 b9b880a5de Review fixes for #765: the glow outside a shape keeps the edge's colour
The output multiplied the glow's colour by its opacity a second time, so outside the shape (where
the glow sets the opacity) it darkened as it faded and showed as a grey rim over a light
background. The test now checks that the fading glow keeps the edge's colour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 09:50:05 +07:00
Vikram Bhaskaran 60831b87d9 Preserve edge color and brightness through glow blur 2026-10-10 09:50:05 +07:00
bflatasticandClaude Opus 5.5 800baacbba Glowing Edges: transparency beyond the right and bottom edges; rustfmt; as_chunks in tests
The edge filter read `y * w + x` for x = w (the next row's first pixel)
and y = h at the raster's right and bottom edges; it now reads
transparency there, as the module documents. A test checks a solid square
glows alike on every side. Formatted with rustfmt, and the test uses
as_chunks for clippy 1.99.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 09:50:05 +07:00
Vikram Bhaskaran 11aaf816d0 M9.2: replace Find Edges with Glowing Edges 2026-10-10 09:50:05 +07:00
Vikram Bhaskaran 2d371849df M9.1: add Find Edges raster effect 2026-10-10 09:50:05 +07:00
BFlat d28cbacbf7 Merge pull request #777 from shmuelbiller1/fix/package-transitive-placed-links
Fix/package transitive placed links
2026-10-10 09:49:28 +07:00
bflatasticandClaude Opus 5.5 2762f61e83 Review fixes for #777: report sections per document, fmt, docs and ROADMAP
The report kept a placed document's LINKED FILES and FONTS inside its parent's list. Each document
now gets its own sections, the packaged one first and unchanged (no Document: line), then each
placed document's, headed by its file. Drops a debug_assert and an unneeded mut, runs rustfmt, and
documents the nested packaging in docs/mcp.md and the ROADMAP.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 09:32:12 +07:00
bflatasticandClaude Opus 5.5 94f27299d4 Merge origin/main into #777
package.rs: the collector takes main's font lookup (fonts found by any of their names, in the
version the type names, a missing style shown in its closest one, files named by packaged_name).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 09:23:25 +07:00
BFlat 6fed61b4db Merge pull request #792 from dotCooCoo/feat/missing-fonts
Fonts: missing fonts are listed when a document opens, with Find Fonts and a folder search
2026-10-10 09:18:20 +07:00
bflatasticandClaude Opus 5.5 09a0ff23ad Review fixes for #792: build expected test paths with the platform's separator
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 09:07:53 +07:00
BFlat 1090385507 Merge pull request #774 from David-T-Campos/fix/svg-drop-uses-open-path
Use File Open path for native SVG drops
2026-10-10 08:50:21 +07:00
dotCooCoo 11cf254a07 Fonts: a folder search finds .suit suitcases and skips font files over 256 MB
Add Fonts adds only files a folder search found.

- macOS declares .suit as the extension of a font suitcase
  (com.apple.font-suitcase), and the font scan reads a suitcase
  whatever its name. A search considered only suitcases without an
  extension. It now also considers files whose extension is .suit, in
  any letter case, and reads one only when it is a suitcase font.
- Add Fonts copies at most 256 MB a file. A search also read larger
  font files, and a search that found one for a font could end before
  it found a smaller copy. A search now skips font files over 256 MB.

Docs: docs/mcp.md.
2026-10-10 08:42:32 +07:00
dotCooCoo 7b7e10e82e Fonts: a folder search skips suitcase fonts whose resource fork is over 8 MB
A folder search reads at most 8 MB of each font file. The suitcase
reader reads a suitcase font's resource fork whole, up to 256 MB.
Before this change, the search applied its limit to each font only
after that read. One search thread could read 256 MB from a single
suitcase and hold a copy of its fonts as well. The search now reads a
suitcase font only when its resource fork is 8 MB or less. The font
scan still reads each suitcase font's resource fork whole, up to
256 MB.

Docs: docs/mcp.md.
2026-10-10 08:42:32 +07:00
dotCooCoo 5709e636a5 Fonts: missing fonts are listed when a document opens, with Find Fonts and a folder search
When a document opens with fonts that aren't available, fonts used
only in its symbols included, VectorCraft lists them in a Missing
Fonts dialog after the missing linked file questions, one document at
a time, with Find Fonts and Close. Find Fonts opens Type › Find Font
on the first missing font of the layers' type, to replace it. After
Find Fonts or Close the dialog doesn't open again for that open; when
another dialog replaces it, it opens again once that dialog closes.

Search Fonts Folder (the Fonts folder File › Package writes next to
the document) and Find in Folder… search a folder and its subfolders
for the fonts' files, and Add Fonts copies the files the user chooses
into a Fonts folder next to the preferences. The desktop app and
vectorcraft-cli read that folder with the system's font folders. Type
› Find Font has a Find in Folder… button too when fonts the document
uses are missing. The web app shows no dialog; a status message says
how many fonts aren't available.

- text.missingFonts lists each missing family and style once,
  whatever version the document's type names, and leaves out CSS
  generic families such as sans-serif. text.findFontFiles searches a
  folder on up to 8 threads and returns at once; text.findFontFiles {}
  reports the search, and {stop: true} stops it. A search reads only
  what the font scan reads of font files (their table directories and
  name, fvar and OS/2 tables) and, on macOS, of suitcase fonts, and
  lists a file for a font only when the file makes the font resolve
  exactly. It does not enter app packages, the Program Files and
  ProgramData folders, the system's folders at the root of a volume,
  the Shared and Public folders in Users, a home folder's Library,
  AppData, Applications, snap and dot folders, a Library folder's app
  data folders or the folders the environment names for apps, and it
  skips other hidden folders and does not follow links below the
  picked folder. It ends after 60 s by default, after 10,000,000
  entries listed, with more than 1,000,000 folders waiting, after
  10,000 font files read or 1,000 kept, or once every font has a file;
  Stop and Close end it too.
- text.addFontFiles copies only files the last search found. Of
  those, it copies only regular .ttf, .otf, .ttc, .otc, .woff and
  .woff2 files and suitcase fonts with their resource fork, at most
  256 MB a file and 1 GB in all. It never replaces a file: a file with
  the same contents is kept, and when another file has that name, the
  copy gets a number (Name 2.otf). The fonts are then scanned again,
  and type set in them redraws.
- ui.missingFontsDialog and ui.findFontsInFolder open the dialog for
  agents; docs/control-protocol.md lists its fields.
- File › Package gives a font file whose name has no font extension
  the extension that matches its data (.ttf, .otf or .ttc).
- vectorcraft-text adds set_app_font_dir, which system_font_dirs
  reads, WantedFonts, which reads a font file's names as the font scan
  does, is_font_file and is_suitcase. #762 split its face reader, which
  now takes read budgets: file_face_names_within tries the suitcase
  reader first, and reader_face_names_within applies the budgets to
  each font. vectorcraft-format adds write_new_with.

Docs: docs/mcp.md, docs/control-protocol.md, ROADMAP.
2026-10-10 08:42:32 +07:00
BFlat 796accffc0 Merge pull request #675 from fastmikey99/fix/pdf-import-past-page-clip
PDF import: clip art reaching past the page to the crop box
2026-10-10 08:41:47 +07:00
BFlat ef574b6319 Merge pull request #854 from rschuerer/fix/ai-non-native-art
Fix #861: open .ai files whose non-native art has ASCII85 lines starting with %_
2026-10-10 08:37:32 +07:00
David Campos ec32a0b537 Add tests for SVG drop handling 2026-10-10 08:32:19 +07:00
David Campos 8b95f79f3b Handle pathless SVG drops by sniffing bytes 2026-10-10 08:32:19 +07:00
David Campos b6625f6964 Open dropped SVG paths via the shared reader 2026-10-10 08:32:19 +07:00
David Campos 8edee45588 Use File Open path for native SVG drops
Route native SVG drops through the same reader as File > Open.
2026-10-10 08:32:18 +07:00
bflatasticandClaude Opus 5.5 d38a2fa023 Review fixes for #675: ROADMAP entry for the PDF page clip
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 08:30:48 +07:00
fastmikey99andClaude Opus 5.5 c2339fca81 PDF import: leave art past the page unclipped in a PDF-compatible .ai
The PDF part of an .ai stands in for the editable document, whose art crossing
the artboard edge isn't clipped, so it keeps opening whole and editable (#646).
Plain PDFs still get the clip to the crop box. path_count is back to counting
every path: no clipping paths appear in the .ai cases it counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 08:26:48 +07:00
fastmikey99andClaude Opus 5.5 1d0305fc2a PDF import: clip art reaching past the page to the crop box
A clip to the page box is dropped as redundant (by hayro, and by
push_clip_path), so art a file hides outside the page - a mock-up backdrop
thousands of points across, say - came in unclipped: it showed, and it sized
Fit to Artwork Bounds and CropTo::Bounding to metres. Viewers show a page
through its crop box, so each object reaching past it now keeps its own clip
to it, with a warning. Art inside the page is unchanged (no clip groups).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 08:26:26 +07:00
Reinhard SchuererandClaude Fable 5.1 f2ba41d1c1 Open .ai files whose non-native art has ASCII85 lines starting with %_
A letterhead saved by Illustrator 28 without PDF compatibility wouldn't
open: "its editing data can't be read (it ends inside a layer)". Its
layer starts with a /ForeignObject (non-native art: the content of a
placed PDF), whose /Data entry is the PDF as ASCII85 in comment lines.
ASCII85 includes `_`, so about one line in 85 starts with `%_`, which
the lexer reads as hidden tokens; a `(` in such a line opened a string
that swallowed the dictionary's end, the rest of the art and the
layer's LB.

The reader now skips to the data's `~>` after `/Data ,` in a
/ForeignObject, as it already did for a /Binary dictionary's ASCII85,
and leaves the non-native art out with a note (nothing draws its PDF
from the editing data yet).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ZwZjADUZP4VzvrFGpiZch
2026-10-10 08:25:35 +07:00
shmuelbiller1 b4784c02ee test(package): retain and report the boundary file at the nesting limit 2026-10-09 14:36:37 -04:00
shmuelbiller1 6f260fac3e fix(package): propagate optional metadata for cyclic links without nesting Options 2026-10-09 14:36:06 -04:00
shmuelbiller1 7d75280ab4 fix(package): preserve FONTS report header and document warning output 2026-10-09 14:35:42 -04:00
shmuelbiller1 c8642eeddb test(package): retain unreadable children and break circular dependencies without aborting 2026-10-09 14:34:21 -04:00
shmuelbiller1 0b326c48bc fix(package): keep copying linked documents on parse failures, cycles and depth limits 2026-10-09 14:33:39 -04:00
shmuelbiller1 f9384dfed7 test(package): nested native files retain PDF compatibility preview and compression 2026-10-09 11:55:49 -04:00
shmuelbiller1 71484fd013 fix(package): preserve nested previews, PDF content, compression and embedded assets 2026-10-09 11:54:37 -04:00
shmuelbiller1 7c3687af29 test(package): distinct nested assets sharing a stale source path remain separate 2026-10-09 11:52:37 -04:00
shmuelbiller1 ba1b7a834f fix(package): deduplicate by resolved source and rebase links per containing document 2026-10-09 11:51:54 -04:00
shmuelbiller1 bbb465a0d3 style(doc): format portable link traversal chain 2026-10-09 11:39:15 -04:00
shmuelbiller1 f549f6ad4d style: keep new package traversal within rustfmt width 2026-10-09 11:37:28 -04:00
shmuelbiller1 a9e3d85b1d style: keep new package traversal within rustfmt width 2026-10-09 11:37:24 -04:00
shmuelbiller1 a4a040653d test(package): resolve nested links from their actual source after moving files 2026-10-09 11:35:51 -04:00
shmuelbiller1 deff7bb757 fix(package): resolve transitive links against the moved file's actual location 2026-10-09 11:34:02 -04:00
shmuelbiller1 022069d5a5 fix(links): retain resolved source paths when packaging moved nested documents 2026-10-09 11:33:42 -04:00
shmuelbiller1 1f668dfaad fix(package): retain nested documents' embedded ICC profile bytes 2026-10-09 11:32:32 -04:00
shmuelbiller1 816a0fe762 test(package): reopen nested linked documents from portable folder and ZIP deliveries 2026-10-09 11:31:30 -04:00
shmuelbiller1 4fe06391d4 fix(package): retain existing top-level missing-link reporting API 2026-10-09 11:30:54 -04:00
shmuelbiller1 ae68704dfc fix(package): preserve rebased portable paths for relative output folders 2026-10-09 11:29:53 -04:00
shmuelbiller1 eacef005b0 fix(package): recursively collect and rebase placed documents and their assets 2026-10-09 11:29:01 -04:00
shmuelbiller1 c461369421 feat(doc): allow portable relinking of images and placed documents 2026-10-09 11:27:13 -04:00
111 changed files with 8679 additions and 572 deletions

No files matched your search

+1 -1
View File
@@ -54,7 +54,7 @@ wasmi = { version = "2.0.0", default-features = false, features = ["std", "valid
wat = "1.228"
# rendering / formats
vello_cpu = "0.2"
vello_cpu = { version = "0.2", features = ["f32_pipeline"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] }
usvg = "0.48"
krilla = "0.8"
+5
View File
@@ -169,6 +169,11 @@ Graphics Processor** and restart. If a graphics processor can't show the window,
next one. To pick one when starting the app, set `WGPU_POWER_PREF=high` (or `low`), or `WGPU_ADAPTER_NAME` to part of
its name, such as `WGPU_ADAPTER_NAME=nvidia` (see [`docs/development.md`](docs/development.md#desktop-graphics-processor)).
On native Wayland, winit 0.30 does not deliver dropped files. To open an SVG, use File › Open;
to place artwork in the current document, copy and paste the file in a file manager; or run
under XWayland (`WAYLAND_DISPLAY= vectorcraft`) for file drag-and-drop
(see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
On Linux under KDE Plasma 6.3 or later with Wayland, a drawing tablet's pen moves the cursor but VectorCraft doesn't
respond to it yet (#491). Start the app under XWayland instead: `WAYLAND_DISPLAY= vectorcraft` (see
[`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
+14 -14
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-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
## Where we are
@@ -42,7 +42,7 @@ since 2026-10-01.
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows renders through DX12 before Vulkan (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel |
| **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) |
@@ -53,11 +53,11 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
1. **Interaction fidelity:** go tool by tool and panel by panel against `plan/illustrator/05-tools.md`,
`06-panels.md` and `09-shortcuts.md`, covering modifier keys, cursors, the Properties panel per context and
isolation mode. The Shaper’s rough-square recognition and shape orientation steps are corrected; Shaper Groups now retain editable originals for region merges/punches and separate fill/stroke edits; their construction-mode widget and gesture refinements remain. 60–90 h.
2. **Photoshop-style raster effects and the Effect Gallery:** about 52 filters (Artistic, Brush Strokes, Distort,
2. **Photoshop-style raster effects and the Effect Gallery:** about 51 filters (Artistic, Brush Strokes, Distort,
Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery. The pixel-filter pipeline is in place
(`vectorcraft_effects::pixel`: the object rendered offscreen, filtered in stack order with Gaussian Blur and
Feather, cached while panning, images in PDF/SVG/Expand Appearance) with Blur › Radial Blur and Smart Blur
(Normal mode only) and Sharpen › Unsharp Mask; each new filter is now one function, a catalogue row, menu and
(Normal mode only), Sharpen › Unsharp Mask and Stylize › Glowing Edges; each new filter is now one function, a catalogue row, menu and
translations. Parallelizes well across agents. 26–40 h.
3. **3D and Materials:** Extrude & Bevel, Revolve, Inflate and Rotate with lighting and materials, using a software
renderer in its own crate (layering allows it below L6), with output in SVG/PDF as rasters or projected vectors.
@@ -98,7 +98,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- JSON-lines control channel with real egui pointer and keyboard injection.
- MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings.
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785).
- Actions panel that records and plays back commands.
- **UI:** Illustrator 2026 layout restyled to measured values:
- Medium Dark theme, categorized and Advanced toolbars (a tool group's flyout opens on a right press, a long press or a press on its corner triangle), 35 pt document tabs, 33 pt panel tabs.
@@ -128,7 +128,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
Agent selection commands validate every object id before changing the selection and report the resulting count and ids (#784).
Clear deletes individual selected compound-path members without deleting their siblings, and explicit object ids work without a selection; Cut still removes the same objects it copies (#786).
- **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Not yet: Update Selection and the Layers panel's saved-selection menu.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; Alt-click or double-click toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners.
- **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812; the on-canvas pie widget is still to come).
- **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes).
- **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag).
@@ -153,7 +153,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original.
- **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 (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; `object.cropImage {rect}` for agents, `{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`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. 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.
- **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`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. 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). 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.
@@ -163,14 +163,14 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; six generated style libraries save and load as `.vcstyles`.
- **Neutral wording:** labels, MCP tool text, docs and packaging use neutral names, and `cargo xtask brands` (part of `cargo xtask ci`) fails on vendor names.
- **Colour, type and file workflows:** Recolor Artwork (dialog with harmonies), Edit Colors, Find & Replace, Change Case, Smart Punctuation, Guides, Lock/Hide Above, Transform Each, Rasterize.
- **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). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite, and those apps and font managers register with CoreText on macOS (#579).
- **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). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite, and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`).
- **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). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask.
- 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; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); 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). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](docs/affinity-validation.md); [scope, provenance and limits](crates/affinity/README.md).
- 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).
- Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.
- **Graphics processor:** the canvas is rasterized on the CPU and the GPU only composites it, so any GPU that can show the window will do. Preferences › Performance › Graphics Processor (`gpuPreference`) is Automatic by default: the power-saving GPU on Windows and macOS (the integrated one on hybrid-graphics laptops, where presenting from the discrete GPU made the window flicker, #306), and the GPU the desktop runs on under Linux, where KWin on an NVIDIA GPU refused frames from a Ryzen's integrated GPU and 0.5.0 crashed at startup (#502). Power Saving and High Performance pick a kind of GPU; `WGPU_POWER_PREF`, `WGPU_ADAPTER_NAME` and `WGPU_BACKEND` override them. The app picks among the adapters that can present to the window (native backends before OpenGL, hardware before software, and on Windows a GPU's DX12 adapter before its Vulkan one: Intel's Vulkan driver made the whole window flicker black, #545), and if the window fails on one while starting up it starts again without it instead of crashing; Help › About, `ui.inspect` and the log name the adapter in use. When the browser drops the page's WebGPU device or WebGL context, the web build writes recovery copies, starts again on new graphics with the same app and uploads its textures again; if it can't, it removes the stale canvas and says to reload, which offers the copies back. The desktop app writes the copies and says to restart (#369). On Windows and Linux the tools' cursors are OS cursors (bitmaps rasterized once per display scale), which the system moves itself: painted into the window, they trailed the pointer by the frames waiting to be shown, and the window now queues one frame instead of two (#444). macOS and the web still paint them (macOS sizes cursor bitmaps in points, eframe has no bitmap cursors on the web). Pens and touch drive the tools as the mouse does, and a tap pressed and lifted within one frame clicks where it tapped (#491); pen pressure reaches the Liquify tools' Use Pressure Pen on Windows, while winit 0.30 reports none on macOS or Linux and egui none on the web. On Linux, see `docs/development.md` for pens under Wayland.
- **Tests and robustness:** ~2,840 automated tests: model-based property tests, a junk-parameter sweep over every command, import fuzzing (SVG, PDF, libraries), golden renders, and MCP end-to-end tests over stdio. Shipped code never panics (workspace lints and a rollback safety net; see `docs/development.md`).
@@ -219,7 +219,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 12–20 |
| Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 |
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 |
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 24% | ~52 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur and Unsharp Mask are done | 26–40 |
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 25% | ~51 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur, Unsharp Mask and Glowing Edges are done | 26–40 |
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
| 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), custom kinsoku sets (beyond Hard, Soft and None) 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 |
@@ -227,8 +227,8 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Image Trace, graphs, image tools | 3 | 72% | graph Design/Column/Marker, Create Object Mosaic, 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 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 | 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; moves snapping to the grid, #740) | 2–4 |
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), 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 rest of Illustrator's editing data (area type and type on a path, appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
| 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; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812) | 2–4 |
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), 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 rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
| 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 |
@@ -252,7 +252,7 @@ lossless SVG/PDF export of live effects with SVG filters, a documented JSON form
command, gesture and dialog drivable by agents (MCP, CLI, control channel).
## Out of scope (by design or by law)
- **Native `.ai` private data, beyond its structure:** the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths, clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours), linear and radial gradients, opacity, blend modes, isolation and knockout, embedded images with their alpha channel, guides, and every artboard where it is. An object with several fills or strokes, effects or a brush comes in as its drawn look (a group named after it). Type that shows comes from the page, which draws it, into its text object's place (no group around it); type that doesn't (hidden layers and objects, art off the page) is made from the file's text document (characters, font, size, colour, alignment and where it is, for point type), and area type and type on a path in it are left out with a note. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type made from the text document and other type left out with a note. Symbols, pattern fills, placed files and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard.
- **Native `.ai` private data, beyond its structure:** the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths, clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours), linear and radial gradients, opacity, blend modes, isolation and knockout, embedded images with their alpha channel, guides, and every artboard where it is. An object with several fills or strokes, effects or a brush comes in as its drawn look (a group named after it). Type is made from the file's text document, whole and editable, shown or not: point type, area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing; the page's drawing of it (often in pieces) is left out. Where the text document can't say (a frame of another kind, or a document that doesn't agree with the page), type that shows comes from the page into its text object's place (no group around it), and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. Symbols, pattern fills, placed files and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard.
- **Adobe cloud services** (Libraries sync, Adobe Fonts, Firefly/generative): these are pluggable provider APIs, not built in.
- **Adobe's bundled assets** (swatch/brush/symbol libraries, presets, icons): ours are original.
+12 -2
View File
@@ -41,6 +41,9 @@ macro_rules! out {
#[path = "../../vectorcraft/src/mac_fonts.rs"]
mod mac_fonts;
mod perf;
/// The desktop app's settings folder, shared: exports and MCP read the same Fonts folder.
#[path = "../../vectorcraft/src/prefs_dir.rs"]
mod prefs_dir;
/// The desktop app's DirectWrite font lister, shared: exports and MCP find the same fonts.
#[cfg(all(windows, not(target_vendor = "win7")))]
#[path = "../../vectorcraft/src/system_fonts.rs"]
@@ -110,6 +113,7 @@ fn main() -> ExitCode {
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
let args: Vec<String> = std::env::args().skip(1).collect();
let r = match args.first().map(String::as_str) {
Some("mcp") => mcp(&args[1..]),
@@ -265,17 +269,23 @@ fn run(args: &[String]) -> Result<(), String> {
} else if !matches!(steps.first(), Some(Step::Cmd(id, _)) if id == "file.new") {
h.ensure_document();
}
// Each step's result, for later steps to refer to (`"$1.id"`, see `vectorcraft_engine::steps`).
let mut results = vec![];
for step in steps {
match step {
let r = match step {
Step::Cmd(id, params) => {
let params = vectorcraft_engine::steps::resolve(&params, &results).map_err(|e| format!("{id}: {e}"))?;
let r = h.call("engine.execute", json!({"command": id, "params": params})).map_err(|e| format!("{id}: {e}"))?;
emit(json!({"step": "cmd", "command": id, "result": r}))?;
r
}
Step::Export(path) => {
let r = h.call("app.export", json!({"path": path, "scale": scale})).map_err(|e| format!("export {path}: {e}"))?;
emit(json!({"step": "export", "result": r}))?;
r
}
}
};
results.push(r);
}
Ok(())
}
+22 -1
View File
@@ -31,7 +31,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use eframe::egui_wgpu::NativeAdapterSelectorMethod;
use eframe::wgpu::{self, Backend, DeviceType, PowerPreference};
use eframe::wgpu::{self, Backend, Backends, DeviceType, PowerPreference};
/// The adapters a restart leaves out, those the window failed on, as comma-separated [`key`]s
/// (`Vulkan:1002:164e`, `Metal:Intel Iris Pro Graphics`). Set by the app itself when it starts
@@ -81,6 +81,15 @@ pub fn preferred_displays(pref: Option<&str>, env: Option<PowerPreference>) -> V
if automatic(pref, env) { display_gpus() } else { Vec::new() }
}
/// The graphics backends the window starts with: on Windows Direct3D 12, falling back to OpenGL,
/// unless `WGPU_BACKEND` names others (`env_set`; `default` then holds them). Creating a Vulkan
/// instance loads every installed Vulkan driver into the process, and a faulty one (Intel's
/// `igvk64.dll`, #806) crashed the app before its window appeared. DX12 is Windows' own backend,
/// as in PdfCraft. Elsewhere, `default`.
pub fn backends(default: Backends, env_set: bool) -> Backends {
if cfg!(windows) && !env_set { Backends::DX12 | Backends::GL } else { default }
}
/// One adapter, as [`adapter_order`] sees it.
#[derive(Clone, Debug)]
pub struct Candidate {
@@ -809,6 +818,18 @@ mod tests {
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next");
}
#[test]
fn windows_never_loads_vulkan_drivers_unless_asked() {
let all = Backends::all();
let start = backends(all, false);
if cfg!(windows) {
assert_eq!(start, Backends::DX12 | Backends::GL, "#806");
} else {
assert_eq!(start, all);
}
assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it");
}
#[test]
fn power_preference_follows_the_environment_then_the_preference() {
assert_eq!(power_preference(None, None), AUTOMATIC);
+8 -19
View File
@@ -28,6 +28,7 @@ mod mac_fonts;
mod mac_menu;
#[cfg(target_os = "macos")]
mod open_documents;
mod prefs_dir;
mod printing;
#[cfg(all(windows, not(target_vendor = "win7")))]
mod system_fonts;
@@ -117,12 +118,11 @@ fn end_before_teardown(frames: u64) {
}
/// 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.
/// can't be opened is reported to the user and on stderr; the others still open.
fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
for f in files {
if let Err(e) = vectorcraft_ui_egui::io::open_path(app, &f) {
if let Err(e) = vectorcraft_ui_egui::io::open_reporting(app, &f) {
eprintln!("vectorcraft: {f}: {e}");
app.status(format!("Couldn't open {}: {e}", fileio::file_name(&f)));
}
}
}
@@ -141,27 +141,13 @@ fn discard_marked_text() {
/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS),
/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux).
fn prefs_path() -> Option<std::path::PathBuf> {
prefs_path_for("VectorCraft", "vectorcraft")
prefs_dir::prefs_path_for("VectorCraft", "vectorcraft")
}
/// The same place under the project's former name (DrawCraft): read once if there are no
/// VectorCraft preferences yet, so settings survive the rename.
fn legacy_prefs_path() -> Option<std::path::PathBuf> {
prefs_path_for("DrawCraft", "drawcraft")
}
fn prefs_path_for(name: &str, lower: &str) -> Option<std::path::PathBuf> {
let base = if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support").join(name))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join(name))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join(lower))
};
base.map(|b| b.join("ui.json"))
prefs_dir::prefs_path_for("DrawCraft", "drawcraft")
}
/// Where the log files live: `logs` in the preferences folder (see `logging`).
@@ -397,6 +383,8 @@ fn main() -> std::process::ExitCode {
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
prefs_dir::install_fonts();
let mut control_port: Option<u16> = std::env::var("VECTORCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
@@ -478,6 +466,7 @@ fn main() -> std::process::ExitCode {
// Metal on an Iris Pro, #651). `WGPU_VALIDATION_INDIRECT_CALL=1` turns it back on.
create.instance_descriptor.flags =
(eframe::wgpu::InstanceFlags::from_build_config() - eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
create.instance_descriptor.backends = gpu::backends(create.instance_descriptor.backends, std::env::var_os("WGPU_BACKEND").is_some());
}
options
};
+45
View File
@@ -0,0 +1,45 @@
//! Where VectorCraft keeps its settings, `ui.json`, and next to it folders of the user's own
//! (Swatches, Graphic Styles, Fonts, Data Recovery, logs). The desktop app and `vectorcraft-cli`
//! (which shares this file) read the same Fonts folder.
use std::path::PathBuf;
/// The settings file `ui.json` of the app `name`: in a folder named `name` in ~/Library/Application
/// Support (macOS) or %APPDATA% (Windows), or `lower` in $XDG_CONFIG_HOME or ~/.config (Linux and
/// BSD).
pub fn prefs_path_for(name: &str, lower: &str) -> Option<PathBuf> {
let base = if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support").join(name))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join(name))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join(lower))
};
base.map(|b| b.join("ui.json"))
}
/// Have the font scans read VectorCraft's own Fonts folder, next to the settings, which
/// `text.addFontFiles` copies font files into. The folder is set whether or not
/// `VECTORCRAFT_NO_PREFS` is set, as the Swatches and Graphic Styles folders are.
pub fn install_fonts() {
if let Some(dir) = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts"))) {
vectorcraft_text::set_app_font_dir(dir);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
install_fonts();
let fonts = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts")));
assert!(fonts.is_some(), "a home folder to keep the settings in");
assert_eq!(vectorcraft_text::app_font_dir().map(std::path::Path::to_path_buf), fonts);
assert!(vectorcraft_text::system_font_dirs().contains(&fonts.unwrap_or_default()));
}
}
+145 -1
View File
@@ -1,7 +1,8 @@
//! Swatch library files: the native `.vcswatches` JSON (colour models, global, spot, gradients
//! and colour groups exactly), `.gpl` palettes (8-bit RGB; colour groups as `# Group:` comment
//! headers), swatch exchange `.ase` files (binary: solid colors in their own model, global, spot
//! and process colors, color groups) and CSS custom properties (written only).
//! and process colors, color groups), color books `.acb` (read only: the books a user owns, such
//! as a Pantone book) and CSS custom properties (written only).
use std::collections::{HashMap, HashSet};
@@ -79,6 +80,8 @@ const ASE_MAX_ENTRIES: usize = 100_000;
/// The most UTF-16 code units of a name that are kept.
const ASE_MAX_NAME: usize = 1024;
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
const ACB_SIGNATURE: &[u8] = b"8BCB";
const ACB_CUT_SHORT: &str = "the color book is cut short";
/// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document)
/// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid
@@ -326,6 +329,9 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
if bytes.starts_with(ASE_SIGNATURE) {
return read_ase(bytes, name);
}
if bytes.starts_with(ACB_SIGNATURE) {
return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e });
}
read(&String::from_utf8_lossy(bytes), name)
}
@@ -333,6 +339,7 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
/// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough).
pub fn sniff_bytes(bytes: &[u8]) -> bool {
bytes.starts_with(ASE_SIGNATURE)
|| bytes.starts_with(ACB_SIGNATURE)
|| std::str::from_utf8(bytes).is_ok_and(sniff)
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
}
@@ -427,6 +434,67 @@ fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
Ok(lib)
}
/// `.acb` (a color book, read only), from public descriptions of the format: after the signature
/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description
/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0
/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its
/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab
/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of
/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand
/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot
/// or process colors (a book without it is a spot color book).
///
/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a
/// name (the padding of a book's pages) are left out. A version other than 1, a color space other
/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error.
fn read_acb(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
let mut data = AseData(bytes);
data.bytes(ACB_SIGNATURE.len())?;
let version = data.u16()?;
if version != 1 {
return Err(format!("color book version {version} isn't supported (only 1)"));
}
let _book_id = data.u16()?;
let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?];
let count = usize::from(data.u16()?);
if count > ASE_MAX_ENTRIES {
return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors"));
}
let (_page_size, _page_offset) = (data.u16()?, data.u16()?);
let space = data.u16()?;
let mut colors = Vec::with_capacity(count);
for _ in 0..count {
let name = data.acb_string()?;
let _code = data.bytes(6)?;
let color = match space {
0 => {
let [r, g, b] = data.array::<3>()?;
Color::rgb8(r, g, b)
}
2 => {
let ink = |v: u8| f32::from(255 - v) / 255.0;
let [c, m, y, k] = data.array::<4>()?;
Color::cmyk(ink(c), ink(m), ink(y), ink(k))
}
7 => {
let [l, a, b] = data.array::<3>()?;
Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0)
}
other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")),
};
colors.push((name, color));
}
// Spot colors unless the book says process ones.
let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice());
let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() };
let mut names = UniqueNames::default();
for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) {
let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string());
lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot });
}
Ok(lib)
}
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
/// Components are clamped to their ranges.
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
@@ -503,6 +571,20 @@ impl<'a> AseData<'a> {
let v = f32::from_be_bytes(self.array()?);
Ok(if v.is_finite() { v } else { 0.0 })
}
/// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units,
/// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units
/// are kept.
fn acb_string(&mut self) -> Result<String, String> {
let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX);
let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>();
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
let s = String::from_utf16_lossy(&units);
let s = match s.strip_prefix("$$$/") {
Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(),
None => s,
};
Ok(s.replace("^R", "®").replace("^C", "©"))
}
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
fn name(&mut self) -> Result<String, String> {
if self.0.is_empty() {
@@ -553,6 +635,68 @@ mod tests {
use crate::{Gradient, GradientPaint, GradientStop};
use proptest::prelude::*;
/// A color book's string: a `u32` count of UTF-16 code units, then the units.
fn acb_str(out: &mut Vec<u8>, s: &str) {
let units: Vec<u16> = s.encode_utf16().collect();
out.extend((units.len() as u32).to_be_bytes());
units.iter().for_each(|u| out.extend(u.to_be_bytes()));
}
/// A color book in `space` (0 RGB, 2 CMYK, 7 Lab) with `colors` (name, components) and an
/// optional spot/process marker.
fn acb(space: u16, colors: &[(&str, &[u8])], marker: &[u8]) -> Vec<u8> {
let mut b = b"8BCB".to_vec();
b.extend(1u16.to_be_bytes());
b.extend(3000u16.to_be_bytes());
for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] {
acb_str(&mut b, s);
}
b.extend((colors.len() as u16).to_be_bytes());
b.extend(7u16.to_be_bytes());
b.extend(0u16.to_be_bytes());
b.extend(space.to_be_bytes());
for (name, comps) in colors {
acb_str(&mut b, name);
b.extend(b"TST001");
b.extend(*comps);
}
b.extend(marker);
b
}
/// #831: color books (`.acb`) are read: their colors in RGB, CMYK or Lab, named with the book's
/// prefix and suffix, spot unless the book says process; page padding is left out.
#[test]
fn color_books_are_read() {
let lib = read_bytes(&acb(0, &[("185", &[228, 0, 43]), ("", &[0, 0, 0]), ("Red 032", &[239, 51, 64])], b"spflspot"), "fallback").unwrap();
assert_eq!(lib.name, "Test Book®");
let names: Vec<&str> = lib.swatches.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["TEST 185 C", "TEST Red 032 C"]);
assert!(lib.swatches.iter().all(|s| s.spot && s.global));
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(228, 0, 43)));
// CMYK ink is stored inverted; a book marked process gives process colors.
let lib = read_bytes(&acb(2, &[("Cyan", &[0, 255, 255, 255])], b"spflproc"), "x").unwrap();
assert_eq!(lib.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
assert!(!lib.swatches[0].spot && !lib.swatches[0].global);
// Lab: lightness 0..255 for 0..100, a and b offset by 128; no marker: spot.
let lib = read_bytes(&acb(7, &[("Grey", &[255, 128, 128])], b""), "x").unwrap();
assert_eq!(lib.swatches[0].paint.color(), Some(Color::lab(100.0, 0.0, 0.0)));
assert!(lib.swatches[0].spot);
assert!(sniff_bytes(&acb(0, &[], b"")));
// Unsupported versions and color spaces, and short files, are errors.
let mut v2 = acb(0, &[], b"");
v2[5] = 2;
assert!(read_bytes(&v2, "x").is_err());
assert!(read_bytes(&acb(1, &[("x", &[1, 2, 3])], b""), "x").is_err());
let full = acb(0, &[("185", &[228, 0, 43])], b"");
for cut in 4..full.len() {
assert!(read_bytes(&full[..cut], "x").is_err(), "{cut} bytes");
}
let mut huge = b"8BCB\0\x01\0\x01".to_vec();
huge.extend(u32::MAX.to_be_bytes());
assert!(read_bytes(&huge, "x").is_err(), "a string longer than the file");
}
fn sample() -> SwatchLibrary {
let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient {
kind: GradientKind::Linear,
+20 -5
View File
@@ -86,6 +86,19 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
/// [`hit_test`] passing over the nodes `skip` names (and their contents).
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool) -> Option<Hit> {
let finish = |mut h: Hit| {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
h
};
// Isolation mode: only what is inside the isolated container hits. The art around it is
// locked, and clicks pass through it (#833).
if let Some(scope) = opt.scope
&& let Some(container) = doc.node(scope).filter(|n| n.is_container())
&& let Some(mut chain) = doc.ancestry(scope)
{
return hit_children(container, p, opt, skip, &mut chain).map(finish);
}
let mut chain = Vec::new();
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked {
@@ -100,10 +113,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
}
chain.push(layer.id);
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
if let Some(mut h) = hit_children(layer, p, opt, skip, &mut chain) {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
return Some(h);
if let Some(h) = hit_children(layer, p, opt, skip, &mut chain) {
return Some(finish(h));
}
chain.pop();
}
@@ -560,7 +571,11 @@ world",
d.insert(Some(l), 9, far).unwrap();
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
assert_eq!(at(30.0, None), vec![g, a_id]);
assert_eq!(at(30.0, Some(g))[..2], [c_id, b_id], "isolated: the group's own objects");
assert_eq!(at(30.0, Some(g)), [c_id, b_id], "isolated: the group's own objects");
// Isolated, the art around the group is locked: clicks pass through it (#833).
assert!(at(5.0, Some(g)).is_empty());
assert!(at(130.0, Some(g)).is_empty());
assert!(hit_test(&d, Point::new(5.0, 25.0), HitOptions { scope: Some(g), ..HitOptions::default() }).is_none());
assert_eq!(at(5.0, None), vec![a_id]);
assert!(at(90.0, None).is_empty());
}
+28
View File
@@ -255,6 +255,34 @@ impl Align {
}
impl Document {
/// Rewrite linked file locations in both raster images and placed VectorCraft documents,
/// including those inside symbols, patterns and opacity masks. Used to make packages portable.
pub fn update_links(&mut self, mut f: impl FnMut(&mut LinkInfo)) {
fn walk(n: &mut Arc<Node>, f: &mut dyn FnMut(&mut LinkInfo)) {
let n = Arc::make_mut(n);
match &mut n.kind {
NodeKind::Image(image) => {
if let Some(link) = &mut image.link {
f(link);
}
}
NodeKind::PlacedDocument(placed) => f(&mut placed.link),
_ => {}
}
if let Some(mask) = &mut n.mask {
walk(&mut mask.art, f);
}
for child in n.children_mut().into_iter().flatten() {
walk(child, f);
}
}
let roots =
self.layers.iter_mut().chain(self.symbols.iter_mut().map(|s| &mut s.art)).chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
for root in roots {
walk(root, &mut f);
}
}
/// Change every image object (in the layers, symbol definitions and pattern swatches, opacity-mask
/// art included) for which `pick` holds; only the subtrees holding one are copied.
pub fn update_images(&mut self, pick: impl Fn(&ImageObject) -> bool, mut f: impl FnMut(&mut ImageObject)) {
+9 -1
View File
@@ -6,7 +6,7 @@
//! - **Geometry effects** (Distort & Transform, Path, Convert to Shape, Round Corners, Scribble,
//! Warp) rewrite a path: [`apply_geometry`] evaluates them in stack order.
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur, and the
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Unsharp Mask) are described by
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Unsharp Mask and Glowing Edges) are described by
//! [`raster_effects`] and painted by the renderer; [`outset`] says how far they reach beyond
//! the geometry.
//! - **Stroke geometry** ([`stroke`]): arrowheads, dash patterns and width profiles, shared by the
@@ -125,6 +125,7 @@ fn lengths_of(id: &str) -> Lengths {
"stylize.scribble" => always(&["overlap", "strokeWidth", "spacing", "variation"]),
"stylize.dropShadow" => always(&["x", "y", "blur"]),
"stylize.innerGlow" | "stylize.outerGlow" => always(&["blur"]),
"stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]),
_ => Lengths::default(),
}
}
@@ -290,6 +291,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"{amount: % 1..500 (50), radius: pt 0.1..250 (1; σ of the blur edges are found against), threshold: levels 0..255 (0; smaller differences are left alone)}",
json!({"amount": 50.0, "radius": 1.0, "threshold": 0.0}),
),
r(
"stylize.glowingEdges",
"Glowing Edges…",
STYLIZE,
"{edgeWidth: pt 1..14 (2), edgeBrightness: 0..20 (6), smoothness: pt 1..15 (5)} finds alpha-weighted Sobel edges and draws bright coloured outlines on black",
json!({"edgeWidth": 2.0, "edgeBrightness": 6.0, "smoothness": 5.0}),
),
];
v.extend([
g(
+87
View File
@@ -0,0 +1,87 @@
//! Stylize › Glowing Edges.
use super::blur_plane;
/// Find Sobel edges, smooth and expand them, then draw coloured outlines on black. Samples outside
/// the raster are transparent.
pub(super) fn glow(px: &mut [[u8; 4]], w: usize, h: usize, width: f64, brightness: f64, smoothness: f64) {
if w == 0 || h == 0 || w.checked_mul(h) != Some(px.len()) {
return;
}
let src = px.to_vec();
let pixel = |x: isize, y: isize| -> ([f32; 3], f32) {
// Beyond the raster's edges is transparency (not the next row's first pixel).
let (Ok(x), Ok(y)) = (usize::try_from(x), usize::try_from(y)) else { return ([0.0; 3], 0.0) };
if x >= w || y >= h {
return ([0.0; 3], 0.0);
}
let Some(p) = src.get(y * w + x) else { return ([0.0; 3], 0.0) };
let alpha = f32::from(p[3]) / 255.0;
let straight =
if alpha > 0.0 { [f32::from(p[0]) / 255.0 / alpha, f32::from(p[1]) / 255.0 / alpha, f32::from(p[2]) / 255.0 / alpha] } else { [0.0; 3] };
(straight, alpha)
};
let signal = |x: isize, y: isize| {
let (rgb, alpha) = pixel(x, y);
(0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) * alpha
};
let mut edges = vec![0.0f32; px.len()];
let mut colours: [Vec<f32>; 3] = std::array::from_fn(|_| vec![0.0; px.len()]);
for y in 0..h {
for x in 0..w {
let x = x as isize;
let y = y as isize;
let gx = -signal(x - 1, y - 1) + signal(x + 1, y - 1) - 2.0 * signal(x - 1, y) + 2.0 * signal(x + 1, y) - signal(x - 1, y + 1)
+ signal(x + 1, y + 1);
let gy = -signal(x - 1, y - 1) - 2.0 * signal(x, y - 1) - signal(x + 1, y - 1)
+ signal(x - 1, y + 1)
+ 2.0 * signal(x, y + 1)
+ signal(x + 1, y + 1);
let alpha_signal = |x, y| pixel(x, y).1;
let agx = -alpha_signal(x - 1, y - 1) + alpha_signal(x + 1, y - 1) - 2.0 * alpha_signal(x - 1, y) + 2.0 * alpha_signal(x + 1, y)
- alpha_signal(x - 1, y + 1)
+ alpha_signal(x + 1, y + 1);
let agy = -alpha_signal(x - 1, y - 1) - 2.0 * alpha_signal(x, y - 1) - alpha_signal(x + 1, y - 1)
+ alpha_signal(x - 1, y + 1)
+ 2.0 * alpha_signal(x, y + 1)
+ alpha_signal(x + 1, y + 1);
let index = y as usize * w + x as usize;
let edge = gx.hypot(gy).max(agx.hypot(agy)).clamp(0.0, 1.0);
if let Some(value) = edges.get_mut(index) {
*value = edge;
let (rgb, alpha) = pixel(x, y);
for channel in 0..3 {
colours[channel][index] = rgb[channel] * alpha * edge;
}
}
}
}
blur_plane(&mut edges, w, h, smoothness.max(0.0));
if width > 0.5 {
blur_plane(&mut edges, w, h, width * 0.5);
}
let peak = edges.iter().copied().fold(0.0f32, f32::max);
if peak > 0.0 {
for colour in &mut colours {
blur_plane(colour, w, h, smoothness.max(0.0));
if width > 0.5 {
blur_plane(colour, w, h, width * 0.5);
}
}
}
for (index, (out, (original, edge))) in px.iter_mut().zip(src.iter().zip(edges)).enumerate() {
let alpha = f32::from(original[3]) / 255.0;
let glow = if peak > 0.0 { (edge / peak * brightness as f32 / 6.0).clamp(0.0, 1.0) } else { 0.0 };
let colour_weight = colours[0][index].max(colours[1][index]).max(colours[2][index]);
let straight = if colour_weight > 1e-6 { std::array::from_fn(|channel| colours[channel][index] / colour_weight) } else { [0.0; 3] };
// Premultiplied: the glow is light of the edge's colour, so outside the shape it keeps that
// colour at the glow's opacity instead of darkening as it fades.
let a = alpha.max(glow);
*out = [
(straight[0] * glow * 255.0).round().clamp(0.0, 255.0) as u8,
(straight[1] * glow * 255.0).round().clamp(0.0, 255.0) as u8,
(straight[2] * glow * 255.0).round().clamp(0.0, 255.0) as u8,
(a * 255.0).round() as u8,
];
}
}
+13 -2
View File
@@ -1,5 +1,5 @@
//! Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Sharpen › Unsharp
//! Mask): filters over the pixels of an object rendered alone, premultiplied RGBA8.
//! Mask, and Stylize › Glowing Edges): filters over premultiplied RGBA8 pixels.
//!
//! - Every distance is in document units (points) and becomes pixels through the raster's
//! [`PixelSpace::px`], so an effect looks the same at any zoom and at any Document Raster Effects
@@ -9,6 +9,7 @@
//! - Beyond the raster's edges is transparency.
mod blur;
mod edges;
mod sharpen;
use serde_json::Value;
@@ -17,7 +18,7 @@ use vectorcraft_geom::{Affine, Point, Rect};
use crate::util::{num, text};
/// The Photoshop-style effect ids (all raster effects, see [`crate::is_raster`]).
pub const PIXEL_EFFECTS: [&str; 3] = ["blur.radial", "blur.smart", "sharpen.unsharpMask"];
pub const PIXEL_EFFECTS: [&str; 4] = ["blur.radial", "blur.smart", "sharpen.unsharpMask", "stylize.glowingEdges"];
/// A Photoshop-style raster effect with its parameters read and clamped to their ranges. Lengths
/// are in document units.
@@ -33,6 +34,8 @@ pub enum PixelFx {
/// Sharpen › Unsharp Mask: colours pushed away from a Gaussian blur of σ = `radius` by `amount`
/// (1 = 100 %), where they differ from it by at least `threshold` levels.
UnsharpMask { amount: f64, radius: f64, threshold: f64 },
/// Stylize › Glowing Edges: bright coloured Sobel outlines on black.
GlowingEdges { width: f64, brightness: f64, smoothness: f64 },
}
/// Where a raster's pixels lie in the document.
@@ -69,6 +72,11 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
radius: num(p, "radius", 1.0).clamp(0.1, 250.0),
threshold: num(p, "threshold", 0.0).clamp(0.0, 255.0),
},
"stylize.glowingEdges" => PixelFx::GlowingEdges {
width: num(p, "edgeWidth", 2.0).clamp(1.0, 14.0),
brightness: num(p, "edgeBrightness", 6.0).clamp(0.0, 20.0),
smoothness: num(p, "smoothness", 5.0).clamp(1.0, 15.0),
},
_ => return None,
})
}
@@ -85,6 +93,7 @@ impl PixelFx {
PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0),
PixelFx::SmartBlur { radius, .. } => radius,
PixelFx::UnsharpMask { .. } => 0.0,
PixelFx::GlowingEdges { width, smoothness, .. } => width.max(smoothness * 3.0),
}
}
@@ -95,6 +104,7 @@ impl PixelFx {
PixelFx::RadialBlur { .. } => None,
PixelFx::SmartBlur { radius, .. } => Some(radius),
PixelFx::UnsharpMask { radius, .. } => Some(3.0 * radius),
PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)),
}
}
@@ -107,6 +117,7 @@ impl PixelFx {
PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes),
PixelFx::SmartBlur { radius, threshold, samples } => blur::smart(px, w, h, to_px(radius), threshold, samples),
PixelFx::UnsharpMask { amount, radius, threshold } => sharpen::unsharp(px, w, h, amount, to_px(radius), threshold),
PixelFx::GlowingEdges { width, brightness, smoothness } => edges::glow(px, w, h, to_px(width), brightness, to_px(smoothness)),
}
}
}
+40
View File
@@ -55,6 +55,7 @@ fn params_take_defaults_and_stay_in_range() {
fx("sharpen.unsharpMask", json!({"amount": 1e9, "radius": 0, "threshold": 1e9})),
PixelFx::UnsharpMask { amount: 5.0, radius: 0.1, threshold: 255.0 }
);
assert_eq!(fx("stylize.glowingEdges", json!({})), PixelFx::GlowingEdges { width: 2.0, brightness: 6.0, smoothness: 5.0 });
for id in PIXEL_EFFECTS {
assert!(crate::is_raster(id) && crate::effect_info(id).is_some_and(|e| e.raster), "{id}");
}
@@ -120,6 +121,45 @@ fn every_effect_is_deterministic() {
}
}
#[test]
fn glowing_edges_draw_a_bright_outline_and_preserve_premultiplication() {
let (w, h) = (9, 9);
let src = image(w, h, |x, _| if x < 4 { [0, 0, 0, 200] } else { [200, 200, 200, 200] });
let mut out = src.clone();
fx("stylize.glowingEdges", json!({"edgeWidth": 1, "smoothness": 1, "edgeBrightness": 20})).apply(&mut out, w, h, &space(w, h));
assert!(at(&out, w, 3, 4)[0] > 0 || at(&out, w, 4, 4)[0] > 0);
assert!(out.as_chunks::<4>().0.iter().all(|p| p[0] <= p[3] && p[1] <= p[3] && p[2] <= p[3]));
}
/// Glowing Edges sees transparency beyond every side of the raster: a solid square glows alike at
/// its left and right edges (the right one doesn't read the next row's first pixel).
#[test]
fn glowing_edges_glow_alike_on_every_side() {
let (w, h) = (9, 9);
let mut out = image(w, h, |_, _| [180, 180, 180, 255]);
fx("stylize.glowingEdges", json!({"edgeWidth": 1, "smoothness": 1, "edgeBrightness": 20})).apply(&mut out, w, h, &space(w, h));
let (left, right, top, bottom) = (at(&out, w, 0, 4), at(&out, w, 8, 4), at(&out, w, 4, 0), at(&out, w, 4, 8));
assert!(left[0] > 0 && left == right && top == bottom, "{left:?} {right:?} {top:?} {bottom:?}");
assert!(at(&out, w, 4, 4)[0] < left[0], "the inside stays darker than the edges");
}
#[test]
fn glowing_edges_defaults_keep_the_outline_bright_and_use_source_colour() {
let (w, h) = (17, 17);
let src = image(w, h, |x, y| if (4..13).contains(&x) && (4..13).contains(&y) { [180, 0, 0, 255] } else { [0; 4] });
let mut out = src.clone();
fx("stylize.glowingEdges", json!({})).apply(&mut out, w, h, &space(w, h));
let outline = at(&out, w, 4, 8);
assert!(outline[0] >= 170, "default outline should retain a near-full-color peak: {outline:?}");
let outside = at(&out, w, 3, 8);
assert_eq!(outside[1], 0, "transparent halo must not be grey: {outside:?}");
assert_eq!(outside[2], 0, "transparent halo must retain source hue: {outside:?}");
// The glow outside keeps the edge's colour as it fades, rather than darkening towards grey.
assert!(outside[3] > 0 && u32::from(outside[0]) * 255 >= 240 * u32::from(outside[3]), "{outside:?}");
assert!(out.as_chunks::<4>().0.iter().all(|p| p[0] <= p[3] && p[1] <= p[3] && p[2] <= p[3]));
}
#[test]
fn spin_blur_smears_along_arcs_and_keeps_the_centre() {
let (w, h) = (41, 41);
+7
View File
@@ -52,6 +52,13 @@ impl RasterFx {
pub fn is_below(&self) -> bool {
matches!(self, RasterFx::DropShadow { .. } | RasterFx::OuterGlow { .. })
}
/// The blend mode it paints with (shadows and glows).
pub fn mode(&self) -> Option<BlendMode> {
match self {
RasterFx::DropShadow { mode, .. } | RasterFx::OuterGlow { mode, .. } | RasterFx::InnerGlow { mode, .. } => Some(*mode),
_ => None,
}
}
/// How far this effect reaches beyond `bounds`, what it paints around (Radial Blur reaches
/// further around larger objects).
pub fn outset(&self, bounds: Rect) -> f64 {
+79
View File
@@ -36,6 +36,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
curvature
),
cmd!(
"path.curvatureEdit",
"Curvature",
[],
None,
"{id, subpath?, op: \"move\"|\"insert\"|\"extend\"|\"close\", anchor?, segment?, t?, end?: \"start\"|\"end\", from?: \"keep\"|\"smooth\"|\"corner\", x?, y?} edit a path as the Curvature tool does, its shape kept elsewhere; the anchor edited becomes the direct-selected one → {anchor}. move: anchor to x, y, re-curving only its two segments; insert: a smooth anchor at t on segment, the shape unchanged (with x, y: then moved there); extend: an open subpath goes on from its end (default) or start to a new end at x, y; close: an open subpath closes from that end. The old end bends into the new segment as from says: keep its curve (default), smooth through its neighbours, or a corner",
has_doc,
curvature_edit
),
cmd!(
"path.removeAnchor",
"Delete Anchor Point",
@@ -593,6 +602,76 @@ fn curvature(s: &mut Session, p: &Value) -> Result<Value> {
add_look(s, "Curvature", path_kind(PathData::single(sp)), look, None)
}
/// An edit `path.curvatureEdit` makes.
enum CurvatureOp {
Move(usize, Point),
Insert(usize, f64, Option<Point>),
Extend(Point),
Close,
}
fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
const C: &str = "path.curvatureEdit";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
let si = p.get("subpath").and_then(Value::as_u64).unwrap_or(0) as usize;
let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
(Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some(Point::new(x, y)),
(None, None) => None,
_ => return Err(bad(C, "x and y must be finite numbers")),
};
let to = || at.ok_or_else(|| bad(C, "missing x, y"));
let start = match str_param(p, "end") {
None | Some("end") => false,
Some("start") => true,
Some(e) => return Err(bad(C, format!("unknown end {e:?}"))),
};
let how = match str_param(p, "from") {
None => EndCurve::Keep,
Some(f) => EndCurve::parse(f).ok_or_else(|| bad(C, format!("unknown from {f:?}")))?,
};
let op = match str_param(p, "op") {
Some("move") => CurvatureOp::Move(usize_req(p, "anchor", C)?, to()?),
Some("insert") => CurvatureOp::Insert(usize_req(p, "segment", C)?, f64_or(p, "t", 0.5), at),
Some("extend") => CurvatureOp::Extend(to()?),
Some("close") => CurvatureOp::Close,
Some(o) => return Err(bad(C, format!("unknown op {o:?}"))),
None => return Err(bad(C, "missing op")),
};
let anchor = s.edit("Curvature", |d, sel| {
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
if matches!(op, CurvatureOp::Extend(_) | CurvatureOp::Close) && sp.closed {
return Err(EngineError::Other("path is already closed".into()));
}
let ai = match op {
CurvatureOp::Move(ai, q) => curvature_move(sp, ai, q).then_some(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?,
CurvatureOp::Insert(seg, t, q) => {
let ai = curvature_insert(sp, seg, t).ok_or_else(|| EngineError::Other("no such segment".into()))?;
if let Some(q) = q {
curvature_move(sp, ai, q);
}
ai
}
CurvatureOp::Extend(q) => {
curvature_extend(sp, start, q, how);
if start { 0 } else { sp.anchors.len() - 1 }
}
CurvatureOp::Close => {
if sp.anchors.len() < 3 {
return Err(EngineError::Other("closing needs three anchors".into()));
}
curvature_close(sp, start, how);
if start { sp.anchors.len() - 1 } else { 0 }
}
};
sel.set([id]);
sel.anchors.insert(id, [(si, ai)].into());
Ok(ai)
})?;
Ok(json!({ "anchor": anchor }))
}
// ---------- anchor tools ----------
fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+4
View File
@@ -228,6 +228,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
};
// Threaded type read from a file flows through its frames.
if !doc.text_threads.is_empty() && !restored {
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
}
if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) {
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays);
}
+17
View File
@@ -0,0 +1,17 @@
//! Looking through a folder the user picks, and its subfolders, for files of some kind, on separate
//! threads: up to 8 walker threads share one stack of folders and list each folder once. They
//! follow no links and don't enter other apps' or the system's folders, hidden folders or folders
//! whose contents aren't on the disk ([`Rules`]); the time, the entries listed, the folders queued,
//! the depth and the files read are capped ([`Limits`]). [`start`] returns at once,
//! [`Search::progress`] reports where a search stands and [`Search::stop`] ends it. A search reads
//! the files [`Visitor::wants`] accepts by their names and [`Visitor::worth_reading`] by the files
//! themselves, and keeps those [`Visitor::items`] gives wanted items for.
//! The web has no file system: [`start`] fails there.
mod rules;
#[cfg(test)]
mod tests;
mod walk;
pub use rules::{Rules, plain};
pub use walk::{End, Limits, Progress, Search, Visitor, start, threads};
+409
View File
@@ -0,0 +1,409 @@
//! Where a folder search goes: not into other apps' or the system's folders. They are told by
//! their names and places (an app package, a home folder's `Library` or `AppData`, the system
//! folders at the root of a volume), never by the name of an app. Names and paths compare in
//! lowercase.
use std::path::{Component, Path, PathBuf};
/// Extensions of the packages apps and media libraries keep their files in.
const PACKAGE_EXTENSIONS: &[&str] = &[
"app",
"appex",
"bundle",
"component",
"fcpbundle",
"framework",
"imovielibrary",
"kext",
"musiclibrary",
"photolibrary",
"photoslibrary",
"plugin",
"tvlibrary",
"xpc",
];
/// The folders Windows installs programs and keeps their data and the system's in, wherever they
/// are.
const INSTALL_FOLDERS: &[&str] =
&["program files", "program files (x86)", "program files (arm)", "programdata", "$recycle.bin", "system volume information"];
/// The folders a home folder keeps apps and their data in (besides its hidden ones).
const HOME_APP_FOLDERS: &[&str] = &["library", "appdata", "applications", "snap"];
/// The folders a `Library` folder keeps apps' data in (macOS).
const LIBRARY_APP_FOLDERS: &[&str] = &["application support", "containers", "group containers", "caches", "preferences"];
/// The folders beside the home folders that apps share (macOS `Shared`, Windows `Public`).
const SHARED_FOLDERS: &[&str] = &["shared", "public"];
/// The system's folders at the root of a macOS volume (or a copy of one).
const MAC_SYSTEM: &[&str] =
&["applications", "bin", "cores", "dev", "etc", "home", "library", "net", "network", "opt", "private", "sbin", "system", "tmp", "usr", "var"];
/// The system's folders at the root of a Linux or BSD system (or a copy of one).
const UNIX_SYSTEM: &[&str] = &[
"bin",
"boot",
"dev",
"efi",
"etc",
"gnu",
"lib",
"lib32",
"lib64",
"libx32",
"lost+found",
"nix",
"opt",
"proc",
"root",
"run",
"sbin",
"snap",
"sys",
"usr",
"var",
];
/// The system's folders at the root of a Windows drive (or a copy of one), besides the install
/// folders.
const WINDOWS_SYSTEM: &[&str] =
&["windows", "windows.old", "recovery", "perflogs", "boot", "config.msi", "msocache", "$windows.~bt", "$windows.~ws", "$winreagent", "$sysreset"];
/// The most entries of a folder read to tell what kind of folder it is.
const MAX_SIBLINGS: usize = 100_000;
/// The names of the folders that show a folder is the root of a system ([`system_folders`]).
const SYSTEM_SIGNS: &[&str] = &["users", "system", "library", "applications", "windows", "program files", "etc", "usr", "bin", "sbin"];
/// Which of [`SYSTEM_SIGNS`] are among the names of a folder's folders and links.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Siblings(u16);
impl Siblings {
/// The folders and links named `names` (in any case).
#[cfg(test)]
pub(crate) fn of(names: &[&str]) -> Self {
let mut s = Self::default();
names.iter().for_each(|n| s.note(n));
s
}
/// Note a folder or link named `name` (in any case).
pub(crate) fn note(&mut self, name: &str) {
if let Some(i) = SYSTEM_SIGNS.iter().position(|s| s.eq_ignore_ascii_case(name)) {
self.0 |= 1 << i;
}
}
/// Whether a folder or link named `name`, one of [`SYSTEM_SIGNS`], was noted.
fn has(self, name: &str) -> bool {
SYSTEM_SIGNS.iter().position(|s| *s == name).is_some_and(|i| self.0 & (1 << i) != 0)
}
}
/// Why a search may not start in a folder ([`Rules::refusal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Refusal {
/// The folder is in other apps' or the system's folders, or in an app package.
Apps,
/// The folder is in the Shared or Public folder of a `Users` folder.
Shared,
}
/// A folder a walk lists, as the rules see it ([`Rules::listed`]).
pub(crate) struct Listed {
/// The folder, in lowercase.
dir: PathBuf,
/// Its name, in lowercase.
name: String,
/// The system folders in it, when it is the root of a system.
system: Option<&'static [&'static str]>,
/// It is a home folder.
home: bool,
}
/// Where a search may go.
#[derive(Clone, Debug, Default)]
pub struct Rules {
/// The home folder (canonical).
pub home: Option<PathBuf>,
/// Folders searched when picked, whatever holds them (canonical): the temporary folders, and
/// tests' folders.
pub user_content: Vec<PathBuf>,
/// Other apps' and the system's folders the environment names (canonical): never entered, and a
/// search of a folder inside one fails.
pub refused: Vec<PathBuf>,
}
/// `path` in lowercase and, on Windows, without its `\\?\` prefix ([`unprefixed`]), for comparing
/// paths.
fn lower(path: &Path) -> PathBuf {
let text = path.to_string_lossy();
let plain = if cfg!(windows) { unprefixed(&text) } else { None };
PathBuf::from(plain.as_deref().unwrap_or(&text).to_lowercase())
}
/// The system's folders a volume's root holds, when its folders (`siblings`) show it is the root of
/// an operating system.
fn system_folders(siblings: Siblings) -> Option<&'static [&'static str]> {
let has = |name: &str| siblings.has(name);
if has("users") && (has("system") || has("library") || has("applications")) {
Some(MAC_SYSTEM)
} else if has("windows") && (has("users") || has("program files")) {
Some(WINDOWS_SYSTEM)
} else if has("etc") && has("usr") && (has("bin") || has("sbin")) {
Some(UNIX_SYSTEM)
} else {
None
}
}
/// What the names of the folders and links in `dir` show ([`Siblings`]).
fn folder_siblings(dir: &Path) -> Siblings {
let mut siblings = Siblings::default();
for e in std::fs::read_dir(dir).into_iter().flatten().take(MAX_SIBLINGS).flatten() {
let name = e.file_name();
if let Some(name) = name.to_str()
&& e.file_type().is_ok_and(|t| t.is_dir() || t.is_symlink())
{
siblings.note(name);
}
}
siblings
}
/// The first `n` components of `path`.
fn prefix(path: &Path, n: usize) -> PathBuf {
path.components().take(n).collect()
}
/// `path` without the `\\?\` prefix that `std::fs::canonicalize` gives paths on Windows: `C:\…`
/// for `\\?\C:\…` and `\\server\share\…` for `\\?\UNC\server\share\…`, when every name in it can
/// be written without the prefix ([`without_verbatim`]). Other paths, and paths on other systems,
/// are returned as they are.
pub fn plain(path: PathBuf) -> PathBuf {
if !cfg!(windows) {
return path;
}
match path.to_str().and_then(without_verbatim) {
Some(p) => PathBuf::from(p),
None => path,
}
}
/// The Windows path `p` without its `\\?\` prefix, when it has one for a drive or a share: `C:\…`
/// for `\\?\C:\…` and `\\server\…` for `\\?\UNC\server\…`.
pub(crate) fn unprefixed(p: &str) -> Option<String> {
if let Some(unc) = p.strip_prefix(r"\\?\UNC\") {
return Some(format!(r"\\{unc}"));
}
let disk = p.strip_prefix(r"\\?\")?;
matches!(disk.as_bytes(), [d, b':', b'\\', ..] if d.is_ascii_alphabetic()).then(|| disk.to_string())
}
/// [`unprefixed`], when each name in the path can be written without the prefix ([`portable`]):
/// a share's server and share names, and the names below a drive's root or a share.
pub(crate) fn without_verbatim(p: &str) -> Option<String> {
let plain = unprefixed(p)?;
let (names, at_least) = match plain.strip_prefix(r"\\") {
Some(unc) => (unc, 2),
None => (plain.get(3..)?, 0),
};
let mut names: Vec<&str> = if names.is_empty() { vec![] } else { names.split('\\').collect() };
// A trailing separator.
if names.len() > at_least && names.last() == Some(&"") {
names.pop();
}
let ok = names.len() >= at_least && names.iter().all(|n| portable(n));
ok.then_some(plain)
}
/// Whether `name` can be a name in a Windows path without the `\\?\` prefix: not `.` or `..`, not
/// ending in a dot or a space, without `<>:"/\|?*` or control characters, and not a device name
/// (`CON`, `PRN`, `AUX`, `NUL`, `COM0` to `COM9`, `LPT0` to `LPT9`, these with a superscript digit,
/// `CONIN$`, `CONOUT$`), with an extension or not.
fn portable(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or(name).trim_end().to_ascii_lowercase();
let numbered = |device: &str| {
stem.strip_prefix(device).is_some_and(|n| {
let mut n = n.chars();
n.next().is_some_and(|c| c.is_ascii_digit() || "¹²³".contains(c)) && n.next().is_none()
})
};
let device = ["con", "prn", "aux", "nul", "conin$", "conout$"].contains(&stem.as_str()) || numbered("com") || numbered("lpt");
!name.is_empty()
&& name != "."
&& name != ".."
&& !name.ends_with(['.', ' '])
&& !name.chars().any(|c| c < ' ' || "<>:\"/\\|?*".contains(c))
&& !device
}
impl Rules {
/// This computer's: the home folder, the temporary folders, and the app and system folders the
/// environment names.
pub fn system() -> Self {
let canonical = |p: PathBuf| p.is_absolute().then(|| std::fs::canonicalize(&p).ok()).flatten();
let var = |name: &str| std::env::var_os(name).map(PathBuf::from).and_then(canonical);
let home = var(if cfg!(windows) { "USERPROFILE" } else { "HOME" });
let user_content = [std::env::temp_dir(), PathBuf::from("/tmp")].into_iter().filter_map(canonical).collect();
let names: &[&str] = if cfg!(windows) {
&["APPDATA", "LOCALAPPDATA", "ProgramData", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "SystemRoot"]
} else {
&[
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_CACHE_HOME",
"XDG_STATE_HOME",
"HOST_XDG_CONFIG_HOME",
"HOST_XDG_DATA_HOME",
"HOST_XDG_CACHE_HOME",
"HOST_XDG_STATE_HOME",
]
};
let refused = names.iter().filter_map(|n| var(n)).collect();
Rules { home, user_content, refused }
}
/// Whether `dir` is a home folder: the home folder, a folder in a `Users` or `home` folder, or
/// a folder the Flatpak document portal exports (`/run/user/<uid>/doc/<id>/<name>`).
fn is_home(&self, dir: &Path) -> bool {
if self.home.as_ref().is_some_and(|h| lower(h) == lower(dir)) {
return true;
}
let above = dir.parent().and_then(Path::file_name).map(|n| n.to_string_lossy().to_lowercase());
if matches!(above.as_deref(), Some("users" | "home")) {
return true;
}
let parts: Vec<String> = dir.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
matches!(parts.as_slice(), [_, run, user, uid, doc, _, _] if run == "run" && user == "user" && is_number(uid) && doc == "doc")
}
/// The folder `dir`, whose folders show `siblings`, as the rules see it when a walk lists it:
/// told once for all the folders in it.
pub(crate) fn listed(&self, dir: &Path, siblings: Siblings) -> Listed {
Listed {
dir: lower(dir),
name: dir.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default(),
system: system_folders(siblings),
home: self.is_home(dir),
}
}
/// Whether a search never enters the folder `name` in the listed folder `parent`: an app's
/// package, a Windows install folder, a system folder at the root of a volume, the folders apps
/// share beside the home folders, a `Library` folder's app data, or a home folder's hidden
/// folders and app folders.
pub(crate) fn never_in(&self, parent: &Listed, name: &str) -> bool {
let name = name.to_lowercase();
let name = name.as_str();
if Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| PACKAGE_EXTENSIONS.contains(&e)) || INSTALL_FOLDERS.contains(&name) {
return true;
}
if parent.system.is_some_and(|system| system.contains(&name)) {
return true;
}
match parent.name.as_str() {
"users" if SHARED_FOLDERS.contains(&name) => return true,
"library" if LIBRARY_APP_FOLDERS.contains(&name) => return true,
_ => {}
}
parent.home && (name.starts_with('.') || HOME_APP_FOLDERS.contains(&name))
}
/// [`Self::never_in`] the folder `parent`, whose folders show `siblings`.
#[cfg(test)]
pub(crate) fn never(&self, parent: &Path, siblings: Siblings, name: &str) -> bool {
self.never_in(&self.listed(parent, siblings), name)
}
/// The home folder, when the listed folder `parent` is the root of a system whose rules skip
/// the folder the home folder is in (`/usr/home/me` on FreeBSD, `/var/home/me`): a walk of the
/// root reaches it this way.
pub(crate) fn home_below(&self, parent: &Listed) -> Option<PathBuf> {
let home = self.home.as_ref()?;
let system = parent.system?;
let below = lower(home).strip_prefix(&parent.dir).ok()?.components().next()?.as_os_str().to_string_lossy().into_owned();
system.contains(&below.as_str()).then(|| home.clone())
}
/// Whether `path` is one of the refused folders.
pub(crate) fn is_refused(&self, path: &Path) -> bool {
let path = lower(path);
self.refused.iter().any(|r| lower(r) == path)
}
/// The folders that hold user content whatever holds them, as far as they hold `folder`: the
/// home folder, [`Self::user_content`], the cloud storage folders in the home folder's
/// `Library` (an app's own iCloud `Documents` folder too), removable media and a user's runtime
/// folder on Linux (network shares, the document portal).
fn bases(&self, folder: &Path) -> Vec<PathBuf> {
let mut v = self.user_content.clone();
let lowered = lower(folder);
if let Some(home) = &self.home {
v.push(home.clone());
let library = home.join("Library");
v.push(library.join("CloudStorage"));
let mobile = library.join("Mobile Documents");
v.push(mobile.join("com~apple~CloudDocs"));
let depth = mobile.components().count();
if lowered.starts_with(lower(&mobile)) && lowered.components().nth(depth + 1).is_some_and(|c| c.as_os_str() == "documents") {
v.push(prefix(folder, depth + 2));
}
}
v.push(PathBuf::from("/run/media"));
let parts: Vec<String> = folder.components().take(4).map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
if matches!(parts.as_slice(), [_, run, user, uid] if run == "run" && user == "user" && is_number(uid)) {
v.push(prefix(folder, 4));
}
v
}
/// Why a search may not start in `folder` (canonical), or `None` when it may: the deepest base
/// ([`Self::bases`]) or refused folder that holds it is a refused one, or a folder below that
/// base (or below the root, without one) is one a walk doesn't enter.
pub(crate) fn refusal(&self, folder: &Path) -> Option<Refusal> {
self.refusal_with(folder, folder_siblings)
}
/// [`Self::refusal`] without listing a folder: the root of a system, told by the folders it
/// holds, isn't recognized.
pub(crate) fn refusal_unlisted(&self, folder: &Path) -> Option<Refusal> {
self.refusal_with(folder, |_| Siblings::default())
}
/// [`Self::refusal`], with `siblings` telling what a folder's folders show.
fn refusal_with(&self, folder: &Path, siblings: impl Fn(&Path) -> Siblings) -> Option<Refusal> {
let lowered = lower(folder);
let held = |p: &PathBuf| lowered.starts_with(lower(p)).then(|| p.components().count());
let base = self.bases(folder).iter().filter_map(held).max();
let refused = self.refused.iter().filter_map(held).max();
let start = match (base, refused) {
(_, Some(r)) if base.is_none_or(|b| r >= b) => return Some(Refusal::Apps),
(Some(b), _) => b,
// From the root of the folder's volume.
(None, _) => folder.components().take_while(|c| matches!(c, Component::Prefix(_) | Component::RootDir)).count(),
};
let mut parent = prefix(folder, start);
for c in folder.components().skip(start) {
let child = parent.join(c);
let listed = self.listed(&parent, siblings(&parent));
let name = c.as_os_str().to_string_lossy().to_lowercase();
if listed.name == "users" && SHARED_FOLDERS.contains(&name.as_str()) {
return Some(Refusal::Shared);
}
if self.never_in(&listed, &name) || self.is_refused(&child) {
return Some(Refusal::Apps);
}
parent = child;
}
None
}
}
/// Whether `s` is a number (a user id).
fn is_number(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
+545
View File
@@ -0,0 +1,545 @@
//! The folder search: where it goes and where it doesn't, its limits, its threads.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use super::rules::{Siblings, unprefixed, without_verbatim};
use super::walk::{Pool, start_in};
use super::*;
/// The walker threads of these tests' searches, apart from the searches of other tests.
static TESTS: Pool = Pool::new(32);
/// [`start`] on the threads of [`TESTS`].
fn begin(folder: PathBuf, rules: Rules, limits: Limits, threads: usize, items: usize, visitor: Arc<dyn Visitor>) -> Search {
start_in(&TESTS, folder, Some(rules), limits, threads, items, visitor).unwrap()
}
/// Reads `.ttf` files; each is the item its name is in the list.
struct Names(&'static [&'static str]);
impl Visitor for Names {
fn wants(&self, name: &str) -> bool {
name.ends_with(".ttf")
}
fn items(&self, path: &Path) -> Vec<usize> {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
self.0.iter().position(|n| *n == name).into_iter().collect()
}
}
/// Reads every file, and waits on reading one until its channel sends or closes.
struct Blocked(Mutex<mpsc::Receiver<()>>);
impl Visitor for Blocked {
fn wants(&self, _: &str) -> bool {
true
}
fn items(&self, _: &Path) -> Vec<usize> {
let _ = self.0.lock().unwrap().recv();
vec![]
}
}
/// A fresh folder (canonical, as a search reports it) holding `paths`: files, and folders where
/// they end in `/`.
fn tree(tag: &str, paths: &[&str]) -> PathBuf {
let root = vectorcraft_testkit::temp_dir(&format!("findfiles-{tag}"));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
for p in paths {
let path = root.join(p);
if p.ends_with('/') {
std::fs::create_dir_all(&path).unwrap();
} else {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"font").unwrap();
}
}
plain(std::fs::canonicalize(&root).unwrap())
}
/// The rules of a search of `root`: its `Users/me` is the home folder, `refused` an app's folder.
fn rules(root: &Path) -> Rules {
Rules { home: Some(root.join("Users/me")), user_content: vec![root.to_path_buf()], refused: vec![root.join("refused")] }
}
/// The search's progress once it ended (or after 10 seconds).
fn wait(s: &Search) -> Progress {
let until = Instant::now() + Duration::from_secs(10);
loop {
let p = s.progress();
if p.end.is_some() || Instant::now() > until {
return p;
}
std::thread::sleep(Duration::from_millis(2));
}
}
/// Search `from` in `root` for the files named `names`, to the end.
fn search(root: &Path, from: &str, limits: Limits, threads: usize, names: &'static [&'static str]) -> Progress {
let s = begin(root.join(from), rules(root), limits, threads, names.len(), Arc::new(Names(names)));
wait(&s)
}
/// The files a search found, relative to `root`, sorted.
fn found(root: &Path, p: &Progress) -> Vec<String> {
let mut v: Vec<String> = p.hits.iter().map(|(f, _)| f.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/")).collect();
v.sort();
v
}
#[test]
fn the_walk_stays_out_of_other_apps_and_the_systems_folders() {
let root = tree(
"roles",
&[
"a/b/c/one.ttf",
"Users/me/Documents/two.ttf",
"Disk/Fonts/four.ttf",
"Disk/Users/you/Documents/four.ttf",
// Never entered: each of these folders counts as skipped once.
"Program Files/x/three.ttf",
"Program Files (Arm)/x/three.ttf",
"Users/me/Library/Fonts/three.ttf",
"Users/me/.cache/three.ttf",
"Users/me/AppData/Roaming/three.ttf",
"Users/you/snap/three.ttf",
"Users/Shared/x/three.ttf",
"Pictures/P.photoslibrary/three.ttf",
"Tools/Foo.app/Contents/three.ttf",
"Copy/Library/Application Support/x/three.ttf",
".hidden/three.ttf",
"refused/three.ttf",
"Disk/System/Library/Fonts/three.ttf",
"Disk/Library/Fonts/three.ttf",
"Disk/Applications/three.ttf",
"Disk/Users/you/Library/three.ttf",
],
);
let p = search(&root, "", Limits::default(), 3, &["one.ttf", "two.ttf", "three.ttf", "four.ttf"]);
assert_eq!(p.end, Some(End::Done));
assert_eq!(found(&root, &p), ["Disk/Fonts/four.ttf", "Disk/Users/you/Documents/four.ttf", "Users/me/Documents/two.ttf", "a/b/c/one.ttf"]);
assert_eq!(p.skipped, 16);
assert_eq!((p.read, p.unreadable), (4, 0));
}
#[test]
fn a_picked_folder_inside_other_apps_folders_is_refused() {
let root = tree(
"picks",
&[
"Users/me/Library/Fonts/",
"Users/me/Library/CloudStorage/Box/F/",
"Users/me/Library/Mobile Documents/x~y/Documents/",
"Users/me/Library/Mobile Documents/x~y/Other/",
"Users/me/.config/fonts/",
"Users/Shared/x/",
"Disk/Users/",
"Disk/System/",
"Disk/Library/Fonts/",
"Tools/Foo.app/Contents/",
"refused/sub/",
"Program Files/x/",
"Program Files (Arm)/x/",
"Users/Public/x/",
"a/.b/",
"file.ttf",
],
);
for picked in [
"Users/me/Library/Fonts",
"Users/me/Library/Mobile Documents/x~y/Other",
"Users/me/.config/fonts",
"Disk/Library/Fonts",
"Tools/Foo.app/Contents",
"refused",
"refused/sub",
"Program Files/x",
"Program Files (Arm)/x",
] {
let p = search(&root, picked, Limits::default(), 1, &[]);
assert_eq!(p.state(), "failed", "{picked}");
assert!(p.error().is_some_and(|e| e.contains("doesn't search other apps' or the system's folders")), "{picked}: {p:?}");
}
for picked in ["Users/Shared/x", "Users/Public/x"] {
let p = search(&root, picked, Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.contains("doesn't search the Shared or Public folder in Users")), "{picked}: {p:?}");
}
// Cloud folders, a hidden folder of the user's and another system's root are searched when
// picked.
for picked in ["Users/me/Library/CloudStorage/Box/F", "Users/me/Library/Mobile Documents/x~y/Documents", "a/.b", "Disk", "Disk/Users", ""] {
let p = search(&root, picked, Limits::default(), 1, &[]);
assert_eq!((p.state(), p.error()), ("done", None), "{picked}");
}
let p = search(&root, "file.ttf", Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.ends_with("is not a folder")), "{p:?}");
let p = search(&root, "missing", Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.starts_with(&root.join("missing").display().to_string())), "{p:?}");
}
#[test]
fn the_search_ends_at_its_limits_and_when_stopped() {
let root = tree("limits", &["one.ttf", "two.ttf", "a/b/c/three.ttf", "x/y.txt"]);
let names = &["one.ttf", "two.ttf", "three.ttf", "nowhere.ttf"];
// The picked folder and the folders in it are listed, not the ones below them.
let p = search(&root, "", Limits { depth: 1, ..Limits::default() }, 2, names);
assert_eq!(p.end, Some(End::Done));
assert_eq!(found(&root, &p), ["one.ttf", "two.ttf"]);
assert_eq!((p.folders, p.skipped), (3, 1));
let p = search(&root, "", Limits { entries: 3, ..Limits::default() }, 1, names);
assert_eq!((p.state(), p.stopped()), ("stopped", Some("limit")));
let p = search(&root, "", Limits { files: 1, ..Limits::default() }, 1, names);
assert_eq!((p.stopped(), p.read), (Some("limit"), 1));
let p = search(&root, "", Limits { hits: 1, ..Limits::default() }, 1, names);
assert_eq!((p.stopped(), p.hits.len()), (Some("limit"), 1));
// Each item keeps at most `per_item` files.
let root = tree("per-item", &["a/one.ttf", "b/one.ttf", "c/one.ttf"]);
let p = search(&root, "", Limits { per_item: 2, ..Limits::default() }, 1, &["one.ttf", "nowhere.ttf"]);
assert_eq!((p.end, p.hits.len(), p.read), (Some(End::Done), 2, 3));
}
#[test]
fn the_search_answers_at_its_deadline_while_a_walker_is_blocked() {
let root = tree("blocked", &["f.ttf"]);
let (tx, rx) = mpsc::channel();
let s = begin(root.clone(), rules(&root), Limits { seconds: 0.2, ..Limits::default() }, 1, 1, Arc::new(Blocked(Mutex::new(rx))));
std::thread::sleep(Duration::from_millis(300));
let p = s.progress();
assert_eq!((p.state(), p.stopped()), ("stopped", Some("time")), "{p:?}");
assert!(p.seconds >= 0.2 && p.seconds < 5.0, "{p:?}");
let (tx2, rx2) = mpsc::channel();
let s2 = begin(root.clone(), rules(&root), Limits::default(), 1, 1, Arc::new(Blocked(Mutex::new(rx2))));
let until = Instant::now() + Duration::from_secs(10);
while s2.progress().read == 0 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(s2.progress().state(), "searching");
s2.stop();
assert_eq!(s2.progress().stopped(), Some("stop"));
drop((tx, tx2));
}
/// Every file is item 0; reading the second file waits until the channel closes.
struct SecondBlocks(Mutex<(usize, mpsc::Receiver<()>)>);
impl Visitor for SecondBlocks {
fn wants(&self, _: &str) -> bool {
true
}
fn items(&self, _: &Path) -> Vec<usize> {
let mut read = self.0.lock().unwrap();
read.0 += 1;
if read.0 == 2 {
let _ = read.1.recv();
}
vec![0]
}
}
/// A file is kept as soon as it is read: progress shows it while the rest of its folder is read,
/// and a search that stops or reaches a limit keeps it.
#[test]
fn files_found_are_kept_as_they_are_read() {
let root = tree("kept", &["a.ttf", "b.ttf", "c.ttf"]);
let (tx, rx) = mpsc::channel();
let s = begin(root.clone(), rules(&root), Limits::default(), 1, 2, Arc::new(SecondBlocks(Mutex::new((0, rx)))));
let until = Instant::now() + Duration::from_secs(10);
while s.progress().read < 2 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
let p = s.progress();
assert_eq!((p.state(), p.hits.len()), ("searching", 1), "{p:?}");
s.stop();
drop(tx);
let p = wait(&s);
assert_eq!(p.stopped(), Some("stop"));
assert!(!p.hits.is_empty(), "{p:?}");
let p = search(&root, "", Limits { files: 2, ..Limits::default() }, 1, &["a.ttf", "b.ttf", "c.ttf", "nowhere.ttf"]);
assert_eq!((p.stopped(), p.hits.len()), (Some("limit"), 2), "{p:?}");
}
#[test]
fn the_search_ends_once_every_item_has_a_file() {
let root = tree("found", &["a/one.ttf", "b/two.ttf", "c/d/e/f/g/other.ttf"]);
let p = search(&root, "", Limits::default(), 2, &["one.ttf", "two.ttf"]);
assert_eq!((p.end.clone(), found(&root, &p)), (Some(End::Found), vec!["a/one.ttf".to_string(), "b/two.ttf".into()]));
}
#[test]
fn one_walker_and_eight_find_the_same_files_and_every_search_ends() {
let mut paths = vec![];
for a in 0..6 {
for b in 0..4 {
paths.push(format!("d{a}/e{b}/one.ttf"));
paths.push(format!("d{a}/e{b}/f/two.ttf"));
paths.push(format!("d{a}/e{b}/f/g/skip.txt"));
}
}
let paths: Vec<&str> = paths.iter().map(String::as_str).collect();
let root = tree("threads", &paths);
let limits = Limits { per_item: 100, ..Limits::default() };
let one = search(&root, "", limits, 1, &["one.ttf", "two.ttf", "nowhere.ttf"]);
assert_eq!((one.end.clone(), one.hits.len(), one.folders), (Some(End::Done), 48, 1 + 6 + 24 + 24 + 24));
for round in 0..25 {
for threads in 1..=8 {
let p = search(&root, "", limits, threads, &["one.ttf", "two.ttf", "nowhere.ttf"]);
assert_eq!(p.end, Some(End::Done), "round {round}, {threads} threads");
assert_eq!(found(&root, &p), found(&root, &one), "round {round}, {threads} threads");
}
}
}
/// Fails on `boom.ttf` with a panic: a bug in reading one file.
struct Boom;
impl Visitor for Boom {
fn wants(&self, name: &str) -> bool {
name.ends_with(".ttf")
}
fn items(&self, path: &Path) -> Vec<usize> {
match path.file_name().and_then(|n| n.to_str()) {
Some("boom.ttf") => panic!("a bug"),
Some("ok.ttf") => vec![0],
_ => vec![1],
}
}
}
#[test]
fn a_visitor_that_panics_on_one_file_does_not_end_the_search() {
// The file beside the one that trips the bug is found too.
let root = tree("boom", &["a/boom.ttf", "a/ok.ttf", "b/c/fine.ttf"]);
let s = begin(root.clone(), rules(&root), Limits::default(), 2, 3, Arc::new(Boom));
let p = wait(&s);
assert_eq!((p.end.clone(), found(&root, &p), p.unreadable), (Some(End::Done), vec!["a/ok.ttf".to_string(), "b/c/fine.ttf".into()], 1));
}
#[cfg(unix)]
#[test]
fn links_are_not_followed_and_unreadable_folders_count() {
use std::os::unix::fs::{PermissionsExt, symlink};
let root = tree("links", &["outside/x.ttf", "inner/locked/y.ttf"]);
let inner = root.join("inner");
symlink(root.join("outside"), inner.join("folder")).unwrap();
symlink(&inner, inner.join("loop")).unwrap();
symlink(root.join("outside/x.ttf"), inner.join("x.ttf")).unwrap();
let locked = inner.join("locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
// Where permissions don't hold (root), the folder reads as any other.
let enforced = std::fs::read_dir(&locked).is_err();
let p = search(&root, "inner", Limits::default(), 2, &["x.ttf", "y.ttf"]);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(p.end, Some(End::Done));
if enforced {
assert!(p.hits.is_empty() && p.unreadable == 1, "{p:?}");
} else {
assert_eq!(found(&root, &p), ["inner/locked/y.ttf"]);
}
// The linked file isn't a file of the folder; y.ttf is one where the locked folder reads.
assert_eq!(p.files, u64::from(!enforced), "{p:?}");
}
#[cfg(unix)]
#[test]
fn a_picked_folder_that_cant_be_listed_fails_the_search() {
use std::os::unix::fs::PermissionsExt;
let root = tree("unlistable", &["locked/y.ttf"]);
let locked = root.join("locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
// Where permissions don't hold (root), the folder reads as any other.
let enforced = std::fs::read_dir(&locked).is_err();
let p = search(&root, "locked", Limits::default(), 2, &["y.ttf"]);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
if enforced {
assert!(matches!(&p.end, Some(End::Failed(e)) if e.contains("locked")), "{p:?}");
} else {
assert_eq!(found(&root, &p), ["locked/y.ttf"]);
}
}
#[test]
fn system_roots_and_homes_are_told_by_what_they_hold() {
let r = Rules { home: Some(PathBuf::from("/home/me")), ..Rules::default() };
let never = |parent: &str, siblings: Siblings, name: &str| r.never(Path::new(parent), siblings, name);
let none = Siblings::default();
let mac = Siblings::of(&["Users", "Library", "System", "Applications", "Volumes", "opt"]);
for name in ["Library", "System", "Applications", "opt", "private"] {
assert!(never("/", mac, name), "{name}");
}
for name in ["Users", "Volumes", "Fonts"] {
assert!(!never("/", mac, name), "{name}");
}
let unix = Siblings::of(&["usr", "etc", "bin", "home", "nix", "srv", "data", "mnt"]);
for name in ["usr", "etc", "bin", "nix", "var", "proc"] {
assert!(never("/", unix, name), "{name}");
}
for name in ["home", "srv", "data", "mnt", "media"] {
assert!(!never("/", unix, name), "{name}");
}
let windows = Siblings::of(&["Windows", "Users", "Program Files", "Data"]);
for name in ["Windows", "Program Files", "Recovery"] {
assert!(never("C:\\", windows, name), "{name}");
}
for name in ["Data", "Users"] {
assert!(!never("C:\\", windows, name), "{name}");
}
// A project that holds a bin and an etc folder isn't the root of a system.
let project = Siblings::of(&["bin", "etc", "src"]);
assert!(!never("/work/p", project, "bin") && !never("/work/p", project, "etc"));
// Home folders: the home folder, and every folder in a Users or home folder.
for name in ["Library", ".config", "snap", "AppData", "Applications"] {
assert!(never("/home/me", none, name), "{name}");
assert!(never("/Users/you", none, name), "{name}");
}
assert!(!never("/home/me", none, "Documents") && !never("/home/me/Documents", none, "Library"));
assert!(never("/run/user/1000/doc/a1b2/me", none, "snap"), "a folder the document portal exports");
assert!(never("/Users", none, "Shared") && never("/Users", none, "Public"));
assert!(never("/Volumes/Copy/Library", none, "Application Support") && !never("/Volumes/Copy/Library", none, "Fonts"));
assert!(never("/x", none, "Foo.app") && never("/x", none, "Program Files (x86)") && !never("/x", none, "Fonts.d"));
assert!(never("/x", none, "Program Files (Arm)"));
// A system root's walk reaches a home folder below a folder it skips (FreeBSD's /usr/home).
let bsd = Rules { home: Some(PathBuf::from("/usr/home/me")), ..Rules::default() };
let root = Path::new("/");
assert_eq!(bsd.home_below(&bsd.listed(root, unix)), Some(PathBuf::from("/usr/home/me")));
assert_eq!(r.home_below(&r.listed(root, unix)), None);
assert_eq!(bsd.home_below(&bsd.listed(root, project)), None);
}
#[test]
fn a_search_starts_with_the_threads_left_and_fails_when_none_is() {
static POOL: Pool = Pool::new(3);
let root = tree("pool", &["f.ttf"]);
let blocked = || {
let (tx, rx) = mpsc::channel();
(tx, Arc::new(Blocked(Mutex::new(rx))) as Arc<dyn Visitor>)
};
let (tx_a, a) = blocked();
let (tx_b, b) = blocked();
let a = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 2, 1, a).unwrap();
let b = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 4, 1, b).unwrap();
assert_eq!(POOL.live(), 3);
let (_, c) = blocked();
let c = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 1, 1, c);
assert_eq!(c.err().as_deref(), Some("the search couldn't start: try again in a moment"));
drop((tx_a, tx_b));
assert_eq!((wait(&a).end, wait(&b).end), (Some(End::Done), Some(End::Done)));
let until = Instant::now() + Duration::from_secs(10);
while POOL.live() > 0 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(POOL.live(), 0, "every walker thread ended");
let s = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 8, 1, Arc::new(Names(&[]))).unwrap();
assert_eq!(wait(&s).end, Some(End::Done));
}
#[test]
fn a_search_takes_the_cpus_the_renderer_leaves_from_two_to_eight() {
use super::walk::threads_for;
assert_eq!([threads_for(64, 4), threads_for(12, 4), threads_for(4, 4), threads_for(1, 0)], [8, 7, 2, 2]);
assert!((2..=8).contains(&threads()));
}
/// A folder holding more folders than a search queues ends the search while it is being listed.
#[test]
fn a_folder_with_more_folders_than_the_search_queues_ends_it_as_it_is_listed() {
// Folders and files made in turns: whatever order a file system lists them in, about half of a
// folder's first entries are folders.
let names: Vec<String> = (0..2048).flat_map(|i| [format!("d{i}/"), format!("f{i}.txt")]).collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
let root = tree("many-folders", &names);
let p = search(&root, "", Limits { folders: 10, ..Limits::default() }, 1, &[]);
assert_eq!(p.end, Some(End::Limit));
assert!(p.files < 2048, "the folder was listed to its end: {p:?}");
}
/// Wants every file, counting the files it is asked about.
struct Counted(AtomicUsize);
impl Visitor for Counted {
fn wants(&self, _: &str) -> bool {
self.0.fetch_add(1, Ordering::Relaxed);
true
}
fn items(&self, _: &Path) -> Vec<usize> {
vec![]
}
}
/// A folder's files past those the search reads aren't kept to be read.
#[test]
fn files_past_those_the_search_reads_are_not_kept() {
let names: Vec<String> = (0..50).map(|i| format!("f{i}.ttf")).collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
let root = tree("many-files", &names);
let counted = Arc::new(Counted(AtomicUsize::new(0)));
let p = wait(&begin(root.clone(), rules(&root), Limits { files: 3, ..Limits::default() }, 1, 1, counted.clone()));
assert_eq!((p.stopped(), p.read, p.files), (Some("limit"), 3, 50), "{p:?}");
assert_eq!(counted.0.load(Ordering::Relaxed), 4, "one more than the files read");
}
/// Wants `.ttf` files by their names, turns down those whose names start with `skip` by the file,
/// and finds `font.ttf`.
struct Picky;
impl Visitor for Picky {
fn wants(&self, name: &str) -> bool {
name.ends_with(".ttf")
}
fn worth_reading(&self, path: &Path) -> bool {
!path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("skip"))
}
fn items(&self, path: &Path) -> Vec<usize> {
if path.ends_with("font.ttf") { vec![0] } else { vec![] }
}
}
/// Files a visitor turns down by the file itself aren't read and don't count among the files
/// read: with room to read one file, the search gets past them to the font in the folder below.
#[test]
fn files_turned_down_by_the_file_are_not_read() {
let root = tree("turned-down", &["skip1.ttf", "skip2.ttf", "skip3.ttf", "sub/font.ttf"]);
let p = wait(&begin(root.clone(), rules(&root), Limits { files: 1, ..Limits::default() }, 1, 1, Arc::new(Picky)));
assert_eq!((p.end.clone(), p.read, found(&root, &p)), (Some(End::Found), 1, vec!["sub/font.ttf".to_string()]), "{p:?}");
}
/// Windows paths lose the `\\?\` prefix `canonicalize` gives them where they read the same
/// without it. Paths compare the same with the prefix and without it.
#[test]
fn windows_paths_lose_the_verbatim_prefix_where_they_read_the_same() {
for (verbatim, without) in [
(r"\\?\C:\Users\me\Fonts", r"C:\Users\me\Fonts"),
(r"\\?\d:\", r"d:\"),
(r"\\?\UNC\server\share\a b\c.otf", r"\\server\share\a b\c.otf"),
(r"\\?\UNC\server\share", r"\\server\share"),
(r"\\?\UNC\server\share\", r"\\server\share\"),
] {
assert_eq!(without_verbatim(verbatim).as_deref(), Some(without), "{verbatim}");
}
// For comparing, any name goes.
assert_eq!(unprefixed(r"\\?\C:\a.\b").as_deref(), Some(r"C:\a.\b"));
assert_eq!(unprefixed(r"\\?\UNC\server").as_deref(), Some(r"\\server"));
assert_eq!((unprefixed(r"\\?\C:"), unprefixed(r"C:\a"), unprefixed("/home/me")), (None, None, None));
for kept in [
r"\\?\C:",
r"\\?\C:\a.\b",
r"\\?\C:\a \b",
r"\\?\C:\CON\b",
r"\\?\C:\a\nul.txt",
r"\\?\C:\a\COM¹",
r"\\?\C:\a/b",
r"\\?\C:\a\..\b",
r"\\?\C:\a\\b",
r"\\?\Volume{00000000-0000-0000-0000-000000000000}\a",
r"\\?\UNC\server",
r"C:\a",
"/home/me",
] {
assert_eq!(without_verbatim(kept), None, "{kept}");
}
if !cfg!(windows) {
assert_eq!(plain(PathBuf::from(r"\\?\C:\a")), PathBuf::from(r"\\?\C:\a"), "other systems' paths stay as they are");
}
}
+666
View File
@@ -0,0 +1,666 @@
//! The walker threads of a folder search and what they share.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};
use super::rules::{Refusal, Rules, Siblings, plain};
/// The most walker threads one search starts.
const MAX_THREADS: usize = 8;
/// The most walker threads all searches together have running.
const MAX_LIVE: usize = 32;
/// How often a walker with nothing to do looks again (the deadline, the end).
const IDLE: Duration = Duration::from_millis(50);
/// How many entries of a folder a walker lists between looks at the end, the deadline and the
/// folders waiting to be listed.
const CHECK_EVERY: u64 = 1024;
/// How a search ends when every walker thread stopped on a bug.
const INTERNAL: &str = "every search thread stopped on an internal error (please report this bug)";
/// What a search looks for.
pub trait Visitor: Send + Sync {
/// Whether the regular file named `name` is to be read: asked of the files a folder lists until
/// it has one more of them to read than [`Limits::files`].
fn wants(&self, name: &str) -> bool;
/// Whether the file at `path`, which [`Self::wants`] took by its name, is to be read after all,
/// by what the file itself is. A file turned down here doesn't count among the files read.
fn worth_reading(&self, _path: &Path) -> bool {
true
}
/// The wanted items (indexes below the search's item count) the file at `path` is.
fn items(&self, path: &Path) -> Vec<usize>;
}
/// The caps on a search.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Limits {
/// Seconds before it ends (0 to 3600; 60 when not finite).
pub seconds: f64,
/// Entries listed, in every folder.
pub entries: u64,
/// Folders waiting to be listed.
pub folders: usize,
/// Folders below the picked one.
pub depth: u32,
/// Files read.
pub files: u64,
/// Files kept for each item.
pub per_item: usize,
/// Files kept in all.
pub hits: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { seconds: 60.0, entries: 10_000_000, folders: 1_000_000, depth: 64, files: 10_000, per_item: 10, hits: 1_000 }
}
}
/// How a search ended.
#[derive(Clone, Debug, PartialEq)]
pub enum End {
/// Every folder it could enter was searched.
Done,
/// Every item has a file.
Found,
/// [`Search::stop`].
Stopped,
/// [`Limits::seconds`] passed.
Time,
/// The entries listed, the folders waiting to be listed, the files read or the files kept
/// reached their [`Limits`]. Folders deeper than [`Limits::depth`] are skipped and an item
/// keeps at most [`Limits::per_item`] files, without ending the search.
Limit,
/// It couldn't start: the folder can't be read, isn't a folder or isn't one to search.
Failed(String),
}
/// Where a search stands ([`Search::progress`]).
#[derive(Clone, Debug, Default)]
pub struct Progress {
/// `None` while it runs.
pub end: Option<End>,
/// The folder searched (canonical, through [`plain`]), once it was checked. The walk reads the
/// folder and the files below it by the paths with the `\\?\` prefix that Windows gives them.
pub folder: PathBuf,
/// The files found, each with the items it is, in the order found (through [`plain`]).
pub hits: Vec<(PathBuf, Vec<usize>)>,
/// Folders listed.
pub folders: u64,
/// Files listed.
pub files: u64,
/// Files read.
pub read: u64,
/// Folders not entered (other apps', the system's, hidden ones, ones too deep, ones whose
/// contents aren't on the disk, ones whose names can't be read).
pub skipped: u64,
/// Folders and files that couldn't be read.
pub unreadable: u64,
/// How long it ran, or has been running.
pub seconds: f64,
}
impl Progress {
/// `searching`, `done` ([`End::Done`], [`End::Found`]), `stopped` ([`End::Stopped`],
/// [`End::Time`], [`End::Limit`]) or `failed`.
pub fn state(&self) -> &'static str {
match &self.end {
None => "searching",
Some(End::Done | End::Found) => "done",
Some(End::Stopped | End::Time | End::Limit) => "stopped",
Some(End::Failed(_)) => "failed",
}
}
/// Why a stopped search stopped: `stop`, `time` or `limit`.
pub fn stopped(&self) -> Option<&'static str> {
match &self.end {
Some(End::Stopped) => Some("stop"),
Some(End::Time) => Some("time"),
Some(End::Limit) => Some("limit"),
_ => None,
}
}
/// Why a failed search failed.
pub fn error(&self) -> Option<&str> {
match &self.end {
Some(End::Failed(e)) => Some(e),
_ => None,
}
}
}
/// Walker threads shared out among searches: all of them together run at most `cap` threads.
pub(crate) struct Pool {
live: AtomicUsize,
cap: usize,
}
impl Pool {
pub(crate) const fn new(cap: usize) -> Self {
Self { live: AtomicUsize::new(0), cap }
}
/// Reserve up to `want` threads: as many as are free, none when none is.
fn reserve(&self, want: usize) -> usize {
let mut live = self.live.load(Ordering::SeqCst);
loop {
let n = want.min(self.cap.saturating_sub(live));
if n == 0 {
return 0;
}
match self.live.compare_exchange(live, live + n, Ordering::SeqCst, Ordering::SeqCst) {
Ok(_) => return n,
Err(now) => live = now,
}
}
}
fn release(&self, n: usize) {
self.live.fetch_sub(n, Ordering::SeqCst);
}
/// The threads running now.
#[cfg(test)]
pub(crate) fn live(&self) -> usize {
self.live.load(Ordering::SeqCst)
}
}
/// The threads of every search.
static POOL: Pool = Pool::new(MAX_LIVE);
/// The walker threads for a search: the logical CPUs less one and less the renderer's threads,
/// from 2 to 8.
pub fn threads() -> usize {
let cpus = std::thread::available_parallelism().map_or(2, std::num::NonZero::get);
threads_for(cpus, usize::from(vectorcraft_render::default_threads()))
}
/// [`threads`] on `cpus` logical CPUs with `render` renderer threads.
pub(crate) fn threads_for(cpus: usize, render: usize) -> usize {
cpus.saturating_sub(1 + render).clamp(2, MAX_THREADS)
}
/// A running (or ended) search. Dropping it stops it.
pub struct Search {
shared: Arc<Shared>,
}
impl Search {
/// End the search ([`End::Stopped`]) unless it has ended. Walkers busy reading a folder or a
/// file stop after it.
pub fn stop(&self) {
let mut w = self.shared.lock();
self.shared.finish(&mut w, End::Stopped);
}
/// Where the search stands. Past its deadline it has ended ([`End::Time`]), even while a walker
/// is still waiting for a slow folder or file.
pub fn progress(&self) -> Progress {
let s = &self.shared;
let mut w = s.lock();
if w.end.is_none() && Instant::now() >= s.deadline {
s.finish(&mut w, End::Time);
}
Progress {
end: w.end.clone(),
folder: plain(w.folder.clone()),
hits: w.hits.iter().map(|(path, items)| (plain(path.clone()), items.clone())).collect(),
folders: w.folders,
files: w.files,
read: s.read.load(Ordering::Relaxed).min(s.limits.files),
skipped: w.skipped,
unreadable: w.unreadable,
seconds: if w.end.is_some() { w.seconds } else { s.started.elapsed().as_secs_f64() },
}
}
}
impl Drop for Search {
fn drop(&mut self) {
self.stop();
}
}
/// Search `folder` and its subfolders on up to `threads` walker threads (at most 8, as many as the
/// process-wide cap leaves) for the `items` a `visitor` looks for, where `rules` allow (this
/// computer's when `None`). Returns at once; the folder is checked on a walker thread.
pub fn start(
folder: PathBuf,
rules: Option<Rules>,
limits: Limits,
threads: usize,
items: usize,
visitor: Arc<dyn Visitor>,
) -> Result<Search, String> {
start_in(&POOL, folder, rules, limits, threads, items, visitor)
}
/// [`start`] with the threads of `pool`.
pub(crate) fn start_in(
pool: &'static Pool,
folder: PathBuf,
rules: Option<Rules>,
limits: Limits,
threads: usize,
items: usize,
visitor: Arc<dyn Visitor>,
) -> Result<Search, String> {
if cfg!(target_arch = "wasm32") {
return Err("searching a folder isn't available on the web".into());
}
let seconds = if limits.seconds.is_finite() { limits.seconds.clamp(0.0, 3600.0) } else { 60.0 };
let n = pool.reserve(threads.clamp(1, MAX_THREADS));
if n == 0 {
return Err("the search couldn't start: try again in a moment".into());
}
let started = Instant::now();
let shared = Arc::new(Shared {
stop: AtomicBool::new(false),
entries: AtomicU64::new(0),
read: AtomicU64::new(0),
started,
deadline: started + Duration::from_secs_f64(seconds),
limits,
items,
given: rules,
rules: OnceLock::new(),
visitor,
walk: Mutex::new(Walk { root: Some(folder), alive: n, found: vec![0; items], ..Walk::default() }),
wake: Condvar::new(),
pool,
});
let mut spawned = 0;
for _ in 0..n {
let s = shared.clone();
let thread = std::thread::Builder::new().name("vectorcraft-find".into()).spawn(move || {
let _alive = Alive(s.clone());
// A bug in the walk ends this walker and the others go on; when every walker ends this
// way, the search fails ([`Alive`]).
let _ = crate::guard::catch_panic(|| walker(&s));
});
if thread.is_ok() {
spawned += 1;
}
}
if spawned < n {
pool.release(n - spawned);
let mut w = shared.lock();
w.alive = w.alive.saturating_sub(n - spawned);
if spawned == 0 {
return Err("the search couldn't start: try again in a moment".into());
}
if w.alive == 0 && w.end.is_none() {
shared.finish(&mut w, End::Failed(INTERNAL.into()));
}
}
Ok(Search { shared })
}
/// What a search's walkers share.
struct Shared {
/// Set once the search ended: walkers stop listing and reading.
stop: AtomicBool,
entries: AtomicU64,
read: AtomicU64,
started: Instant,
deadline: Instant,
limits: Limits,
items: usize,
/// The rules given to [`start`], else this computer's, read by the first walker.
given: Option<Rules>,
rules: OnceLock<Rules>,
visitor: Arc<dyn Visitor>,
walk: Mutex<Walk>,
/// Woken when folders are queued, a walker finishes a folder, or the search ends.
wake: Condvar,
pool: &'static Pool,
}
/// The state walkers change under the lock.
#[derive(Default)]
struct Walk {
/// The picked folder, until a walker takes it to check it.
root: Option<PathBuf>,
/// A walker is checking the picked folder.
preparing: bool,
folder: PathBuf,
/// Folders waiting to be listed, with their depth below the picked one.
stack: Vec<(PathBuf, u32)>,
/// Folders being listed (and their candidates read) now.
listing: usize,
/// Walker threads still running.
alive: usize,
end: Option<End>,
seconds: f64,
hits: Vec<(PathBuf, Vec<usize>)>,
/// Files kept for each item.
found: Vec<usize>,
folders: u64,
files: u64,
skipped: u64,
unreadable: u64,
/// The home folder was queued from a system's root ([`Rules::home_below`]).
home_queued: bool,
}
impl Shared {
fn lock(&self) -> MutexGuard<'_, Walk> {
self.walk.lock().unwrap_or_else(|e| e.into_inner())
}
/// End the search as `end` unless it has ended, and wake every walker to see it.
fn finish(&self, w: &mut Walk, end: End) {
if w.end.is_none() {
w.end = Some(end);
w.seconds = self.started.elapsed().as_secs_f64();
}
self.stop.store(true, Ordering::Relaxed);
self.wake.notify_all();
}
fn end_with(&self, end: End) {
let mut w = self.lock();
self.finish(&mut w, end);
}
/// Whether to stop listing and reading: the search ended or its time is up.
fn should_stop(&self) -> bool {
self.stop.load(Ordering::Relaxed) || Instant::now() >= self.deadline
}
/// Whether the folders waiting to be listed and `more` folders found in the folder being listed
/// come to more than [`Limits::folders`], which ends the search ([`End::Limit`]).
fn too_many_folders(&self, more: usize) -> bool {
let mut w = self.lock();
let over = w.stack.len().saturating_add(more) > self.limits.folders;
if over {
self.finish(&mut w, End::Limit);
}
over
}
/// Check the picked folder, then queue it.
fn prepare(&self, root: &Path) {
let rules = self.rules.get_or_init(|| self.given.clone().unwrap_or_else(Rules::system));
let path = root.display();
let checked = match std::fs::canonicalize(root) {
Err(e) => Err(format!("{path}: {e}")),
Ok(folder) if !folder.is_dir() => Err(format!("{path} is not a folder")),
Ok(folder) => match rules.refusal(&folder) {
None => Ok(folder),
Some(Refusal::Shared) => Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")),
Some(Refusal::Apps) => Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")),
},
};
let mut w = self.lock();
match checked {
Ok(folder) => {
w.folder = folder.clone();
w.stack.push((folder, 0));
}
Err(e) => self.finish(&mut w, End::Failed(e)),
}
}
/// List one folder: queue its subfolders, then read the files [`Visitor::wants`] accepts.
fn list(&self, dir: &Path, depth: u32) {
let Some(rules) = self.rules.get() else { return };
let (mut skipped, mut unreadable, mut files) = (0, 0, 0);
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) => {
let mut w = self.lock();
// The picked folder itself: the search can't run, and says why.
if depth == 0 {
self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display())));
} else {
w.unreadable += 1;
w.folders += 1;
}
return;
}
};
let (mut folders, mut siblings, mut candidates) = (vec![], Siblings::default(), vec![]);
for (n, entry) in entries.enumerate() {
if n as u64 % CHECK_EVERY == CHECK_EVERY - 1 && (self.should_stop() || self.too_many_folders(folders.len())) {
break;
}
if self.entries.fetch_add(1, Ordering::Relaxed) >= self.limits.entries {
self.end_with(End::Limit);
break;
}
let Ok(entry) = entry else {
unreadable += 1;
break;
};
let Ok(kind) = entry.file_type() else {
unreadable += 1;
continue;
};
let name = entry.file_name();
let Some(name) = name.to_str() else {
// A name that isn't Unicode: its folder is left out, its file can't be wanted.
if kind.is_dir() {
skipped += 1;
}
continue;
};
if kind.is_dir() || kind.is_symlink() {
siblings.note(name);
}
// Links are neither followed nor read.
if kind.is_dir() {
folders.push((entry, name.to_string()));
} else if kind.is_file() {
files += 1;
// At most one file more than the search reads is kept to be read.
if (candidates.len() as u64) <= self.limits.files && self.visitor.wants(name) && self.visitor.worth_reading(&entry.path()) {
if hidden_and_offline(&entry).1 {
// Its contents are in the cloud: counted as unreadable, never read.
unreadable += 1;
} else {
candidates.push(entry);
}
}
}
}
// The folder is told once for all its folders.
let listed = rules.listed(dir, siblings);
let mut queue = vec![];
for (n, (entry, name)) in folders.into_iter().enumerate() {
if n as u64 % CHECK_EVERY == CHECK_EVERY - 1 && self.should_stop() {
break;
}
let path = entry.path();
let (hidden, offline) = hidden_and_offline(&entry);
if depth >= self.limits.depth || name.starts_with('.') || hidden || offline || rules.never_in(&listed, &name) || rules.is_refused(&path) {
skipped += 1;
continue;
}
queue.push((path, depth + 1));
}
let home = rules.home_below(&listed);
{
let mut w = self.lock();
w.files += files;
w.skipped += skipped;
w.unreadable += unreadable;
if w.end.is_none() {
if w.stack.len() + queue.len() > self.limits.folders {
self.finish(&mut w, End::Limit);
} else {
w.stack.extend(queue);
if let Some(home) = home.filter(|_| !w.home_queued) {
w.home_queued = true;
w.stack.push((home, 1));
}
self.wake.notify_all();
}
}
}
let mut unreadable = 0;
for entry in candidates {
if self.should_stop() {
break;
}
if self.read.fetch_add(1, Ordering::Relaxed) >= self.limits.files {
self.end_with(End::Limit);
break;
}
let path = entry.path();
match crate::guard::catch_panic(|| self.visitor.items(&path)) {
Ok(items) if !items.is_empty() => self.keep(path, items),
Ok(_) => {}
// A file that trips a bug: as one that can't be read, and the search goes on.
Err(_) => unreadable += 1,
}
}
let mut w = self.lock();
w.folders += 1;
w.unreadable += unreadable;
}
/// Keep a file the visitor gave `items` for, for those of its items that take more files, as
/// soon as it is read: a file read as the search ends is kept too. The search ends at the most
/// files it keeps, and once every item has a file.
fn keep(&self, path: PathBuf, mut items: Vec<usize>) {
let mut w = self.lock();
items.sort_unstable();
items.dedup();
items.retain(|i| w.found.get(*i).is_some_and(|n| *n < self.limits.per_item));
if items.is_empty() || w.hits.len() >= self.limits.hits {
return;
}
for i in &items {
if let Some(n) = w.found.get_mut(*i) {
*n += 1;
}
}
w.hits.push((path, items));
if w.hits.len() >= self.limits.hits {
self.finish(&mut w, End::Limit);
}
if self.items > 0 && w.found.iter().all(|n| *n > 0) {
self.finish(&mut w, End::Found);
}
}
}
/// What a walker does next.
enum Job {
Prepare(PathBuf),
List(PathBuf, u32),
}
/// A walker thread: check the picked folder, or list the next folder, until the search ends.
fn walker(s: &Shared) {
loop {
let job = {
let mut w = s.lock();
loop {
if w.end.is_some() {
return;
}
if Instant::now() >= s.deadline {
s.finish(&mut w, End::Time);
return;
}
if let Some(root) = w.root.take() {
w.preparing = true;
break Job::Prepare(root);
}
if let Some((dir, depth)) = w.stack.pop() {
w.listing += 1;
break Job::List(dir, depth);
}
if !w.preparing && w.listing == 0 {
s.finish(&mut w, End::Done);
return;
}
w = s.wake.wait_timeout(w, IDLE).map_or_else(|e| e.into_inner().0, |(w, _)| w);
}
};
// The guard lowers `preparing` or `listing` when the job ends, on a bug too.
let _busy = Busy(s, matches!(job, Job::Prepare(_)));
let done = crate::guard::catch_panic(|| match &job {
Job::Prepare(root) => s.prepare(root),
Job::List(dir, depth) => s.list(dir, *depth),
});
if done.is_err() {
let mut w = s.lock();
match job {
Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into())),
Job::List(..) => w.unreadable += 1,
}
}
}
}
/// A walker's job in progress: preparing (`true`) or listing a folder.
struct Busy<'a>(&'a Shared, bool);
impl Drop for Busy<'_> {
fn drop(&mut self) {
let mut w = self.0.lock();
if self.1 {
w.preparing = false;
} else {
w.listing = w.listing.saturating_sub(1);
}
self.0.wake.notify_all();
}
}
/// A running walker thread, counted out of the search and the pool when it ends.
struct Alive(Arc<Shared>);
impl Drop for Alive {
fn drop(&mut self) {
let mut w = self.0.lock();
w.alive = w.alive.saturating_sub(1);
if w.alive == 0 && w.end.is_none() {
self.0.finish(&mut w, End::Failed(INTERNAL.into()));
}
drop(w);
self.0.pool.release(1);
}
}
/// Whether a folder or file is hidden by its flags (macOS `UF_HIDDEN`; Windows hidden or system),
/// and whether its contents are in the cloud rather than on the disk (macOS `SF_DATALESS`; Windows
/// offline or recalled on access).
#[cfg(target_os = "macos")]
fn hidden_and_offline(entry: &std::fs::DirEntry) -> (bool, bool) {
use std::os::macos::fs::MetadataExt;
const UF_HIDDEN: u32 = 0x8000;
const SF_DATALESS: u32 = 0x4000_0000;
entry.metadata().map_or((false, false), |m| (m.st_flags() & UF_HIDDEN != 0, m.st_flags() & SF_DATALESS != 0))
}
#[cfg(windows)]
fn hidden_and_offline(entry: &std::fs::DirEntry) -> (bool, bool) {
use std::os::windows::fs::MetadataExt;
const HIDDEN: u32 = 0x2;
const SYSTEM: u32 = 0x4;
const OFFLINE: u32 = 0x1000;
const RECALL_ON_OPEN: u32 = 0x4_0000;
const RECALL_ON_DATA_ACCESS: u32 = 0x40_0000;
entry.metadata().map_or((false, false), |m| {
let a = m.file_attributes();
(a & (HIDDEN | SYSTEM) != 0, a & (OFFLINE | RECALL_ON_OPEN | RECALL_ON_DATA_ACCESS) != 0)
})
}
#[cfg(not(any(target_os = "macos", windows)))]
fn hidden_and_offline(_: &std::fs::DirEntry) -> (bool, bool) {
(false, false)
}
+517
View File
@@ -0,0 +1,517 @@
//! The fonts a document uses that aren't available (`text.missingFonts`), the files that provide
//! them in a folder the user picks (`text.findFontFiles`, searched on separate threads:
//! [`super::findfiles`]), and copying the files the user chooses into VectorCraft's own Fonts
//! folder, which the font scan reads (`text.addFontFiles`).
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_text::{FontDb, FontMatch, WantedFont, WantedFonts};
use super::findfiles::{self, Limits, Visitor};
use super::*;
use crate::DocState;
/// The most fonts listed, or looked for at once.
const MAX_FONTS: usize = 1_000;
/// The longest family or style name listed or given (bytes).
const MAX_NAME: usize = 256;
/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place
/// of a font and no font file provides; compared in any ASCII case. The list leaves out
/// `fangsong`, which is also the family name of a Chinese font (FangSong).
const GENERIC_FAMILIES: &[&str] = &[
"serif",
"sans-serif",
"monospace",
"cursive",
"fantasy",
"system-ui",
"ui-serif",
"ui-sans-serif",
"ui-monospace",
"ui-rounded",
"math",
"emoji",
];
/// The longest folder path given (bytes).
const MAX_PATH: usize = 4096;
/// The most files one `text.addFontFiles` copies: as many as a search keeps.
const MAX_ADD_FILES: usize = 1_000;
/// The largest font file a search reads and `text.addFontFiles` copies, and the most bytes one
/// `text.addFontFiles` copies.
pub(crate) const MAX_FONT_FILE: u64 = 256 << 20;
#[cfg(not(target_arch = "wasm32"))]
const MAX_ADD_BYTES: u64 = 1 << 30;
/// The highest number a copy's name gets (`Name 99.otf`).
#[cfg(not(target_arch = "wasm32"))]
const MAX_NUMBER: u32 = 99;
/// The extensions of the font files `text.addFontFiles` copies (in any case), besides suitcase
/// fonts.
#[cfg(not(target_arch = "wasm32"))]
const FONT_EXTENSIONS: &[&str] = &["ttf", "otf", "ttc", "otc", "woff", "woff2"];
/// Why a file wasn't copied.
const NOT_A_FILE: &str = "not a file";
#[cfg(not(target_arch = "wasm32"))]
const NOT_A_FONT: &str = "not a font file";
#[cfg(not(target_arch = "wasm32"))]
const TOO_LARGE: &str = "larger than 256 MB";
#[cfg(not(target_arch = "wasm32"))]
const TOO_MUCH: &str = "the files come to more than 1 GB: add fewer at a time";
#[cfg(not(target_arch = "wasm32"))]
const NO_NAME: &str = "every numbered name for it is taken in the Fonts folder";
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "text.missingFonts",
"Missing Fonts",
[],
None,
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols, that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
has_doc,
missing
),
cmd!(
query "text.findFontFiles",
"Find Font Files",
[],
None,
"{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
always,
find
),
cmd!(
query "text.addFontFiles",
"Add Font Files",
[],
None,
"{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: a file with the same contents is kept, and when another file has that name, the copy gets a number (Name 2.otf); then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}",
always,
add
),
]
}
/// A font a document names that isn't available as named.
#[derive(Clone, Debug, PartialEq)]
pub struct MissingFont {
pub family: String,
pub style: String,
/// [`FontMatch::Missing`] or [`FontMatch::Style`].
pub status: FontMatch,
/// The family and style of the face shown instead.
pub resolved: Option<(String, String)>,
}
/// The fonts the type of `d` uses, in its layers and its symbols, that aren't available as named
/// (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
let db = FontDb::global();
let generic = |family: &str| GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim()));
let mut used: Vec<(String, String)> = super::fonts::used_fonts(d).into_iter().map(|(family, style, _)| (family, style)).collect();
// Sorted by family and style: the versions type names of one face are neighbors.
used.dedup();
used.into_iter()
.filter(|(family, style)| !family.trim().is_empty() && !generic(family) && family.len() <= MAX_NAME && style.len() <= MAX_NAME)
.filter_map(|(family, style)| {
let resolved = db.resolve(&family, &style);
let status = resolved.as_ref().map_or(FontMatch::Missing, |(_, m)| *m);
(status != FontMatch::Exact).then(|| MissingFont {
family,
style,
status,
resolved: resolved.map(|(f, _)| (f.family.clone(), f.style.clone())),
})
})
.take(MAX_FONTS)
.collect()
}
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
/// computer's when `None`).
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
let fonts: Vec<Value> = missing_fonts(&st.doc)
.into_iter()
.map(|m| {
json!({
"family": m.family, "style": m.style, "status": m.status.as_str(),
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
})
})
.collect();
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
// is made absolute against the working folder when the document's path is relative. It is
// offered when a search may start there, as far as the rules tell without listing a folder.
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
let system;
let rules = match rules {
Some(rules) => rules,
None => {
system = findfiles::Rules::system();
&system
}
};
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
out["fontsNextToDocument"] = json!(dir);
}
}
out
}
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
Ok(missing_fonts_of(s.doc()?, s.search_rules.as_ref()))
}
/// A font a search looks for.
#[derive(Clone, Debug)]
pub(crate) struct Sought {
pub(crate) family: String,
pub(crate) style: String,
pub(crate) status: FontMatch,
}
/// The session's last search for font files (`text.findFontFiles`).
pub(crate) struct FontSearch {
/// The search's number in the session; [`stop`] takes it.
pub(crate) id: u64,
/// The folder as given.
pub(crate) folder: String,
pub(crate) fonts: Vec<Sought>,
pub(crate) search: findfiles::Search,
}
/// The files a search for fonts reads: font files, by their names ([`WantedFonts`]).
struct FontFiles(WantedFonts);
impl Visitor for FontFiles {
fn wants(&self, name: &str) -> bool {
let path = Path::new(name);
// A suitcase font (macOS) has no extension, or `.suit`.
vectorcraft_text::is_font_file(path) || cfg!(target_os = "macos") && path.extension().is_none_or(|e| e.eq_ignore_ascii_case("suit"))
}
fn worth_reading(&self, path: &Path) -> bool {
// A search reads font files and suitcase fonts of at most [`MAX_FONT_FILE`] bytes, the files
// `text.addFontFiles` copies.
(vectorcraft_text::is_font_file(path) || vectorcraft_text::is_suitcase(path))
&& std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_FONT_FILE)
}
fn items(&self, path: &Path) -> Vec<usize> {
self.0.provided_by(path)
}
}
/// `[{family, style?}]`: 1 to 1000 fonts with a family of 1 to 256 bytes and a style of at most 256
/// (Regular when left out).
fn font_list(v: &Value) -> Option<Vec<(String, String)>> {
let list = v.as_array().filter(|a| (1..=MAX_FONTS).contains(&a.len()))?;
list.iter()
.map(|f| {
let family = f.get("family")?.as_str().filter(|s| !s.trim().is_empty() && s.len() <= MAX_NAME)?;
let style = match f.get("style") {
None | Some(Value::Null) => "Regular",
Some(s) => s.as_str().filter(|s| s.len() <= MAX_NAME)?,
};
Some((family.to_string(), style.to_string()))
})
.collect()
}
fn find(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.findFontFiles";
static NEXT: AtomicU64 = AtomicU64::new(1);
if bool_or(p, "stop", false) {
if let Some(f) = &s.font_search {
f.search.stop();
}
return Ok(state(s));
}
let Some(folder) = p.get("folder").filter(|f| !f.is_null()) else { return Ok(state(s)) };
let given = match p.get("fonts") {
None | Some(Value::Null) => None,
Some(v) => Some(font_list(v).ok_or_else(|| bad(C, "each of `fonts` is {family, style?}; 1 to 1000 of them"))?),
};
let seconds = p.get("maxSeconds").and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(60.0).clamp(1.0, 600.0);
// Only checked here: the folder is read on a walker thread.
let folder = folder
.as_str()
.filter(|f| !f.is_empty() && f.len() <= MAX_PATH && !f.contains(['\0', '\u{FFFD}']) && Path::new(f).is_absolute())
.ok_or_else(|| bad(C, "`folder` must be an absolute folder path"))?
.to_string();
let fonts = match given {
Some(fonts) => fonts,
None => missing_fonts(&s.active().ok_or_else(|| bad(C, "give `fonts`, or open a document"))?.doc)
.into_iter()
.map(|m| (m.family, m.style))
.collect(),
};
let db = FontDb::global();
let (mut sought, mut wanted) = (vec![], vec![]);
for (family, style) in fonts {
let (status, installed) = match db.resolve(&family, &style) {
Some((_, FontMatch::Exact)) => continue,
Some((f, FontMatch::Style)) => (FontMatch::Style, Some(f.family.clone())),
_ => (FontMatch::Missing, None),
};
wanted.push(WantedFont { family: family.clone(), style: style.clone(), installed });
sought.push(Sought { family, style, status });
}
if sought.is_empty() {
return Err(bad(C, "no fonts to look for: they are all available"));
}
// A new search stops the last one.
s.font_search = None;
let threads = s.search_threads.unwrap_or_else(findfiles::threads);
let limits = Limits { seconds, ..Limits::default() };
let visitor = Arc::new(FontFiles(WantedFonts::new(&wanted)));
let search =
findfiles::start(PathBuf::from(&folder), s.search_rules.clone(), limits, threads, sought.len(), visitor).map_err(EngineError::Other)?;
s.font_search = Some(FontSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, fonts: sought, search });
Ok(state(s))
}
/// Where the session's last search stands (`text.findFontFiles` without `folder`).
fn state(s: &Session) -> Value {
let Some(f) = &s.font_search else { return json!({ "state": "idle", "fonts": [] }) };
let p = f.search.progress();
let mut files: Vec<Vec<String>> = vec![vec![]; f.fonts.len()];
for (path, items) in &p.hits {
for i in items {
if let Some(v) = files.get_mut(*i) {
v.push(path.to_string_lossy().into_owned());
}
}
}
let fonts: Vec<Value> = f
.fonts
.iter()
.zip(files)
.map(|(font, mut files)| {
files.sort();
json!({ "family": font.family, "style": font.style, "status": font.status.as_str(), "files": files })
})
.collect();
let folder = if p.folder.as_os_str().is_empty() { f.folder.clone() } else { p.folder.to_string_lossy().into_owned() };
let mut out = json!({
"id": f.id, "state": p.state(), "folder": folder, "fonts": fonts,
"searched": { "folders": p.folders, "files": p.files, "fontFiles": p.read },
"skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0,
});
if let Some(why) = p.stopped() {
out["stopped"] = json!(why);
}
if let Some(e) = p.error() {
out["error"] = json!(e);
}
out
}
/// Stop the session's search when it is the one numbered `id` (`text.findFontFiles`'s `id`): a
/// newer search, started by someone else, goes on.
pub fn stop(s: &mut Session, id: u64) {
if let Some(f) = s.font_search.as_ref().filter(|f| f.id == id) {
f.search.stop();
}
}
/// What copying font files into a folder did: each file copied (from, to), kept because the same
/// file is there already (from, the file there), or skipped (file, why).
#[derive(Debug, Default)]
pub(crate) struct CopyReport {
pub(crate) copied: Vec<(PathBuf, PathBuf)>,
pub(crate) kept: Vec<(PathBuf, PathBuf)>,
pub(crate) skipped: Vec<(PathBuf, String)>,
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.addFontFiles";
let mut files: Vec<PathBuf> = p
.get("files")
.and_then(Value::as_array)
.filter(|a| (1..=MAX_ADD_FILES).contains(&a.len()))
.and_then(|a| a.iter().map(|f| f.as_str().map(PathBuf::from)).collect::<Option<Vec<_>>>())
.ok_or_else(|| bad(C, "`files` must be 1 to 1000 paths of font files the last text.findFontFiles search found"))?;
files.sort();
files.dedup();
let dir = vectorcraft_text::app_font_dir()
.ok_or_else(|| EngineError::Other("VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it".into()))?;
let found: Vec<PathBuf> =
s.font_search.as_ref().map(|f| f.search.progress().hits.into_iter().map(|(path, _)| path).collect()).unwrap_or_default();
if let Some(f) = files.iter().find(|f| !found.contains(f)) {
return Err(bad(C, format!("`{}` is not a font file the last text.findFontFiles search found", f.display())));
}
super::fileio::create_dir(&dir.to_string_lossy())?;
let report = copy_into(&files, dir);
let pairs = |v: &[(PathBuf, PathBuf)]| {
v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": to.to_string_lossy() })).collect::<Vec<_>>()
};
let mut out = json!({
"folder": dir.to_string_lossy(), "copied": pairs(&report.copied), "kept": pairs(&report.kept),
"skipped": report.skipped.iter().map(|(file, why)| json!({ "file": file.to_string_lossy(), "reason": why })).collect::<Vec<_>>(),
});
if !report.copied.is_empty() || !report.kept.is_empty() {
// The fonts are cataloged and type set in them redraws, as Refresh Font List does it.
let r = super::fonts::rescan(s, &Value::Null)?;
out["families"] = r["families"].clone();
out["faces"] = r["faces"].clone();
}
Ok(out)
}
/// Where [`copy_one`] put a file: copied to, or kept as, the file in the folder.
#[cfg(not(target_arch = "wasm32"))]
enum Placed {
Copied(PathBuf),
Kept(PathBuf),
}
/// Copy `files` into `dir`, never replacing a file there: a file with the same contents is kept,
/// and when another file has the name, the copy gets the first free name from `Name 2.otf` to
/// `Name 99.otf`. At most [`MAX_FONT_FILE`] bytes a file and 1 GB in all.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn copy_into(files: &[PathBuf], dir: &Path) -> CopyReport {
let mut report = CopyReport::default();
let mut total = 0;
for from in files {
match copy_one(from, dir, &mut total) {
Ok(Placed::Copied(to)) => report.copied.push((from.clone(), to)),
Ok(Placed::Kept(to)) => report.kept.push((from.clone(), to)),
Err(why) => report.skipped.push((from.clone(), why)),
}
}
report
}
/// The web has no file system: nothing is copied.
#[cfg(target_arch = "wasm32")]
pub(crate) fn copy_into(files: &[PathBuf], _: &Path) -> CopyReport {
CopyReport { skipped: files.iter().map(|f| (f.clone(), NOT_A_FILE.to_string())).collect(), ..CopyReport::default() }
}
#[cfg(not(target_arch = "wasm32"))]
fn copy_one(from: &Path, dir: &Path, total: &mut u64) -> std::result::Result<Placed, String> {
use std::io::ErrorKind;
let meta = std::fs::symlink_metadata(from).map_err(|e| e.to_string())?;
if !meta.is_file() {
return Err(NOT_A_FILE.into());
}
let font = from.extension().and_then(|e| e.to_str()).is_some_and(|e| FONT_EXTENSIONS.iter().any(|x| e.eq_ignore_ascii_case(x)));
// A suitcase font's fonts are in its resource fork, which is copied with it, whatever its name.
let fork = match (vectorcraft_text::is_suitcase(from), font) {
(true, _) => Some(read_fork(from)?),
(false, true) => None,
(false, false) => return Err(NOT_A_FONT.into()),
};
let len = fork.as_ref().map_or(meta.len(), |f| f.len() as u64);
if len > MAX_FONT_FILE {
return Err(TOO_LARGE.into());
}
if total.saturating_add(len) > MAX_ADD_BYTES {
return Err(TOO_MUCH.into());
}
let (Some(name), Some(stem)) = (from.file_name(), from.file_stem()) else { return Err(NOT_A_FILE.into()) };
let ext = from.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
for n in 1..=MAX_NUMBER {
let to = if n == 1 { dir.join(name) } else { dir.join(format!("{} {n}{ext}", stem.to_string_lossy())) };
match std::fs::symlink_metadata(&to) {
Err(e) if e.kind() == ErrorKind::NotFound => match create_copy(from, &to, fork.as_deref()) {
Ok(()) => {
*total += len;
return Ok(Placed::Copied(to));
}
// Taken meanwhile: the next name.
Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
Err(e) => return Err(e.to_string()),
},
Ok(m) if m.is_file() && same_file(from, &to, m.len(), len, fork.as_deref()) => return Ok(Placed::Kept(to)),
_ => {}
}
}
Err(NO_NAME.into())
}
/// Create `to` as a copy of the font file `from`, or for a suitcase font, as an empty file whose
/// resource fork is `fork`; never in place of a file.
#[cfg(not(target_arch = "wasm32"))]
fn create_copy(from: &Path, to: &Path, fork: Option<&[u8]>) -> std::io::Result<()> {
let Some(fork) = fork else { return vectorcraft_format::write_new_with(to, |f| copy_capped(from, f)) };
vectorcraft_format::write_new_with(to, |_| Ok(()))?;
std::fs::write(fork_path(to), fork).inspect_err(|_| {
// Best effort: the empty file just made is all there is to clean up.
let _ = std::fs::remove_file(to);
})
}
/// Whether the file `to` (`to_len` bytes) holds what the copy of `from` (`len` bytes, or the
/// resource fork `fork` of a suitcase font) would.
#[cfg(not(target_arch = "wasm32"))]
fn same_file(from: &Path, to: &Path, to_len: u64, len: u64, fork: Option<&[u8]>) -> bool {
match fork {
None => to_len == len && same_contents(from, to),
Some(fork) => to_len == 0 && read_fork(to).is_ok_and(|f| f == fork),
}
}
/// The resource fork of the file at `path` (where macOS keeps a suitcase font's fonts), at most
/// [`MAX_FONT_FILE`] bytes.
#[cfg(not(target_arch = "wasm32"))]
fn read_fork(path: &Path) -> std::result::Result<Vec<u8>, String> {
use std::io::Read;
let mut fork = vec![];
std::fs::File::open(fork_path(path)).and_then(|f| f.take(MAX_FONT_FILE + 1).read_to_end(&mut fork)).map_err(|e| e.to_string())?;
if fork.len() as u64 > MAX_FONT_FILE {
return Err(TOO_LARGE.into());
}
Ok(fork)
}
/// Where macOS shows the resource fork of the file at `path`.
#[cfg(not(target_arch = "wasm32"))]
fn fork_path(path: &Path) -> PathBuf {
path.join("..namedfork/rsrc")
}
/// Copy the file `from` into `to`, failing past [`MAX_FONT_FILE`] bytes (a file that grew since
/// it was measured).
#[cfg(not(target_arch = "wasm32"))]
fn copy_capped(from: &Path, to: &mut std::fs::File) -> std::io::Result<()> {
use std::io::Read;
let copied = std::io::copy(&mut std::fs::File::open(from)?.take(MAX_FONT_FILE + 1), to)?;
if copied > MAX_FONT_FILE {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, TOO_LARGE));
}
Ok(())
}
/// Whether the files `a` and `b` hold the same bytes (read 64 KB at a time).
#[cfg(not(target_arch = "wasm32"))]
fn same_contents(a: &Path, b: &Path) -> bool {
let (Ok(mut a), Ok(mut b)) = (std::fs::File::open(a), std::fs::File::open(b)) else { return false };
let (mut x, mut y) = (vec![0; 1 << 16], vec![0; 1 << 16]);
loop {
match (fill(&mut a, &mut x), fill(&mut b, &mut y)) {
(Ok(0), Ok(0)) => return true,
(Ok(n), Ok(m)) if n == m && x.get(..n) == y.get(..m) => {}
_ => return false,
}
}
}
/// Read from `f` until `buf` is full or the file ends: the bytes read.
#[cfg(not(target_arch = "wasm32"))]
fn fill(f: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result<usize> {
use std::io::Read;
let mut n = 0;
while let Some(rest) = buf.get_mut(n..).filter(|r| !r.is_empty()) {
match f.read(rest)? {
0 => break,
k => n += k,
}
}
Ok(n)
}
+7 -4
View File
@@ -283,6 +283,9 @@ fn stale(d: &Document, g: &Group) -> bool {
pub(crate) struct LinkedFile {
pub path: String,
pub name: String,
/// The file actually read, which may be next to the current document after a move.
/// Nested links must be resolved against this folder, not the obsolete original path.
pub found_path: Option<String>,
/// Read from where the file is found, else the pixels the document holds when they are the
/// file's own; `None` when neither.
pub bytes: Option<Vec<u8>>,
@@ -297,10 +300,10 @@ pub(crate) fn linked_files(d: &Document, doc_path: Option<&str>) -> Vec<LinkedFi
.filter(|g| seen.insert(g.link.path.clone()))
.map(|g| {
let own = |b: &&ImageBlob| !b.is_proxy() && fileio::format_for_name(g.link.name()).is_some_and(|f| f.mime == b.mime);
let bytes = locate(&g.link, folder(doc_path))
.and_then(|mut f| f.read().ok())
.or_else(|| d.images.get(&g.key).filter(own).map(|b| b.bytes.to_vec()));
LinkedFile { path: g.link.path.clone(), name: g.link.name().to_string(), bytes }
let found = locate(&g.link, folder(doc_path));
let found_path = found.as_ref().map(|f| f.path.clone());
let bytes = found.and_then(|mut f| f.read().ok()).or_else(|| d.images.get(&g.key).filter(own).map(|b| b.bytes.to_vec()));
LinkedFile { path: g.link.path.clone(), name: g.link.name().to_string(), found_path, bytes }
})
.collect()
}
+18 -5
View File
@@ -22,7 +22,9 @@ mod effectcmd;
pub mod expand;
pub(crate) mod fileinfo;
pub mod fileio;
pub mod findfiles;
pub mod flatten;
pub mod fontfiles;
mod fonts;
pub(crate) mod freeform;
pub(crate) mod gradient;
@@ -223,6 +225,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(inline::specs());
v.extend(textstyles::specs());
v.extend(fonts::specs());
v.extend(fontfiles::specs());
v.extend(help::specs());
v.extend(threads::specs());
v.extend(textwrap::specs());
@@ -363,13 +366,23 @@ pub fn color_value(v: &Value) -> Option<Color> {
/// Objects a command targets: explicit `ids` param or the selection.
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
if let Some(ids) = ids_param(p, "ids") {
return Ok(ids);
// Objects given are used as given: a value that isn't an object id fails rather than the
// command acting on the selection instead (#785).
let object_id = |v: &Value| v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}")));
match p.get("ids").filter(|v| !v.is_null()) {
Some(Value::Array(a)) => return a.iter().map(object_id).collect(),
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
None => {}
}
if let Some(id) = id_param(p, "id") {
return Ok(vec![id]);
match p.get("id").filter(|v| !v.is_null()) {
Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]),
// A step reference a batch couldn't resolve (other strings are other ids, such as an
// effect's).
Some(Value::String(r)) if r.starts_with('$') => {
Err(EngineError::Other(format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
}
_ => Ok(s.doc()?.selection.objects.clone()),
}
Ok(s.doc()?.selection.objects.clone())
}
pub(crate) fn ok() -> Result<Value> {
+279 -83
View File
@@ -6,7 +6,10 @@
use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use std::path::Path;
use std::path::{Path, PathBuf};
use vectorcraft_doc::links::hash_bytes;
use vectorcraft_doc::{Document, LinkInfo};
use serde_json::{Value, json};
@@ -21,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package",
[],
None,
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder",
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder",
has_doc,
package
)]
@@ -50,6 +53,17 @@ fn font_ext(bytes: &[u8]) -> &'static str {
}
}
/// The name a font's file gets in the package's `Fonts` folder: the name of the file at `path`,
/// with the extension the font's `data` calls for ([`font_ext`]) when that name has no font
/// extension; without a file, `family-style` with that extension.
fn packaged_name(path: Option<&Path>, family: &str, style: &str, data: &[u8]) -> String {
match path.and_then(Path::file_name).map(|n| n.to_string_lossy().into_owned()) {
Some(name) if vectorcraft_text::is_font_file(Path::new(&name)) => name,
Some(name) => format!("{name}.{}", font_ext(data)),
None => format!("{family}-{style}.{}", font_ext(data)).replace(|c: char| !(c.is_alphanumeric() || "-_.".contains(c)), ""),
}
}
/// The options of a package.
struct Options {
copy_links: bool,
@@ -59,6 +73,238 @@ struct Options {
report: bool,
}
/// An asset that has been copied to the package, including rewritten linked documents.
#[derive(Clone)]
struct Copied {
name: String,
size: Option<u64>,
hash: Option<String>,
}
/// The parent of a packaged document and its asset both live inside the package.
/// Use paths relative to that *document*, not the package's root: a linked document
/// in Links/ must reference its own sibling image as "image.png".
fn relative_in_package(document: &str, asset: &str) -> String {
let parent = document.rsplit_once('/').map_or("", |(dir, _)| dir);
let a: Vec<&str> = parent.split('/').filter(|s| !s.is_empty()).collect();
let b: Vec<&str> = asset.split('/').filter(|s| !s.is_empty()).collect();
let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
let mut out = vec![".."; a.len() - common];
out.extend_from_slice(&b[common..]);
out.join("/")
}
fn safe_asset_name(name: &str) -> String {
let name: String =
name.chars().map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect();
let name = name.trim().trim_matches('.');
if name.is_empty() { "asset".into() } else { name.into() }
}
/// Collect dependencies depth-first so nested VectorCraft files are rewritten before
/// their parents: each parent can record the final hash of the rewritten child.
/// Cycles, excessive nesting, and unreadable children are reported, not fatal.
struct Collector<'a> {
opts: &'a Options,
root: Option<PathBuf>,
entries: Vec<Entry>,
copies: BTreeMap<String, Copied>,
visiting: BTreeMap<String, String>,
taken: HashSet<String>,
link_names: HashSet<String>,
font_files: HashSet<String>,
fonts: usize,
missing: Vec<String>,
skipped: Vec<Value>,
warnings: Vec<String>,
/// The report's lines, one section per document: the packaged one first, then each placed
/// document in the order it is reached.
sections: Vec<Vec<String>>,
}
impl<'a> Collector<'a> {
fn new(opts: &'a Options, root: Option<PathBuf>, doc_name: &str) -> Self {
let mut taken = HashSet::new();
taken.insert(doc_name.to_lowercase());
Self {
opts,
root,
entries: Vec::new(),
copies: BTreeMap::new(),
visiting: BTreeMap::new(),
taken,
link_names: HashSet::new(),
font_files: HashSet::new(),
fonts: 0,
missing: Vec::new(),
skipped: Vec::new(),
warnings: Vec::new(),
sections: Vec::new(),
}
}
fn warn(&mut self, lines: &mut Vec<String>, message: String) {
lines.push(format!("WARNING: {message}"));
self.warnings.push(message);
}
fn collect(&mut self, doc: &mut Document, source: &str, destination: &str, depth: usize) -> Result<()> {
// The caller checks cycles and depth before descending; active documents have
// a destination reserved so back-links can point at their single packaged copy.
self.visiting.insert(source.to_string(), destination.to_string());
// This document's section comes before those of the documents it places.
let section = self.sections.len();
self.sections.push(vec![]);
let mut lines = vec![];
// The packaged document's sections read as before; a placed document's name its file.
let heading = |lines: &mut Vec<String>, title: &str| {
lines.push(title.into());
if depth > 0 {
lines.push(format!("Document: {source}"));
}
};
// A file's saved path is only meaningful inside its own document.
// Different linked documents can reuse the same stale absolute path yet
// resolve it to distinct local assets. Keep a mapping per document.
let mut local = BTreeMap::<String, Copied>::new();
if self.opts.copy_links {
let mut placed = HashSet::new();
doc.visit_placed(|_, p| {
placed.insert(p.link.path.clone());
});
heading(&mut lines, "LINKED FILES");
for file in super::links::linked_files(doc, Some(source)) {
let found_path = file.found_path.as_deref().unwrap_or(&file.path);
if let Some(ancestor) = self.visiting.get(found_path).cloned() {
// The ancestor is already included (possibly the root document). A
// cyclic reference cannot have a final content hash until both files
// have been written, so leave its size/hash unspecified, not stale.
self.warn(&mut lines, format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path));
local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None });
continue;
}
if let Some(existing) = self.copies.get(found_path) {
local.insert(file.path.clone(), existing.clone());
continue;
}
let Some(mut bytes) = file.bytes else {
lines.push(format!("{}: not found ({}), not copied", file.name, file.path));
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) });
continue;
};
if self.copies.len() >= 10_000 {
return Err(bad(C, "more than 10000 linked files: package dependencies in smaller parts"));
}
let dir = if self.opts.links_folder { "Links/" } else { "" };
let name = safe_asset_name(&file.name);
let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken });
let destination_file = format!("{dir}{unique}");
if placed.contains(&file.path) {
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
} else {
match vectorcraft_format::load_file(&bytes) {
Ok(saved) => {
let preview = vectorcraft_format::preview(&bytes);
let pdf = vectorcraft_format::pdf_content(&bytes);
let compressed = bytes.starts_with(&[0x1f, 0x8b]);
let include_linked =
saved.doc.linked_only_images().iter().any(|key| saved.doc.images.get(key).is_some_and(|blob| !blob.is_proxy()));
let mut nested = saved.doc;
self.collect(&mut nested, found_path, &destination_file, depth + 1)?;
if self.opts.relink {
// Preserve auxiliary native-file content when rewriting.
let mut options = vectorcraft_format::SaveOptions::for_doc(&nested);
options.preview = preview;
options.pdf = pdf;
options.profiles = saved.profiles;
options.compress = compressed;
options.include_linked = include_linked;
match vectorcraft_format::save_with(&nested, &options) {
Ok(rewritten) => bytes = rewritten,
Err(e) => self.warn(
&mut lines,
format!(
"{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked",
file.path
),
),
}
}
}
Err(e) => self.warn(
&mut lines,
format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path),
),
}
}
}
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
self.copies.insert(found_path.to_string(), copy.clone());
local.insert(file.path.clone(), copy);
lines.push(format!("{} → {destination_file}", file.path));
self.entries.push((destination_file, bytes));
}
lines.push(String::new());
}
if self.opts.copy_fonts {
let db = vectorcraft_text::FontDb::global();
heading(&mut lines, "FONTS");
for used in super::fonts::used_fonts(doc) {
let font = super::fonts::font_label(&used);
let (family, style, version) = used;
// Found by any of its names, as the canvas draws it (in the version the type names).
let resolved = db
.resolve(&family, &style)
.filter(|(_, m)| *m != vectorcraft_text::FontMatch::Missing)
.map(|(f, m)| (db.face_version(&family, &style, version.as_deref()).unwrap_or(f), m));
// A style the family lacks is shown in its closest style, whose file is copied.
let shown = match &resolved {
Some((f, vectorcraft_text::FontMatch::Style)) => format!(" (shown in {} {})", f.family, f.style),
_ => String::new(),
};
let reason = match resolved {
Some((f, _)) if f.embeddable() => {
let data = f.file_data();
let file = packaged_name(f.path(), &f.family, &f.style, data);
// A collection, or a style shown in another face's file, is copied once.
if self.font_files.insert(file.to_lowercase()) {
self.entries.push((format!("Fonts/{file}"), data.to_vec()));
self.fonts += 1;
}
lines.push(format!("{font}{shown} → Fonts/{file}"));
continue;
}
Some(_) => "its licence doesn't allow embedding",
None => "not available on this computer",
};
lines.push(format!("{font}{shown}: {reason}, not copied"));
self.skipped.push(json!({ "font": font, "reason": reason }));
}
lines.push(String::new());
}
if self.opts.relink {
// The child files have already been rewritten; the hash and size of each
// target must reflect the *packaged* bytes rather than the original.
doc.update_links(|link: &mut LinkInfo| {
if let Some(copy) = local.get(&link.path) {
let relative = relative_in_package(destination, &copy.name);
link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(&copy.name).to_string_lossy().into_owned());
link.relative = Some(relative);
link.size = copy.size;
link.hash = copy.hash.clone();
link.modified = None;
}
});
}
if let Some(s) = self.sections.get_mut(section) {
*s = lines;
}
self.visiting.remove(source);
Ok(())
}
}
fn package(s: &mut Session, p: &Value) -> Result<Value> {
let o = Options {
copy_links: bool_or(p, "copyLinks", true),
@@ -77,94 +323,26 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
let root = folder.map(|f| Path::new(f).join(&name));
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
let st = s.doc()?;
let mut entries: Vec<Entry> = vec![];
let mut taken = HashSet::new();
let mut lines = vec![];
// The linked files.
let (mut copies, mut missing) = (BTreeMap::new(), vec![]);
if o.copy_links {
let dir = if o.links_folder { "Links/" } else { "" };
let mut names = HashSet::new();
lines.push("LINKED FILES".to_string());
for f in super::links::linked_files(&st.doc, Some(&doc_path)) {
let Some(bytes) = f.bytes else {
lines.push(format!("{}: not found ({}), not copied", f.name, f.path));
missing.push(f.name);
continue;
};
let rel = format!("{dir}{}", free_name(&f.name, if o.links_folder { &mut names } else { &mut taken }));
lines.push(format!("{} → {rel}", f.path));
copies.insert(f.path, rel.clone());
entries.push((rel, bytes));
}
lines.push(String::new());
}
// The fonts.
let (mut fonts, mut skipped) = (0, vec![]);
if o.copy_fonts {
let db = vectorcraft_text::FontDb::global();
let mut files = HashSet::new();
lines.push("FONTS".to_string());
for used in super::fonts::used_fonts(&st.doc) {
let font = super::fonts::font_label(&used);
let (family, style, version) = used;
// Found by any of its names, as the canvas draws it (in the version the type names).
let resolved = db
.resolve(&family, &style)
.filter(|(_, m)| *m != vectorcraft_text::FontMatch::Missing)
.map(|(f, m)| (db.face_version(&family, &style, version.as_deref()).unwrap_or(f), m));
// A style the family lacks is shown in its closest style, whose file is copied.
let shown = match &resolved {
Some((f, vectorcraft_text::FontMatch::Style)) => format!(" (shown in {} {})", f.family, f.style),
_ => String::new(),
};
let reason = match resolved {
Some((f, _)) if f.embeddable() => {
let data = f.file_data();
let file = f.path().and_then(Path::file_name).map_or_else(
|| format!("{}-{}.{}", f.family, f.style, font_ext(data)).replace(|c: char| !(c.is_alphanumeric() || "-_.".contains(c)), ""),
|n| n.to_string_lossy().into_owned(),
);
// A collection, or a style shown in another face's file, is copied once.
if files.insert(file.to_lowercase()) {
entries.push((format!("Fonts/{file}"), data.to_vec()));
fonts += 1;
}
lines.push(format!("{font}{shown} → Fonts/{file}"));
continue;
}
Some(_) => "its licence doesn't allow embedding",
None => "not available on this computer",
};
lines.push(format!("{font}{shown}: {reason}, not copied"));
skipped.push(json!({ "font": font, "reason": reason }));
}
lines.push(String::new());
}
// The document, linking to the copies.
let mut doc = (*st.doc).clone();
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
// Prepare original links for the destination *before* rebasing copied links.
// Recalculating afterward would overwrite the portable relative paths.
if let Some(root) = &root
&& let Some(d) = super::links::with_relative_paths(&doc, &root.join(&doc_name).to_string_lossy())
{
doc = d;
}
if o.relink && !copies.is_empty() {
let copied = |im: &vectorcraft_doc::ImageObject| im.link.as_ref().is_some_and(|l| copies.contains_key(&l.path));
doc.update_images(copied, |im| {
if let Some(l) = &mut im.link
&& let Some(rel) = copies.get(&l.path)
{
l.path = root.as_ref().map_or_else(|| rel.clone(), |r| r.join(rel).to_string_lossy().into_owned());
(l.relative, l.modified) = (Some(rel.clone()), None);
}
});
}
let mut collector = Collector::new(&o, root.clone(), &doc_name);
collector.collect(&mut doc, &doc_path, &doc_name, 0)?;
let mut entries = std::mem::take(&mut collector.entries);
entries.insert(0, (doc_name.clone(), vectorcraft_format::save_file(&doc)));
taken.insert(doc_name.to_lowercase());
let mut taken = std::mem::take(&mut collector.taken);
let lines = collector.sections.concat();
let missing = std::mem::take(&mut collector.missing);
let skipped = std::mem::take(&mut collector.skipped);
let warnings = std::mem::take(&mut collector.warnings);
let fonts = collector.fonts;
let links = collector.copies.len();
// The report.
if let Some(info) = info {
@@ -176,7 +354,7 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
}
let files: Vec<&str> = entries.iter().map(|(p, _)| p.as_str()).collect();
let mut out = json!({ "files": files, "links": copies.len(), "fonts": fonts, "missingLinks": missing, "skippedFonts": skipped });
let mut out = json!({ "files": files, "links": links, "fonts": fonts, "missingLinks": missing, "skippedFonts": skipped, "warnings": warnings });
match root {
Some(root) => {
for (rel, bytes) in &entries {
@@ -258,3 +436,21 @@ pub(crate) fn zip(files: &[(String, &[u8])]) -> Result<Vec<u8>> {
out.extend_from_slice(&0u16.to_le_bytes());
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
/// A font read from a file without a font extension (one a font manager keeps, for example) is
/// packaged with the extension its data calls for.
#[test]
fn packaged_fonts_have_a_font_extension() {
let (otf, ttc, ttf) = (b"OTTO....".as_slice(), b"ttcf....".as_slice(), b"\0\x01\0\0....".as_slice());
let name = |path: Option<&str>, data: &[u8]| packaged_name(path.map(Path::new), "Some Family", "Bold", data);
assert_eq!(name(Some("/fonts/A8F3C2"), otf), "A8F3C2.otf");
assert_eq!(name(Some("/fonts/Shared Fonts.dat"), ttc), "Shared Fonts.dat.ttc");
assert_eq!(name(Some("/fonts/Kept.TTF"), otf), "Kept.TTF");
assert_eq!(name(Some("/fonts/Kept.otc"), ttc), "Kept.otc");
assert_eq!(name(None, ttf), "SomeFamily-Bold.ttf");
}
}
+46 -6
View File
@@ -15,7 +15,7 @@
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_color::Paint;
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::rastersettings::MAX_ADD_AROUND;
use vectorcraft_doc::{
Appearance, AppearanceItem, ColorMode, Document, Effect, ImageBlob, ImageObject, Node, NodeId, NodeKind, RasterColorModel, StrokeLayer,
@@ -217,18 +217,55 @@ pub(crate) fn raster_fx(n: &Node) -> Vec<RasterFx> {
/// Remove the raster effects of `n` (its own and its fills' and strokes') and, with `members`, of
/// everything inside it.
pub(crate) fn strip_raster(n: &mut Node, members: bool) {
let keep = |e: &Effect| !effects::is_raster(&e.id);
retain_effects(n, members, &|e| !effects::is_raster(&e.id));
}
/// Keep the effects of `n` (its own and its fills' and strokes') that `keep` accepts and, with
/// `members`, of everything inside it.
fn retain_effects(n: &mut Node, members: bool, keep: &dyn Fn(&Effect) -> bool) {
n.appearance.effects.retain(keep);
for it in &mut n.appearance.items {
it.effects_mut().retain(keep);
}
if members {
for c in n.children_mut().into_iter().flatten() {
strip_raster(Arc::make_mut(c), true);
retain_effects(Arc::make_mut(c), true, keep);
}
}
}
/// The blend mode raster effect `e` paints with (`None`: not a raster effect, or one without).
fn effect_mode(e: &Effect) -> Option<BlendMode> {
effects::raster_effects(std::slice::from_ref(e)).first().and_then(RasterFx::mode)
}
/// The images of the shadows and outer glows of `n`, one per blend mode they use (in the order
/// the modes first come), each composited with its mode: rendered alone, over nothing, they can't
/// blend with the art below the object, so the image does.
fn below_images(d: &mut Document, n: &Node) -> Option<Vec<Node>> {
let mut modes: Vec<BlendMode> = vec![];
for mode in raster_fx(n).iter().filter_map(RasterFx::mode) {
if !modes.contains(&mode) {
modes.push(mode);
}
}
if modes.len() < 2 {
let mut image = raster_image(d, n, true, false)?;
image.blend = modes.first().copied().unwrap_or_default();
return Some(vec![image]);
}
modes
.into_iter()
.map(|mode| {
let mut only = n.clone();
retain_effects(&mut only, false, &|e| effect_mode(e).is_none_or(|m| m == mode));
let mut image = raster_image(d, &only, true, false)?;
image.blend = mode;
Some(image)
})
.collect()
}
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image of `d`
/// rendered at the document's raster effects resolution, without `n`'s transparency (that stays
/// on the object). With `below` (they all paint below it: shadows and outer glows) the image holds
@@ -405,15 +442,18 @@ fn walk(out: &mut Document, n: &Node, which: Which) -> Option<Node> {
return Some(walk(out, &g, which).unwrap_or(g));
}
// An image that can't be made leaves the object as it is (the writer reports its effects).
let image = raster_image(out, n, below, false)?;
let mut v = n.clone();
strip_raster(&mut v, false);
let mut m = if below {
let images = below_images(out, n)?;
let mut m = walk(out, &v, which).unwrap_or(v);
put_below(out, &mut m, image);
// Each goes in first: the last one put is the lowest.
for image in images.into_iter().rev() {
put_below(out, &mut m, image);
}
m
} else {
replace_with_image(v, image)
replace_with_image(v, raster_image(out, n, false, false)?)
};
walk_mask(out, &mut m, which);
Some(m)
+2 -2
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Library…",
["Window", "Swatch Libraries"],
None,
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl or .ase (swatch exchange) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
always,
load
),
@@ -130,7 +130,7 @@ impl LibraryFile for SwatchLibrary {
}
/// The extensions of library files [`palette_io::read_bytes`] reads.
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase"];
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"];
/// A library file the save commands write ([`Libraries::write`]).
pub(crate) enum FileData {
+9 -2
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id, start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
has_doc,
set_range_style
),
@@ -420,7 +420,14 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>
fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setRangeStyle";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
// The type object given, else the one selected (#785).
let id = match p.get("id").filter(|v| !v.is_null()) {
Some(v) => v.as_u64().map(NodeId).ok_or_else(|| bad(C, format!("`id` must be an object id, not {v}")))?,
None => match super::typecmd::text_targets(s, &json!({}), C)?.as_slice() {
[one] => *one,
_ => return Err(bad(C, "missing `id`: give one, or select one type object")),
},
};
let change = CharChange::parse(p, C, &s.doc()?.doc.setup)?;
if change.is_empty() {
return Err(bad(C, "nothing to change"));
+15 -1
View File
@@ -142,6 +142,17 @@ fn de_key<'de, T: Keyed, D: Deserializer<'de>>(d: D) -> std::result::Result<T, D
T::parse(&s).ok_or_else(|| D::Error::custom(format!("`{s}`: {}", T::KEYS)))
}
/// A size in pixels: a number, rounded to whole pixels (`300.0` is 300).
fn de_pixels<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<Option<u32>, D::Error> {
let Some(v) = Option::<f64>::deserialize(d)? else { return Ok(None) };
let px = v.round();
if !(px.is_finite() && px >= 0.0 && px <= f64::from(u32::MAX)) {
return Err(D::Error::custom(format!("{v} is not a size in pixels")));
}
// In range and whole: the cast is exact.
Ok(Some(px as u32))
}
/// The file format.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -361,8 +372,10 @@ pub struct WebSettings {
/// JPEG: embed the sRGB profile.
pub embed_profile: bool,
/// The image width in pixels (the height follows).
#[serde(deserialize_with = "de_pixels")]
pub width: Option<u32>,
/// The image height in pixels (the width follows).
#[serde(deserialize_with = "de_pixels")]
pub height: Option<u32>,
/// The image size in percent of the art's size in points.
pub percent: Option<f64>,
@@ -569,7 +582,8 @@ pub fn render(doc: &Document, s: &WebSettings) -> std::result::Result<WebRender,
let doc = doc.without_edit_modes();
let (region, scale) = region(&doc, s)?;
let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 4]);
let opts = vectorcraft_render::RenderOptions { background: page, skip_templates: true, anti_alias: s.anti_alias, ..Default::default() };
let opts =
vectorcraft_render::RenderOptions { background: page, skip_templates: true, anti_alias: s.anti_alias, precise: true, ..Default::default() };
let img = vectorcraft_render::Renderer::new().render_region_with(&doc, region, scale, &opts);
Ok(WebRender { rgba: img.to_straight(), width: img.width, height: img.height, region, scale })
}
+15
View File
@@ -9,6 +9,7 @@
pub mod cmd;
pub mod guard;
pub mod inspect;
pub mod steps;
mod tooling;
pub mod units;
@@ -861,6 +862,15 @@ pub struct Session {
pub(crate) plane_widget_press: bool,
/// A guide being dragged out of a ruler ([`Session::ruler_guide`]).
pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>,
/// The last search for the files of missing fonts (`text.findFontFiles`), until another
/// starts; dropping it stops it.
pub(crate) font_search: Option<cmd::fontfiles::FontSearch>,
/// Where folder searches may go; `None`: this computer's rules ([`cmd::findfiles::Rules`]).
/// Tests set it.
pub search_rules: Option<cmd::findfiles::Rules>,
/// The walker threads a folder search starts; `None`: [`cmd::findfiles::threads`]. Tests set
/// it.
pub search_threads: Option<usize>,
}
impl Default for Session {
@@ -913,6 +923,9 @@ impl Session {
liquify_stroke: None,
plane_widget_press: false,
ruler_guide: None,
font_search: None,
search_rules: None,
search_threads: None,
}
}
@@ -1459,6 +1472,8 @@ mod tests_flatten;
#[cfg(test)]
mod tests_focal;
#[cfg(test)]
mod tests_fontfiles;
#[cfg(test)]
mod tests_fontlist;
#[cfg(test)]
mod tests_freeform;
+138
View File
@@ -0,0 +1,138 @@
//! References between the steps of a batch (`vectorcraft-cli run`, MCP `command_batch`): a
//! parameter string that is exactly `$N` or `$N.path` takes that value from the result of step `N`
//! (0-based, in the order the steps ran), and `$last…` from the step before. A path goes into
//! objects by key and into arrays by index: `$1.id`, `$2.ids.0`, `$last.ids[0]`. `$$` at the start
//! of a string stands for one `$` and is never a reference (text such as `$$1.99`). A string that
//! looks like a reference but names no value is an error, so a step never runs with a reference
//! left in it.
use serde_json::Value;
/// Most nesting [`resolve`] walks into: deeper parameters are left as they are.
const MAX_DEPTH: usize = 64;
/// `params` with every step reference replaced from `results` (the results of the steps run so
/// far, in order); an error names a reference that resolves to nothing.
pub fn resolve(params: &Value, results: &[Value]) -> Result<Value, String> {
resolve_at(params, results, 0)
}
fn resolve_at(v: &Value, results: &[Value], depth: usize) -> Result<Value, String> {
if depth > MAX_DEPTH {
return Ok(v.clone());
}
Ok(match v {
Value::String(s) => match s.strip_prefix("$$") {
Some(rest) => Value::String(format!("${rest}")),
None => match parse(s) {
Some((step, path)) => lookup(s, step, &path, results)?,
None => v.clone(),
},
},
Value::Array(a) => Value::Array(a.iter().map(|x| resolve_at(x, results, depth + 1)).collect::<Result<_, _>>()?),
Value::Object(o) => Value::Object(o.iter().map(|(k, x)| Ok((k.clone(), resolve_at(x, results, depth + 1)?))).collect::<Result<_, String>>()?),
_ => v.clone(),
})
}
/// Which step a reference names.
#[derive(Debug, PartialEq)]
enum Step {
Index(usize),
Last,
}
/// A path segment: an object key or an array index (`.0` is either, as the value decides).
#[derive(Debug, PartialEq)]
enum Seg {
Key(String),
Index(usize),
}
/// `$N…` or `$last…` → the step and the path after it; `None` for any other string.
fn parse(s: &str) -> Option<(Step, Vec<Seg>)> {
let rest = s.strip_prefix('$')?;
let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
let (step, mut rest) = if digits > 0 {
let (n, rest) = rest.split_at_checked(digits)?;
(Step::Index(n.parse().ok()?), rest)
} else {
(Step::Last, rest.strip_prefix("last")?)
};
let mut path = vec![];
while !rest.is_empty() {
if let Some(r) = rest.strip_prefix('.') {
let len = r.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count();
let (key, r) = r.split_at_checked(len)?;
if key.is_empty() {
return None;
}
path.push(Seg::Key(key.to_string()));
rest = r;
} else {
let (n, r) = rest.strip_prefix('[')?.split_once(']')?;
path.push(Seg::Index(n.parse().ok()?));
rest = r;
}
}
Some((step, path))
}
fn lookup(text: &str, step: Step, path: &[Seg], results: &[Value]) -> Result<Value, String> {
let (i, found) = match step {
Step::Index(i) => (i, results.get(i)),
Step::Last => (results.len().saturating_sub(1), results.last()),
};
let mut cur = found.ok_or_else(|| format!("`{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $)"))?;
for seg in path {
let next = match (seg, cur) {
(Seg::Key(k), Value::Object(o)) => o.get(k),
(Seg::Key(k), Value::Array(a)) => k.parse::<usize>().ok().and_then(|n| a.get(n)),
(Seg::Index(n), Value::Array(a)) => a.get(*n),
_ => None,
};
cur = next.ok_or_else(|| format!("`{text}`: step {i}'s result has no such value (write $$ for a literal $)"))?;
}
Ok(cur.clone())
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn references_take_values_from_earlier_results() {
let results = [json!({"index": 0}), json!({"id": 2}), json!({"ids": [5, 6]})];
let p = json!({"id": "$1.id", "ids": ["$2.ids.1", "$last.ids[0]"], "nested": {"all": "$2"}, "n": 3, "flag": true});
assert_eq!(resolve(&p, &results).unwrap(), json!({"id": 2, "ids": [6, 5], "nested": {"all": {"ids": [5, 6]}}, "n": 3, "flag": true}));
}
#[test]
fn plain_strings_and_escapes_are_left_alone() {
let results = [json!({"id": 2})];
let p = json!({"text": "costs $1", "price": "$$1.99", "name": "a$1.id", "dollar": "$", "word": "$lastname"});
assert_eq!(
resolve(&p, &results).unwrap(),
json!({"text": "costs $1", "price": "$1.99", "name": "a$1.id", "dollar": "$", "word": "$lastname"})
);
}
#[test]
fn a_reference_to_nothing_is_an_error() {
let results = [json!({"id": 2})];
for bad in ["$1", "$1.id", "$0.ids", "$0.id.x", "$last.nope", "$7[0]"] {
let e = resolve(&json!({"id": bad}), &results).unwrap_err();
assert!(e.contains(bad), "{bad}: {e}");
}
assert!(resolve(&json!({"id": "$last"}), &[]).is_err(), "no step before the first");
// Huge indexes and deep nesting don't panic.
assert!(resolve(&json!("$99999999999999999999999.id"), &results).is_ok_and(|v| v == json!("$99999999999999999999999.id")));
let mut deep = json!("$0.id");
for _ in 0..200 {
deep = json!([deep]);
}
assert!(resolve(&deep, &results).is_ok());
}
}
+27
View File
@@ -853,3 +853,30 @@ fn new_layers_and_sublayers_are_numbered_together() {
let sub = s.execute("layer.newSublayer", &json!({})).unwrap();
assert_eq!(name(&s, &sub), "Layer 4", "the art doesn't count");
}
/// #785: objects given are used as given (a value that isn't an object id fails, never the
/// selection instead), and `text.setRangeStyle` works on the selected type object without `id`.
#[test]
fn given_targets_are_used_as_given_and_range_style_takes_the_selected_type() {
let mut s = session();
let first = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "first", "size": 30})).unwrap()["id"].clone();
s.execute("text.create", &json!({"x": 10, "y": 140, "text": "second", "size": 30})).unwrap();
for bad in [
json!({"id": "$1.id", "size": 60}),
json!({"id": 2.5, "size": 60}),
json!({"ids": [first.clone(), "$1.id"], "size": 60}),
json!({"ids": 3, "size": 60}),
] {
assert!(s.execute("text.setStyle", &bad).is_err(), "{bad}");
}
// Another kind of id (an effect's) is still not an object id.
let sel = s.doc().unwrap().selection.objects.clone();
assert!(s.execute("effect.apply", &json!({"id": "stylize.dropShadow"})).is_ok());
assert_eq!(s.doc().unwrap().selection.objects, sel);
// The selected type object (the second) is styled when no id is given.
let r = s.execute("text.setRangeStyle", &json!({"start": 0, "end": 3, "style": "Bold"})).unwrap();
assert_ne!(r["id"], first);
s.execute("select.all", &json!({})).unwrap();
assert!(s.execute("text.setRangeStyle", &json!({"start": 0, "end": 3, "size": 40})).is_err(), "two type objects: which one?");
assert!(s.execute("text.setRangeStyle", &json!({"id": "two", "size": 40})).is_err());
}
+62
View File
@@ -197,6 +197,68 @@ fn curvature_click_first_point_closes() {
assert_eq!(p.anchor_count(), 3);
}
/// The Curvature tool edits a path another tool drew (#798), one undo step per edit, keeping its
/// shape except where edited.
#[test]
fn curvature_edits_any_selected_path() {
let mut s = session();
let v = view();
let anchors = json!([
{"x": 100, "y": 300},
{"x": 200, "y": 200, "in": [160, 210], "out": [260, 185]},
{"x": 350, "y": 280, "in": [320, 230], "out": [380, 330]},
{"x": 450, "y": 350, "in": [420, 360], "out": [480, 300]},
{"x": 550, "y": 260, "in": [520, 290]}
]);
let id = NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.select_tool("curvature", v).unwrap();
let before = path(&s, id).subpaths[0].clone();
// Drag a point: only its two segments change.
assert_eq!(gesture(&mut s, &[(350.0, 280.0), (360.0, 320.0), (370.0, 340.0)], Mods::default()), 1);
let sp = path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors[2].p, Point::new(370.0, 340.0));
assert_eq!((sp.segment(0), sp.segment(3)), (before.segment(0), before.segment(3)));
assert_eq!(s.doc().unwrap().selection.anchors.get(&id).map(|a| a.len()), Some(1), "the point is current");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, id).subpaths[0], before);
// Alt-click toggles it, Delete removes the current point: one step each.
let (alt, steps) = (Mods { alt: true, ..Default::default() }, undo_steps(&s));
assert_eq!(gesture(&mut s, &[(200.0, 200.0)], alt), 1);
assert!(!path(&s, id).subpaths[0].anchors[1].has_out());
s.tool_key(ToolKey::Delete, Mods::default(), v).unwrap();
assert_eq!(path(&s, id).anchor_count(), 4);
assert_eq!(undo_steps(&s), steps + 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, id).subpaths[0], before);
// A press on a segment adds a point, the drag moving it: one step.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let on = kurbo::ParamCurve::eval(&before.segment(3), 0.5);
assert_eq!(gesture(&mut s, &[(on.x, on.y), (on.x, on.y + 20.0), (on.x, on.y + 30.0)], Mods::default()), 1);
let sp = path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors.len(), 6);
assert_eq!(sp.anchors[4].p, Point::new(on.x, on.y + 30.0));
assert_eq!((sp.segment(0), sp.segment(1), sp.segment(2)), (before.segment(0), before.segment(1), before.segment(2)));
s.execute("edit.undo", &json!({})).unwrap();
// A click on an end, then two more: the path goes on, its old segments unchanged.
let steps = undo_steps(&s);
for (x, y) in [(550.0, 260.0), (650.0, 300.0), (720.0, 220.0)] {
gesture(&mut s, &[(x, y)], Mods::default());
}
assert_eq!(undo_steps(&s), steps + 2, "selecting the end is no step");
let sp = path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors.len(), 7);
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
assert_eq!(sp.anchors[6].p, Point::new(720.0, 220.0));
// The other end closes it; Esc and a click away start a new path.
gesture(&mut s, &[(100.0, 300.0)], Mods::default());
assert!(path(&s, id).is_closed());
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
gesture(&mut s, &[(700.0, 550.0)], Mods::default());
assert_eq!(paths(&s).len(), 2);
}
#[test]
fn add_and_delete_anchor_tools() {
let mut s = session();
+429
View File
@@ -0,0 +1,429 @@
//! Missing fonts: listed (`text.missingFonts`), their files found in a folder on threads of their
//! own (`text.findFontFiles`), and copied into a folder without replacing a file there. These tests
//! never set VectorCraft's Fonts folder and never add a font to the process's font database:
//! `tests/font_folder.rs` does both, in a process of its own.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_text::FontMatch;
use crate::cmd::findfiles::{self, Limits, Rules, Visitor};
use crate::cmd::fontfiles::{self, FontSearch, MAX_FONT_FILE, Sought, copy_into};
use crate::{EngineError, Session};
/// A fresh temporary folder (canonical, as a search reports it).
fn folder(tag: &str) -> PathBuf {
let dir = vectorcraft_testkit::temp_dir(&format!("fontfiles-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
findfiles::plain(std::fs::canonicalize(&dir).unwrap())
}
/// A session whose folder searches may go anywhere in `root`, on two threads.
fn session_for(root: &Path) -> Session {
let mut s = Session::new();
s.search_rules = Some(Rules { user_content: vec![root.to_path_buf()], ..Rules::default() });
s.search_threads = Some(2);
s
}
/// `text.findFontFiles {}` once the search ended (10 seconds at most).
fn finished(s: &mut Session) -> Value {
let until = Instant::now() + Duration::from_secs(10);
loop {
let r = s.execute("text.findFontFiles", &json!({})).unwrap();
if r["state"] != "searching" || Instant::now() > until {
return r;
}
std::thread::sleep(Duration::from_millis(5));
}
}
/// New point type in `font` and `style` → its id.
fn text(s: &mut Session, y: f64, font: &str, style: &str) -> u64 {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Ab", "font": font, "style": style})).unwrap()["id"].as_u64().unwrap()
}
fn bundled(file: &str) -> Vec<u8> {
std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts").join(file)).unwrap()
}
#[test]
fn missing_fonts_are_listed_symbols_included() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, "No Such Font Family", "Regular");
// Type naming another version of a missing font is listed with it.
let other = vectorcraft_doc::NodeId(text(&mut s, 40.0, "No Such Font Family", "Regular"));
s.edit("version", |d, _| {
if let vectorcraft_doc::NodeKind::Text(t) = &mut d.node_mut(other).unwrap().kind {
t.runs.iter_mut().for_each(|r| r.style.font_version = Some("Version 2.000".into()));
}
Ok(())
})
.unwrap();
// A style no Source Sans 3 has, bundled or installed.
text(&mut s, 60.0, "Source Sans 3", "Black Wide");
text(&mut s, 100.0, "Source Sans 3", "Semibold");
let id = text(&mut s, 140.0, "Symbol Only Family", "Bold");
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("symbol.new", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
// CSS generic families, which no font file provides, are left out.
text(&mut s, 180.0, "sans-serif", "Regular");
text(&mut s, 220.0, "SERIF", "Bold");
let r = s.execute("text.missingFonts", &json!({})).unwrap();
let rows: Vec<(&str, &str, &str)> = r["fonts"]
.as_array()
.unwrap()
.iter()
.map(|f| (f["family"].as_str().unwrap(), f["style"].as_str().unwrap(), f["status"].as_str().unwrap()))
.collect();
assert_eq!(
rows,
[("No Such Font Family", "Regular", "missing"), ("Source Sans 3", "Black Wide", "substitute"), ("Symbol Only Family", "Bold", "missing")]
);
assert_eq!((r["count"].as_u64(), r["fonts"][1]["resolved"]["family"].as_str()), (Some(3), Some("Source Sans 3")));
assert!(r.get("fontsNextToDocument").is_none(), "an unsaved document has no folder");
let listed = s.execute("text.fonts", &json!({})).unwrap();
assert!(!listed.as_array().unwrap().iter().any(|f| f["family"] == "Symbol Only Family"), "Find Font lists the layers' type only");
assert!(listed.as_array().unwrap().iter().any(|f| f["family"] == "sans-serif" && f["status"] == "missing"), "{listed}");
assert!(matches!(Session::new().execute("text.missingFonts", &json!({})), Err(EngineError::Disabled(..))));
}
/// A font whose name is longer than 256 bytes is left out of the list, and a search for the fonts
/// listed finds the other fonts' files.
#[test]
fn an_overlong_font_name_leaves_the_other_fonts_searchable() {
let root = folder("long-name");
std::fs::write(root.join("Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
let mut s = session_for(&root);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, &"L".repeat(300), "Regular");
text(&mut s, 60.0, "Findme Sans 3", "Regular");
let listed = s.execute("text.missingFonts", &json!({})).unwrap();
let fonts: Vec<Value> = listed["fonts"].as_array().unwrap().iter().map(|f| json!({"family": f["family"], "style": f["style"]})).collect();
assert_eq!(fonts, [json!({"family": "Findme Sans 3", "style": "Regular"})]);
s.execute("text.findFontFiles", &json!({"folder": root, "fonts": fonts})).unwrap();
assert_eq!(finished(&mut s)["fonts"][0]["files"], json!([root.join("Findme.otf")]));
}
/// The Fonts folder next to a document is offered only where a search may start: not inside other
/// apps' folders, such as the attachments a mail app keeps in the home folder's Library.
#[test]
fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() {
let root = folder("next-to");
let home = root.join("Users/me");
let mut s = Session::new();
s.search_rules = Some(Rules { home: Some(home.clone()), ..Rules::default() });
for (dir, offered) in [("Library/Mail Downloads/pkg", false), ("Documents/pkg", true)] {
std::fs::create_dir_all(home.join(dir).join("Fonts")).unwrap();
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
doc.title = "doc".into();
s.add_document(doc, Some(home.join(dir).join("doc.vectorcraft").to_string_lossy().into_owned()));
text(&mut s, 20.0, "No Such Font Family", "Regular");
let r = s.execute("text.missingFonts", &json!({})).unwrap();
assert_eq!(r.get("fontsNextToDocument").is_some(), offered, "{dir}: {r}");
}
}
/// A document opened by a relative path gives the Fonts folder next to it as an absolute path,
/// which `text.findFontFiles` takes.
#[cfg(unix)]
#[test]
fn the_fonts_folder_next_to_a_document_is_an_absolute_path() {
let root = folder("relative");
std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap();
let cwd = std::env::current_dir().unwrap();
let up = "../".repeat(cwd.components().count().saturating_sub(1));
let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display());
assert!(Path::new(&relative).is_relative());
let mut s = session_for(&root);
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
doc.title = "doc".into();
s.add_document(doc, Some(relative));
text(&mut s, 20.0, "No Such Font Family", "Regular");
let next = s.execute("text.missingFonts", &json!({})).unwrap()["fontsNextToDocument"].as_str().unwrap().to_string();
assert!(Path::new(&next).is_absolute(), "{next}");
assert_eq!(std::fs::canonicalize(&next).unwrap(), root.join("pkg/Fonts"));
assert!(s.execute("text.findFontFiles", &json!({"folder": next})).is_ok());
assert_ne!(finished(&mut s)["state"], "failed");
}
#[test]
fn a_search_finds_a_missing_fonts_file_by_its_names() {
let root = folder("find");
std::fs::create_dir_all(root.join("x/y")).unwrap();
std::fs::write(root.join("x/y/Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
std::fs::write(root.join("other.ttf"), bundled("SourceSerif4-Regular.ttf")).unwrap();
std::fs::write(root.join("readme.txt"), "Findme Sans 3").unwrap();
let mut s = session_for(&root);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, "Findme Sans 3", "Regular");
// Never found: the search reads the whole folder.
text(&mut s, 60.0, "No Such Font Family", "Regular");
let r = s.execute("text.findFontFiles", &json!({"folder": root})).unwrap();
assert!(matches!(r["state"].as_str(), Some("searching" | "done")), "{r}");
let id = r["id"].clone();
let r = finished(&mut s);
assert_eq!((&r["state"], &r["id"], r.get("stopped")), (&json!("done"), &id, None), "{r}");
let found = root.join("x").join("y").join("Findme.otf").to_string_lossy().into_owned();
let findme = r["fonts"].as_array().unwrap().iter().find(|f| f["family"] == "Findme Sans 3").cloned().unwrap();
assert_eq!((findme["status"].as_str(), findme["files"].clone()), (Some("missing"), json!([found])));
assert_eq!(r["searched"]["fontFiles"], 2, "the font files are read, not the text file: {r}");
assert_eq!(r["folder"], json!(root));
// Fonts given by name: the search ends once each has a file.
let r = s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Findme Sans 3"}]})).unwrap();
assert_ne!(r["id"], id, "a new search");
let r = finished(&mut s);
assert_eq!((&r["state"], &r["fonts"][0]["files"]), (&json!("done"), &json!([found])), "{r}");
// Fonts that are available aren't looked for.
let r = s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Source Sans 3"}]}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
// Stopped by a new search, or by `stop`.
s.execute("text.findFontFiles", &json!({"folder": root})).unwrap();
let r = s.execute("text.findFontFiles", &json!({"stop": true})).unwrap();
assert!(matches!(r["state"].as_str(), Some("stopped" | "done")), "{r}");
}
#[test]
fn junk_search_params_never_fail_internally() {
let root = folder("junk");
let mut s = session_for(&root);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, "No Such Font Family", "Regular");
let internal = |r: &crate::Result<Value>| matches!(r, Err(EngineError::Internal { .. }));
let mut cases = vec![];
for v in vectorcraft_testkit::strategies::junk_values() {
cases.extend([
json!({"folder": root, "maxSeconds": v}),
json!({"folder": root, "fonts": v}),
json!({"folder": root, "stop": v}),
json!({"folder": v}),
json!({"folder": root, "fonts": [v]}),
json!({"folder": root, "fonts": [{"family": v}]}),
json!({"folder": root, "fonts": [{"family": "No Such Font Family", "style": v}]}),
]);
assert!(s.execute("text.addFontFiles", &json!({"files": v})).is_err());
assert!(s.execute("text.addFontFiles", &json!({"files": [v]})).is_err());
}
let long = "x".repeat(257);
let many: Vec<Value> = (0..1001).map(|i| json!({"family": format!("No Such Family {i}")})).collect();
cases.extend([
json!({"folder": root, "fonts": [{"family": long}]}),
json!({"folder": root, "fonts": [{"family": "x", "style": long}]}),
json!({"folder": root, "fonts": [{"family": "a\u{0}b"}]}),
json!({"folder": root, "fonts": many}),
json!({"folder": root, "fonts": many[..1000]}),
json!({"folder": "/a\u{0}b"}),
json!({"folder": "relative/folder"}),
json!({"folder": "/\u{FFFD}"}),
json!({"folder": format!("/{}", "x".repeat(4096))}),
json!({"folder": root.join("No Such Folder")}),
]);
let mut started = 0;
for p in &cases {
let r = s.execute("text.findFontFiles", p);
assert!(!internal(&r), "{p}: {r:?}");
if r.is_ok() && p.get("folder").is_some_and(|f| f.is_string()) {
started += 1;
assert_ne!(finished(&mut s)["state"], "searching", "{p}");
}
}
assert!(started > 40, "only {started} searches started");
// After a finished search, files it didn't find aren't copied.
for v in [json!(["/no/such.ttf"]), json!([root.join("readme.ttf")])] {
assert!(s.execute("text.addFontFiles", &json!({"files": v})).is_err());
}
}
/// Reads every file, and waits on reading one until its channel sends or closes.
struct Blocked(Mutex<mpsc::Receiver<()>>);
impl Visitor for Blocked {
fn wants(&self, _: &str) -> bool {
true
}
fn items(&self, _: &Path) -> Vec<usize> {
let _ = self.0.lock().unwrap().recv();
vec![]
}
}
#[test]
fn stop_ends_only_the_search_it_names() {
let root = folder("stop");
std::fs::write(root.join("a.ttf"), b"font").unwrap();
let mut s = session_for(&root);
let (tx, rx) = mpsc::channel();
let search = findfiles::start(root.clone(), s.search_rules.clone(), Limits::default(), 1, 1, Arc::new(Blocked(Mutex::new(rx)))).unwrap();
let fonts = vec![Sought { family: "A".into(), style: "Regular".into(), status: FontMatch::Missing }];
s.font_search = Some(FontSearch { id: 7, folder: root.to_string_lossy().into_owned(), fonts, search });
let until = Instant::now() + Duration::from_secs(10);
while s.execute("text.findFontFiles", &json!({})).unwrap()["searched"]["fontFiles"] != 1 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
fontfiles::stop(&mut s, 8);
assert_eq!(s.execute("text.findFontFiles", &json!({})).unwrap()["state"], "searching");
fontfiles::stop(&mut s, 7);
let r = s.execute("text.findFontFiles", &json!({})).unwrap();
assert_eq!((r["state"].as_str(), r["stopped"].as_str(), r["id"].as_u64()), (Some("stopped"), Some("stop"), Some(7)));
drop(tx);
}
#[test]
fn adding_fonts_needs_vectorcraft_s_fonts_folder() {
let mut s = Session::new();
let r = s.execute("text.addFontFiles", &json!({"files": ["/fonts/a.ttf"]}));
assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("isn't set here")), "{r:?}");
// As many files as a search keeps (one for each of 1000 fonts) can be added at once.
let files = |n: usize| json!({"files": (0..n).map(|i| format!("/fonts/{i}.ttf")).collect::<Vec<_>>()});
let r = s.execute("text.addFontFiles", &files(1000));
assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("isn't set here")), "{r:?}");
assert!(matches!(s.execute("text.addFontFiles", &files(1001)), Err(EngineError::BadParams { .. })));
}
#[test]
fn copying_never_replaces_a_file() {
let root = folder("copy");
let (src, dest) = (root.join("src"), root.join("dest"));
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dest).unwrap();
std::fs::write(src.join("a.otf"), b"new font").unwrap();
std::fs::write(dest.join("a.otf"), b"keep").unwrap();
let r = copy_into(&[src.join("a.otf")], &dest);
assert_eq!(r.copied, [(src.join("a.otf"), dest.join("a 2.otf"))]);
assert_eq!((std::fs::read(dest.join("a.otf")).unwrap(), std::fs::read(dest.join("a 2.otf")).unwrap()), (b"keep".to_vec(), b"new font".to_vec()));
// The same file again: kept, not copied a third time.
let r = copy_into(&[src.join("a.otf")], &dest);
assert_eq!((r.copied.len(), r.kept.clone()), (0, vec![(src.join("a.otf"), dest.join("a 2.otf"))]));
assert!(!dest.join("a 3.otf").exists());
// A link of that name, even one to nothing, is neither replaced nor written through.
#[cfg(unix)]
{
std::fs::write(src.join("b.otf"), b"b").unwrap();
std::os::unix::fs::symlink(root.join("nothing.otf"), dest.join("b.otf")).unwrap();
let r = copy_into(&[src.join("b.otf")], &dest);
assert_eq!(r.copied, [(src.join("b.otf"), dest.join("b 2.otf"))]);
assert!(!root.join("nothing.otf").exists());
}
// A name taken in another case: on a file system that ignores case, the copy gets a number.
std::fs::write(dest.join("C.OTF"), b"other").unwrap();
std::fs::write(src.join("c.otf"), b"c").unwrap();
let ignores_case = dest.join("c.otf").exists();
let r = copy_into(&[src.join("c.otf")], &dest);
let to = dest.join(if ignores_case { "c 2.otf" } else { "c.otf" });
assert_eq!((r.copied, std::fs::read(dest.join("C.OTF")).unwrap()), (vec![(src.join("c.otf"), to)], b"other".to_vec()));
// Every numbered name taken.
std::fs::write(src.join("d.otf"), b"d").unwrap();
std::fs::write(dest.join("d.otf"), b"other").unwrap();
for n in 2..=99 {
std::fs::write(dest.join(format!("d {n}.otf")), b"other").unwrap();
}
let r = copy_into(&[src.join("d.otf")], &dest);
assert_eq!(r.skipped, [(src.join("d.otf"), "every numbered name for it is taken in the Fonts folder".to_string())]);
// Too large (a sparse file), a folder, and a file that isn't there.
let huge = std::fs::File::create(src.join("huge.otf")).unwrap();
huge.set_len(MAX_FONT_FILE + 1).unwrap();
std::fs::create_dir_all(src.join("folder.otf")).unwrap();
let r = copy_into(&[src.join("huge.otf"), src.join("folder.otf"), src.join("none.otf")], &dest);
let reasons: Vec<&str> = r.skipped.iter().map(|(_, why)| why.as_str()).collect();
assert_eq!(reasons[..2], ["larger than 256 MB", "not a file"]);
assert!(r.copied.is_empty() && reasons.len() == 3, "{r:?}");
assert!(!dest.join("huge.otf").exists() && !dest.join("folder.otf").exists());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn only_font_files_are_copied() {
let root = folder("allowed");
let (src, dest) = (root.join("src"), root.join("dest"));
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dest).unwrap();
let names = ["notes.txt", "Script", "web.WOFF2", "font.woff"];
for name in names {
std::fs::write(src.join(name), name).unwrap();
}
let r = copy_into(&names.map(|n| src.join(n)), &dest);
let copied: Vec<PathBuf> = r.copied.iter().map(|(from, _)| from.clone()).collect();
assert_eq!(copied, [src.join("web.WOFF2"), src.join("font.woff")]);
let not_a_font = |n: &str| (src.join(n), "not a font file".to_string());
assert_eq!(r.skipped, [not_a_font("notes.txt"), not_a_font("Script")]);
assert!(!dest.join("notes.txt").exists() && !dest.join("Script").exists());
let _ = std::fs::remove_dir_all(&root);
}
/// A search reads no font file larger than Add Fonts copies, and finds a smaller copy of the font.
#[test]
fn a_search_skips_font_files_too_large_to_add() {
let root = folder("too-large");
let (big, small) = (root.join("big").join("Sizeme.otf"), root.join("small").join("Sizeme.otf"));
let font = vectorcraft_testkit::fonts::renamed("Sizeme Sans 3");
for path in [&big, &small] {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, &font).unwrap();
}
// One byte past the limit, without writing it: the file system leaves the rest unallocated.
std::fs::File::options().write(true).open(&big).unwrap().set_len(MAX_FONT_FILE + 1).unwrap();
let mut s = session_for(&root);
// A font no file has keeps the search going through every folder.
s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Sizeme Sans 3"}, {"family": "No Such Sans"}]})).unwrap();
let r = finished(&mut s);
assert_eq!(r["fonts"][0]["files"], json!([small]), "{r}");
let _ = std::fs::remove_dir_all(&root);
}
/// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its
/// resource fork, which only macOS keeps. A search finds it, and Add Fonts copies it with its fork.
#[cfg(target_os = "macos")]
#[test]
fn suitcase_fonts_are_found_and_copied_with_their_fork() {
use vectorcraft_testkit::fonts::{renamed, suitcase_fork};
let root = folder("suitcase");
let (src, dest) = (root.join("src"), root.join("dest"));
std::fs::create_dir_all(src.join("sub")).unwrap();
std::fs::create_dir_all(&dest).unwrap();
let suitcase = |path: &Path, family: &str| {
let fork = suitcase_fork(&[renamed(family)]);
std::fs::write(path, b"").unwrap();
std::fs::write(path.join("..namedfork/rsrc"), &fork).unwrap();
fork
};
let found = src.join("sub/Suitme");
let fork = suitcase(&found, "Suitme Sans 3");
// A file without an extension that isn't a suitcase is checked and left out.
std::fs::write(src.join("README"), b"text").unwrap();
let mut s = session_for(&root);
s.execute("text.findFontFiles", &json!({"folder": src, "fonts": [{"family": "Suitme Sans 3"}]})).unwrap();
let r = finished(&mut s);
assert_eq!(r["fonts"][0]["files"], json!([found]), "{r}");
// A suitcase with the `.suit` extension is found too, and a `.suit` file that isn't one is left out.
let suit = src.join("Suited.SUIT");
suitcase(&suit, "Suited Sans 3");
std::fs::write(src.join("Plain.suit"), b"text").unwrap();
// A font no file has keeps the search going through every folder.
s.execute("text.findFontFiles", &json!({"folder": src, "fonts": [{"family": "Suited Sans 3"}, {"family": "No Such Sans"}]})).unwrap();
let r = finished(&mut s);
assert_eq!((r["fonts"][0]["files"].clone(), r["searched"]["fontFiles"].as_u64()), (json!([suit]), Some(2)), "{r}");
let r = copy_into(std::slice::from_ref(&found), &dest);
assert_eq!(r.copied, [(found.clone(), dest.join("Suitme"))]);
assert!(vectorcraft_text::is_suitcase(&dest.join("Suitme")));
assert_eq!(std::fs::read(dest.join("Suitme/..namedfork/rsrc")).unwrap(), fork);
// The same suitcase again is kept; another of that name gets a number.
assert_eq!(copy_into(std::slice::from_ref(&found), &dest).kept, [(found.clone(), dest.join("Suitme"))]);
let other = src.join("Suitme");
suitcase(&other, "Other Sans 33");
assert_eq!(copy_into(std::slice::from_ref(&other), &dest).copied, [(other.clone(), dest.join("Suitme 2"))]);
// A suitcase named like a font file keeps its fork too.
let named = src.join("Suitext.ttf");
let named_fork = suitcase(&named, "Suitext Sans3");
assert_eq!(copy_into(std::slice::from_ref(&named), &dest).copied, [(named.clone(), dest.join("Suitext.ttf"))]);
assert_eq!(std::fs::read(dest.join("Suitext.ttf/..namedfork/rsrc")).unwrap(), named_fork);
// The font scan reads the copies.
let db = vectorcraft_text::FontDb::with_font_dirs(vec![dest.clone()]);
assert_eq!((db.styles("Suitme Sans 3"), db.styles("Other Sans 33")), (vec!["Regular".to_string()], vec!["Regular".to_string()]));
let _ = std::fs::remove_dir_all(&root);
}
+308
View File
@@ -223,3 +223,311 @@ fn the_document_info_report_has_every_category() {
let face = vectorcraft_text::FontDb::global().face("Source Sans 3", "Regular").unwrap();
assert!(face.embeddable() && face.path().is_none());
}
/// A professional handoff: the poster links to a reusable illustration, whose
/// own artwork links to a raster asset. Both dependency levels must travel.
fn poster_with_placed_document(dir: &Folder) -> Session {
let image = dir.file("art/photo.png");
write(&image, &png(600, 300, RED));
let mut part = session();
place(&mut part, &image);
let part_path = dir.file("art/part.vectorcraft");
save(&mut part, &part_path);
let mut poster = session();
let placed = run(&mut poster, "file.place", json!({ "path": part_path, "link": true }));
assert_eq!(placed["linked"], true, "{placed}");
save(&mut poster, &dir.file("poster.vectorcraft"));
poster
}
/// Every link must point to a packaged copy, including links inside a linked
/// VectorCraft file. Validate after original assets have been removed.
fn verify_portable_nested_package(folder: &std::path::Path) {
let main = folder.join("poster.vectorcraft");
let part = folder.join("Links/part.vectorcraft");
let image = folder.join("Links/photo.png");
assert!(main.is_file() && part.is_file() && image.is_file());
let mut parent = session();
let opened = open(&mut parent, &main.to_string_lossy());
assert_eq!(opened["missingLinks"], json!([]), "main package has broken links: {opened}");
let mut targets = Vec::new();
parent.doc().unwrap().doc.visit_placed(|_, p| targets.push(p.link.clone()));
assert_eq!(targets.len(), 1);
let link = &targets[0];
assert_eq!(link.relative.as_deref(), Some("Links/part.vectorcraft"));
let packaged_part = std::fs::read(&part).unwrap();
let expected_hash = vectorcraft_doc::links::hash_bytes(&packaged_part);
assert_eq!(link.hash.as_deref(), Some(expected_hash.as_str()));
let mut nested = session();
let opened = open(&mut nested, &part.to_string_lossy());
assert_eq!(opened["missingLinks"], json!([]), "nested document has broken links: {opened}");
let mut img_links = Vec::new();
nested.doc().unwrap().doc.visit_images(|_, im| img_links.extend(im.link.clone()));
assert_eq!(img_links.len(), 1);
assert_eq!(img_links[0].relative.as_deref(), Some("photo.png"));
assert_eq!(std::fs::read(&image).unwrap(), png(600, 300, RED));
}
#[test]
fn package_recursively_relinks_placed_documents_and_their_images() {
let dir = Folder::new("package-placed");
let mut s = poster_with_placed_document(&dir);
let out = dir.file("delivery");
let result = run(&mut s, "file.package", json!({ "folder": out }));
assert_eq!((result["links"].as_u64(), result["missingLinks"].clone()), (Some(2), json!([])), "{result}");
let folder = dir.0.join("delivery/poster Folder");
// The package must work on a second computer without the source tree.
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
verify_portable_nested_package(&folder);
}
#[test]
fn zipped_package_recursively_relinks_without_absolute_creator_paths() {
let dir = Folder::new("package-placed-zip");
let mut s = poster_with_placed_document(&dir);
let result = run(&mut s, "file.package", json!({}));
assert_eq!(result["links"], 2, "{result}");
let bytes = vectorcraft_format::base64_decode(result["dataBase64"].as_str().unwrap()).unwrap();
let archive = unzip(&bytes);
let extraction = dir.file("extracted");
for (name, bytes) in archive {
write(&format!("{extraction}/{name}"), &bytes);
}
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
verify_portable_nested_package(&dir.0.join("extracted/poster Folder"));
}
#[test]
fn package_keeps_distinct_linked_documents_with_colliding_file_names() {
let dir = Folder::new("package-collisions");
let mut poster = session();
for (number, color) in [(1, RED), (2, BLUE)] {
let image = dir.file(&format!("art{number}/picture.png"));
write(&image, &png(300, 300, color));
let mut part = session();
place(&mut part, &image);
let name = dir.file(&format!("art{number}/part.vectorcraft"));
save(&mut part, &name);
run(&mut poster, "file.place", json!({ "path": name, "link": true }));
}
save(&mut poster, &dir.file("poster.vectorcraft"));
let result = run(&mut poster, "file.package", json!({ "folder": dir.file("delivery") }));
assert_eq!(result["links"], 4, "{result}");
assert_eq!(result["missingLinks"], json!([]));
let folder = dir.0.join("delivery/poster Folder");
let packaged: Vec<_> =
result["files"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|name| name.ends_with(".vectorcraft")).collect();
assert_eq!(packaged.len(), 3, "both nested documents must be retained: {packaged:?}");
std::fs::remove_dir_all(dir.0.join("art1")).unwrap();
std::fs::remove_dir_all(dir.0.join("art2")).unwrap();
let mut check = session();
assert_eq!(open(&mut check, &folder.join("poster.vectorcraft").to_string_lossy())["missingLinks"], json!([]));
for name in packaged.into_iter().filter(|n| n.starts_with("Links/")) {
let mut inner = session();
let result = open(&mut inner, &folder.join(name).to_string_lossy());
assert_eq!(result["missingLinks"], json!([]), "{name}: {result}");
}
}
#[test]
fn package_finds_nested_assets_after_the_source_tree_moves() {
let dir = Folder::new("package-moved-nested");
let _original = poster_with_placed_document(&dir);
let moved = dir.0.join("moved");
std::fs::create_dir_all(&moved).unwrap();
std::fs::rename(dir.0.join("art"), moved.join("art")).unwrap();
std::fs::rename(dir.0.join("poster.vectorcraft"), moved.join("poster.vectorcraft")).unwrap();
// The file paths embedded in both documents still point to the old location.
// Opening the parent repairs its direct link, but the child must resolve
// the image from the folder where it was actually found.
let mut opened = session();
open(&mut opened, &moved.join("poster.vectorcraft").to_string_lossy());
let result = run(&mut opened, "file.package", json!({ "folder": dir.file("delivery") }));
assert_eq!(result["missingLinks"], json!([]), "moved file's nested link wasn't found: {result}");
std::fs::remove_dir_all(moved.join("art")).unwrap();
verify_portable_nested_package(&dir.0.join("delivery/poster Folder"));
}
#[test]
fn identical_stale_paths_in_different_nested_documents_keep_separate_assets() {
let dir = Folder::new("package-stale-paths");
let mut poster = session();
for (number, color) in [(1, RED), (2, BLUE)] {
let image = dir.file(&format!("art{number}/photo.png"));
write(&image, &png(300, 300, color));
let mut part = session();
place(&mut part, &image);
let name = dir.file(&format!("art{number}/part.vectorcraft"));
save(&mut part, &name);
// Two otherwise independent linked documents have the *same* obsolete
// absolute image path. Their relative paths identify different files.
let mut saved = vectorcraft_format::load(&std::fs::read(&name).unwrap()).unwrap();
saved.update_links(|link| {
link.path = "/old-computer/illustrations/photo.png".into();
link.relative = Some("photo.png".into());
});
write(&name, &vectorcraft_format::save_file(&saved));
run(&mut poster, "file.place", json!({ "path": name, "link": true }));
}
save(&mut poster, &dir.file("poster.vectorcraft"));
let result = run(&mut poster, "file.package", json!({ "folder": dir.file("delivery") }));
assert_eq!(result["links"], 4, "both images and both documents must be copied: {result}");
assert_eq!(result["missingLinks"], json!([]), "{result}");
let folder = dir.0.join("delivery/poster Folder");
std::fs::remove_dir_all(dir.0.join("art1")).unwrap();
std::fs::remove_dir_all(dir.0.join("art2")).unwrap();
let mut actual = Vec::new();
for filename in result["files"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|name| name.ends_with(".png")) {
actual.push(std::fs::read(folder.join(filename)).unwrap());
}
assert_eq!(actual.len(), 2, "stale source paths must not cause asset deduplication");
assert_ne!(actual[0], actual[1], "different original illustrations must keep different pixels");
for filename in result["files"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.filter(|name| name.starts_with("Links/") && name.ends_with(".vectorcraft"))
{
let mut nested = session();
let opened = open(&mut nested, &folder.join(filename).to_string_lossy());
assert_eq!(opened["missingLinks"], json!([]), "{filename}: {opened}");
}
}
#[test]
fn packaging_nested_files_preserves_embedded_preview_pdf_and_compression() {
let dir = Folder::new("package-native-extras");
let mut parent = poster_with_placed_document(&dir);
let source = dir.file("art/part.vectorcraft");
let original = std::fs::read(&source).unwrap();
let doc = vectorcraft_format::load(&original).unwrap();
let preview = png(8, 8, BLUE);
let pdf = b"%PDF-1.7\n%Embedded client preview\n".to_vec();
let mut opts = vectorcraft_format::SaveOptions::for_doc(&doc);
opts.preview = Some(preview.clone());
opts.pdf = Some(pdf.clone());
opts.compress = true;
write(&source, &vectorcraft_format::save_with(&doc, &opts).unwrap());
let result = run(&mut parent, "file.package", json!({ "folder": dir.file("delivery") }));
assert_eq!(result["missingLinks"], json!([]), "{result}");
let packaged = std::fs::read(dir.0.join("delivery/poster Folder/Links/part.vectorcraft")).unwrap();
assert!(packaged.starts_with(&[0x1f, 0x8b]), "compression must be preserved");
assert_eq!(vectorcraft_format::preview(&packaged), Some(preview));
assert_eq!(vectorcraft_format::pdf_content(&packaged), Some(pdf));
let nested = vectorcraft_format::load(&packaged).unwrap();
let mut images = Vec::new();
nested.visit_images(|_, image| images.push(image.link.clone()));
assert_eq!(images.len(), 1);
assert_eq!(images[0].as_ref().unwrap().relative.as_deref(), Some("photo.png"));
}
/// The report keeps the packaged document's sections as they were, then gives each placed
/// document's own, headed by its file, instead of nesting them inside the parent's list.
#[test]
fn the_report_lists_a_placed_documents_links_in_a_section_of_its_own() {
let dir = Folder::new("package-report-sections");
let mut parent = poster_with_placed_document(&dir);
run(&mut parent, "file.package", json!({ "folder": dir.file("delivery"), "copyFonts": false }));
let report = std::fs::read_to_string(dir.0.join("delivery/poster Folder/poster Report.txt")).unwrap();
let lines: Vec<&str> = report.lines().collect();
let sections: Vec<usize> = lines.iter().enumerate().filter(|(_, l)| **l == "LINKED FILES").map(|(i, _)| i).collect();
let [poster, part] = sections[..] else { panic!("two link sections: {report}") };
assert!(lines[poster + 1].ends_with("→ Links/part.vectorcraft"), "the packaged document's section as before: {report}");
assert!(lines[part + 1].starts_with("Document: ") && lines[part + 1].ends_with("part.vectorcraft"), "{report}");
assert!(lines[part + 2].ends_with("→ Links/photo.png"), "{report}");
}
/// A damaged or newer-format linked native file is still an asset worth delivering.
/// Package must preserve the exact bytes instead of failing the entire handoff.
#[test]
fn unreadable_placed_document_is_copied_unchanged_with_warning() {
let dir = Folder::new("package-unreadable-placed");
let mut parent = poster_with_placed_document(&dir);
let damaged = dir.file("art/part.vectorcraft");
let bytes = b"not a parseable VectorCraft file".to_vec();
write(&damaged, &bytes);
let result = run(&mut parent, "file.package", json!({ "folder": dir.file("delivery") }));
assert_eq!(result["links"], 1, "{result}");
assert_eq!(result["missingLinks"], json!([]), "{result}");
let warnings = result["warnings"].as_array().unwrap();
assert_eq!(warnings.len(), 1, "{result}");
assert!(warnings[0].as_str().unwrap().contains("unreadable linked document"), "{result}");
let packaged = dir.0.join("delivery/poster Folder");
assert_eq!(std::fs::read(packaged.join("Links/part.vectorcraft")).unwrap(), bytes);
let report = std::fs::read_to_string(packaged.join("poster Report.txt")).unwrap();
assert!(report.lines().any(|line| line == "LINKED FILES"), "{report}");
assert!(report.contains("copied unchanged") && report.contains("its own links were not collected"), "{report}");
}
#[test]
fn circular_placed_links_copy_each_document_once_and_warn() {
let dir = Folder::new("package-placed-cycle");
let source = dir.file("root.vectorcraft");
let child_path = dir.file("child.vectorcraft");
let mut root = session();
save(&mut root, &source);
let mut child = session();
run(&mut child, "file.place", json!({ "path": source, "link": true }));
save(&mut child, &child_path);
run(&mut root, "file.place", json!({ "path": child_path, "link": true }));
save(&mut root, &source);
let result = run(&mut root, "file.package", json!({ "folder": dir.file("delivery") }));
assert_eq!(result["links"], 1, "the root must not be copied a second time: {result}");
assert_eq!(result["missingLinks"], json!([]), "{result}");
assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("circular placed-document link")), "{result}");
let packaged = dir.0.join("delivery/root Folder");
let root_doc = vectorcraft_format::load(&std::fs::read(packaged.join("root.vectorcraft")).unwrap()).unwrap();
let child_doc = vectorcraft_format::load(&std::fs::read(packaged.join("Links/child.vectorcraft")).unwrap()).unwrap();
let mut direct = Vec::new();
root_doc.visit_placed(|_, p| direct.push(p.link.relative.clone()));
assert_eq!(direct, [Some("Links/child.vectorcraft".into())]);
let mut back = Vec::new();
child_doc.visit_placed(|_, p| {
back.push((p.link.relative.clone(), p.link.hash.clone(), p.link.size));
});
assert_eq!(back, [(Some("../root.vectorcraft".into()), None, None)]);
let report = std::fs::read_to_string(packaged.join("root Report.txt")).unwrap();
assert!(report.lines().any(|line| line == "LINKED FILES"), "{report}");
assert!(report.contains("stopped following the cycle"), "{report}");
}
#[test]
fn nesting_limit_copies_boundary_file_and_reports_uncollected_links() {
let dir = Folder::new("package-placed-depth-limit");
let mut deepest = session();
let mut next = dir.file("leaf.vectorcraft");
save(&mut deepest, &next);
let mut root = None;
for depth in (0..=vectorcraft_doc::placed_document::MAX_DEPTH).rev() {
let mut current = session();
run(&mut current, "file.place", json!({ "path": next, "link": true }));
let name = dir.file(&format!("level{depth}.vectorcraft"));
save(&mut current, &name);
next = name;
if depth == 0 {
root = Some(current);
}
}
let mut root = root.unwrap();
let result = run(&mut root, "file.package", json!({ "folder": dir.file("delivery") }));
let expected_links = vectorcraft_doc::placed_document::MAX_DEPTH + 1;
assert_eq!(result["links"].as_u64(), Some(expected_links as u64), "{result}");
assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("nesting limit reached")), "{result}");
let folder = dir.0.join("delivery/level0 Folder");
let packaged = std::fs::read(folder.join("Links/leaf.vectorcraft")).unwrap();
assert_eq!(packaged, std::fs::read(dir.file("leaf.vectorcraft")).unwrap());
let report = std::fs::read_to_string(folder.join("level0 Report.txt")).unwrap();
assert!(report.contains("nesting limit reached"), "{report}");
}
+32
View File
@@ -150,3 +150,35 @@ fn live_objects_and_single_fills_and_strokes_keep_their_raster_effects() {
assert_eq!(pieces, 2, "item {item}: one piece per fill and stroke");
}
}
#[test]
fn shadows_and_glows_keep_their_blend_modes() {
// #827: a red Screen glow over grey can't darken it, as Normal would.
let glow = Effect {
id: "stylize.outerGlow".into(),
params: json!({"mode": "screen", "color": "#ff0000", "opacity": 100.0, "blur": 20.0}),
visible: true,
};
let mut d = Document::new(200.0, 200.0);
let back = rect(&mut d, Rect::new(0.0, 0.0, 200.0, 200.0), Color::rgb(0.5, 0.5, 0.5));
add(&mut d, back);
let dot = rect(&mut d, Rect::new(70.0, 70.0, 130.0, 130.0), Color::rgb(0.12, 0.12, 0.12));
add(&mut d, with(dot, glow.clone()));
assert_written("screen glow", &d);
let r = crate::cmd::rasterfx::export_pdf_with_report(&d, &Default::default()).unwrap();
let back = render(&vectorcraft_pdf::import(&r.bytes).unwrap());
for x in [133, 138, 145] {
let i = (100 * back.width as usize + x) * 4;
let (red, green, blue) = (back.pixels[i], back.pixels[i + 1], back.pixels[i + 2]);
assert!(red > green && green >= 124 && blue >= 124, "x {x}: {:?}", (red, green, blue));
}
// A Multiply shadow and the Screen glow: an image each, composited with its mode.
let mut d = Document::new(200.0, 200.0);
let dot = rect(&mut d, Rect::new(70.0, 70.0, 130.0, 130.0), Color::rgb(0.12, 0.12, 0.12));
add(&mut d, with(with(dot, shadow()), glow));
let flat = crate::flatten_raster_effects(&d).unwrap();
let modes: Vec<_> =
flat.layers[0].children().unwrap()[0].children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Image(_))).map(|c| c.blend).collect();
assert_eq!(modes, [vectorcraft_color::BlendMode::Multiply, vectorcraft_color::BlendMode::Screen]);
}
+7
View File
@@ -285,9 +285,16 @@ fn image_size_region_and_metadata() {
assert_eq!(size(&mut s, json!({"width": 80})), (80, 60));
assert_eq!(size(&mut s, json!({"height": 15})), (20, 15));
assert_eq!(size(&mut s, json!({"percent": 150})), (60, 45));
// The dialog's fields send decimal numbers: rounded to whole pixels.
assert_eq!(size(&mut s, json!({"width": 80.0})), (80, 60));
assert_eq!(size(&mut s, json!({"height": 14.6})), (20, 15));
for bad in [
json!({"percent": 0}),
json!({"width": 0}),
json!({"width": 0.2}),
json!({"width": -5}),
json!({"height": 1e300}),
json!({"height": "tall"}),
json!({"format": "bmp"}),
json!({"colors": "many"}),
json!({"matte": "plaid"}),
+5
View File
@@ -215,6 +215,11 @@ fn structured_junk() {
("path.freehand", json!({"points": [[0, 0], [0, 0], [0, 0], [0, 0]]})),
("path.freehand", json!({"points": [[1e308, 1e308], [-1e308, 0]], "fidelity": 0})),
("path.curvature", json!({"points": [{"x": 0, "y": 0}]})),
("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 1000, "x": 0, "y": 0})),
("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 0, "x": 1e308, "y": -1e308})),
("path.curvatureEdit", json!({"id": 2, "subpath": 7, "op": "extend", "x": 1e308, "y": -1e308, "from": "smooth"})),
("path.curvatureEdit", json!({"id": 2, "op": "insert", "segment": 99, "t": -5, "x": 1})),
("path.curvatureEdit", json!({"id": 2, "op": "close", "end": "start", "from": "corner"})),
("path.knife", json!({"points": [[0, 0], [1e9, 1e9]]})),
("path.eraseRegion", json!({"points": [[100, 80]], "size": 0})),
("path.eraseRegion", json!({"points": [[100, 80], [101, 80]], "size": 1e9})),
+77
View File
@@ -0,0 +1,77 @@
//! VectorCraft's own Fonts folder: a missing font's file, found in a folder, is copied into it
//! without replacing a file there, and type set in the font redraws in it. One test in its own
//! process, so the process-wide font database and Fonts folder start fresh, as when the app starts.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::findfiles::{Rules, plain};
/// `text.findFontFiles {}` once the search ended (10 seconds at most).
fn finished(s: &mut Session) -> Value {
let until = Instant::now() + Duration::from_secs(10);
loop {
let r = s.execute("text.findFontFiles", &json!({})).unwrap();
if r["state"] != "searching" || Instant::now() > until {
return r;
}
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() {
let root = vectorcraft_testkit::temp_dir("font-folder");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("Downloads/Deep")).unwrap();
let root = plain(std::fs::canonicalize(&root).unwrap());
let fonts = root.join("App Fonts");
vectorcraft_text::set_app_font_dir(fonts.clone());
assert!(vectorcraft_text::system_font_dirs().contains(&fonts));
let file = root.join("Downloads").join("Deep").join("Findme.otf");
std::fs::write(&file, vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
let serif = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSerif4-Regular.ttf");
std::fs::copy(serif, root.join("other.ttf")).unwrap();
let mut s = Session::new();
s.search_rules = Some(Rules { user_content: vec![root.clone()], ..Rules::default() });
s.search_threads = Some(2);
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Findme", "font": "Findme Sans 3"})).unwrap();
let r = s.execute("text.missingFonts", &json!({})).unwrap();
assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["status"].as_str()), (Some("Findme Sans 3"), Some("missing")), "{r}");
s.doc_mut().unwrap().mark_saved();
let revision = s.doc().unwrap().revision;
s.execute("text.findFontFiles", &json!({"folder": root})).unwrap();
let r = finished(&mut s);
assert_eq!((&r["state"], &r["fonts"][0]["files"]), (&json!("done"), &json!([file])), "{r}");
// A file of that name is in the Fonts folder already: it stays, and the copy takes a number.
std::fs::create_dir_all(&fonts).unwrap();
std::fs::write(fonts.join("Findme.otf"), b"keep").unwrap();
let r = s.execute("text.addFontFiles", &json!({"files": [file]})).unwrap();
assert_eq!(r["copied"], json!([{"from": file, "to": fonts.join("Findme 2.otf")}]), "{r}");
assert!(r["faces"].as_u64().is_some_and(|n| n > 0) && r["families"].as_u64().is_some(), "{r}");
assert_eq!(std::fs::read(fonts.join("Findme.otf")).unwrap(), b"keep");
// The type is set in the font now, without editing the document.
let listed = s.execute("text.fonts", &json!({})).unwrap();
let findme = listed.as_array().unwrap().iter().find(|f| f["family"] == "Findme Sans 3").cloned().unwrap();
assert_eq!((findme["status"].as_str(), findme["resolved"]["family"].as_str()), (Some("exact"), Some("Findme Sans 3")), "{findme}");
let st = s.doc().unwrap();
assert!(st.revision > revision && !st.is_dirty());
assert_eq!(s.execute("text.missingFonts", &json!({})).unwrap()["count"], 0);
// The same file again is kept, not copied a third time.
let r = s.execute("text.addFontFiles", &json!({"files": [file]})).unwrap();
assert_eq!((r["copied"].clone(), r["kept"].clone()), (json!([]), json!([{"from": file, "to": fonts.join("Findme 2.otf")}])), "{r}");
assert!(!fonts.join("Findme 3.otf").exists());
// Only files the last search found are copied.
let r = s.execute("text.addFontFiles", &json!({"files": [root.join("other.ttf")]}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the last text.findFontFiles search")), "{r:?}");
let _ = std::fs::remove_dir_all(&root);
}
+194 -2
View File
@@ -6,7 +6,9 @@
//! of every kind with random contents) opened, placed or pasted, nor EPS and PostScript files
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions).
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the
//! font files a folder search reads (damaged fonts, collections whose headers give any count of
//! faces).
//!
//! `PROPTEST_CASES=20000 cargo test -p vectorcraft-engine --test import_fuzz` runs a deeper search.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
@@ -1689,12 +1691,69 @@ fn text_document_text() -> String {
.to_string()
}
/// The text document of area type threaded through two frames and of type on a path, as an
/// editing copy keeps it (frames on the canvas, y down).
fn frames_document_text() -> String {
let area = |x0: f64, x1: f64| {
let (y0, y1) = (8201.5, 8221.5);
let corners = [(x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)];
let segments: Vec<String> = corners.windows(2).map(|w| format!("{0} {1} {0} {1} {2} {3} {2} {3}", w[0].0, w[0].1, w[1].0, w[1].1)).collect();
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 /7 18 >> >> >>", segments.join(" "))
};
let path = "<< /0 << /0 [ 0 0 ] /1 << /0 [ 8151.5 8171.5 8151.5 8171.5 8191.5 8161.5 8191.5 8171.5 8191.5 8171.5 8211.5 8181.5 8231.5 8171.5 8231.5 8171.5 ] >> /2 << /0 2 /6 [ 0.5 2.0 ] >> >> >>";
let story = |text: &str, frames: &str, style: &str| {
let n = text.chars().count() - text.matches('\\').count();
format!(
"<< /0 << /0 ({text}) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 2 /1 4 /2 6 >> /6 0 >> >> /1 {n} >> ] >> \
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << {style} >> >> >> /1 {n} >> ] >> >> /1 << /0 [ {frames} ] >> >>"
)
};
format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} {} {path} ] >> >>\n/1 << /1 [ {} {} ] /2 << /1 12.0 >> >>\n",
area(8151.5, 8201.5),
area(8211.5, 8241.5),
story(
"A story in two frames\\rand more\\r",
"<< /0 0 >> << /0 1 >>",
"/1 9.0 /8 50 /53 << /99 /CAITextPaint /0 << /0 1 /1 [ 1.0 1.0 0.0 0.0 ] >> >>"
),
story("On a path\\r", "<< /0 2 >>", "/1 8.0"),
)
}
/// The text objects of [`frames_document_text`]: story 0 in its two frames, story 1 in its one (a
/// text object names its frame among its story's).
const FRAME_OBJECTS: &str = "/AI11Text :\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n/AI11Text :\n1 /FrameIndex ,\n0 /StoryIndex ,\n;\n/AI11Text :\n0 /FrameIndex ,\n1 /StoryIndex ,\n;\n";
/// The fuzzed fixture, as it is, reads as area type in two threaded frames and type on a path.
#[test]
fn the_frames_fixture_reads_as_threaded_area_type_and_type_on_a_path() {
let l = vectorcraft_engine::cmd::fileio::load("x.eps", &text_eps_of(&frames_document_text(), FRAME_OBJECTS)).unwrap();
let mut kinds = vec![];
l.doc.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
kinds.push(match t.kind {
vectorcraft_doc::TextKind::Area { .. } => "area",
vectorcraft_doc::TextKind::OnPath { .. } => "path",
_ => "point",
});
}
});
assert_eq!(kinds, ["area", "area", "path"], "{:?}", l.warnings);
assert_eq!(l.doc.text_threads.len(), 1);
}
/// An EPS with a hidden text object whose story is in `document`.
fn text_eps(document: &str) -> Vec<u8> {
text_eps_of(document, "/AI11Text :\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n")
}
/// An EPS with the text `objects` on a hidden layer, their stories in `document`.
fn text_eps_of(document: &str, objects: &str) -> Vec<u8> {
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let editing = format!(
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
%AI5_BeginLayer\n0 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Spare) Ln\n/AI11Text :\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nLB\n%AI5_EndLayer--\n\
%AI5_BeginLayer\n0 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Spare) Ln\n{objects}LB\n%AI5_EndLayer--\n\
%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n",
lines.join("\n")
);
@@ -1712,6 +1771,15 @@ proptest! {
survive("mutated EPS text document", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
/// The same for area type threaded through frames and type on a path, opened as a document
/// (its threads flow).
#[test]
fn eps_text_frames_never_panic(cut in 0usize..2_500, edits in prop::collection::vec((0usize..2_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1', '2'])), 0..12)) {
let text = mutate_text(&frames_document_text(), cut, &edits);
let bytes = text_eps_of(&text, FRAME_OBJECTS);
survive("mutated EPS text frames", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?;
}
/// An Illustrator EPS whose editing data is damaged or hostile: read as its layers, or as its page.
#[test]
fn eps_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'k', 'x'])), 0..12)) {
@@ -1915,3 +1983,127 @@ proptest! {
}
}
}
// ---------- font files a folder search reads ----------
/// A small font file holding what a folder search reads: an outline table's tag, the `name` and
/// `OS/2` tables of the bundled Source Sans 3 renamed "Findme Sans 3", and an `fvar` table with a
/// weight axis and three named instances (named by name ids 2, 1 and 4).
fn search_font() -> Vec<u8> {
let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3");
let be32 = |at: usize| u32::from_be_bytes(font[at..at + 4].try_into().unwrap()) as usize;
let table = |tag: &[u8; 4]| {
let n = u16::from_be_bytes([font[4], font[5]]) as usize;
let r = (0..n).map(|i| 12 + 16 * i).find(|&r| &font[r..r + 4] == tag).unwrap();
font[be32(r + 8)..be32(r + 8) + be32(r + 12)].to_vec()
};
// fvar 1.0: the axis array at 16, one axis of 20 bytes, three instances of 8.
let mut fvar = vec![];
for v in [1u16, 0, 16, 2, 1, 20, 3, 8] {
fvar.extend(v.to_be_bytes());
}
fvar.extend(b"wght");
for v in [100i32, 400, 900] {
fvar.extend((v << 16).to_be_bytes());
}
fvar.extend([0, 0, 1, 0]);
for (name, weight) in [(2u16, 300i32), (1, 600), (4, 900)] {
fvar.extend(name.to_be_bytes());
fvar.extend(0u16.to_be_bytes());
fvar.extend((weight << 16).to_be_bytes());
}
let tables: [(&[u8; 4], Vec<u8>); 4] = [(b"OS/2", table(b"OS/2")), (b"fvar", fvar), (b"glyf", vec![0; 4]), (b"name", table(b"name"))];
let mut out = 0x0001_0000_u32.to_be_bytes().to_vec();
for v in [tables.len() as u16, 0, 0, 0] {
out.extend(v.to_be_bytes());
}
let mut offset = 12 + 16 * tables.len();
for (tag, data) in &tables {
out.extend(*tag);
for v in [0, offset as u32, data.len() as u32] {
out.extend(v.to_be_bytes());
}
offset += data.len().next_multiple_of(4);
}
for (_, data) in &tables {
out.extend(data);
out.resize(out.len().next_multiple_of(4), 0);
}
out
}
/// `font` as a collection of `faces % 5` faces that all read it, whose header gives `faces` as the
/// count.
fn search_collection(font: &[u8], faces: u32) -> Vec<u8> {
let k = (faces % 5) as usize;
let base = 12 + 4 * k;
let mut out = b"ttcf".to_vec();
out.extend(0x0001_0000_u32.to_be_bytes());
out.extend(faces.to_be_bytes());
for _ in 0..k {
out.extend((base as u32).to_be_bytes());
}
// The tables' offsets count from the start of the collection.
let mut f = font.to_vec();
let n = u16::from_be_bytes([f[4], f[5]]) as usize;
for i in 0..n {
let at = 12 + 16 * i + 8;
let offset = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) + base as u32;
f[at..at + 4].copy_from_slice(&offset.to_be_bytes());
}
out.extend(f);
out
}
/// The fonts a search for "Findme Sans 3" looks for: the face, and a style of the family as if the
/// family were installed.
fn findme_wanted() -> vectorcraft_text::WantedFonts {
use vectorcraft_text::WantedFont;
vectorcraft_text::WantedFonts::new(&[
WantedFont { family: "Findme Sans 3".into(), style: "Regular".into(), installed: None },
WantedFont { family: "FINDME SANS 3".into(), style: "Black".into(), installed: Some("Findme Sans 3".into()) },
WantedFont { family: "SourceSans3-Regular".into(), style: "Bold".into(), installed: None },
])
}
/// Whether reading `bytes` as a font file a search reads panics.
fn search_reads(what: &str, bytes: &[u8]) -> Result<Vec<usize>, TestCaseError> {
let path = vectorcraft_testkit::temp_dir("font-search-fuzz").join(format!("{:?}.ttc", std::thread::current().id()));
std::fs::write(&path, bytes).unwrap();
catch_quiet(|| findme_wanted().provided_by(&path)).map_err(|e| TestCaseError::fail(format!("{what}: a search reading the file panicked: {e}")))
}
/// The samples the fuzz properties mutate reach the matching: each provides the face it names.
#[test]
fn the_search_font_samples_are_read_whole() {
let font = search_font();
assert_eq!(search_reads("font", &font).unwrap(), [0, 2]);
assert_eq!(search_reads("collection", &search_collection(&font, 3)).unwrap(), [0, 2]);
// Two faces, and a header that gives seven.
assert_eq!(search_reads("collection claiming more faces", &search_collection(&font, 7)).unwrap(), [0, 2]);
}
proptest! {
#![proptest_config(config())]
#[test]
fn font_files_a_search_reads_never_panic(
faces in prop::option::of(any::<u32>()),
cut in prop::option::of(0usize..12_000),
edits in prop::collection::vec((0usize..12_000, any::<u8>()), 0..12),
) {
let font = search_font();
let mut bytes = match faces {
Some(n) => search_collection(&font, n),
None => font,
};
for (at, b) in edits {
let n = bytes.len();
bytes[at % n] = b;
}
if let Some(cut) = cut {
bytes.truncate(cut);
}
search_reads("mutated font file", &bytes)?;
}
}
+1 -1
View File
@@ -27,8 +27,8 @@ use std::io::Read as _;
use super::lex::find;
use crate::ps;
pub(crate) use read::slot_of;
pub use read::{Structure, read};
pub(crate) use read::{slot_frame, slot_of};
#[cfg(test)]
mod tests;
+22 -5
View File
@@ -78,7 +78,12 @@ pub(crate) const TEXT_SLOT: &str = "\u{0}text";
/// Is `name` that of a text slot, and which story is it of?
pub(crate) fn slot_of(name: Option<&str>) -> Option<Option<u32>> {
name?.strip_prefix(TEXT_SLOT).map(|rest| rest.parse().ok())
name?.strip_prefix(TEXT_SLOT).map(|rest| rest.split(':').next().and_then(|s| s.parse().ok()))
}
/// Which of its story's frames a text slot named `name` is (0 when it doesn't say).
pub(crate) fn slot_frame(name: Option<&str>) -> usize {
name.and_then(|n| n.strip_prefix(TEXT_SLOT)).and_then(|rest| rest.split_once(':')).and_then(|(_, f)| f.parse().ok()).unwrap_or(0)
}
/// Read the structure of the editing data `data`.
@@ -311,6 +316,9 @@ const SKIPPED: &[(&str, &str)] = &[
("Alternate_Content", "End_Versioned_Content"),
];
/// The note for a `/ForeignObject`, art the editor shows but doesn't edit.
pub const NON_NATIVE_ART: &str = "non-native art (a placed PDF's content) is left out: VectorCraft doesn't draw it from the editing data yet";
/// A section comment's marker without its `AI<version>_` prefix and value (`AI14_BeginSymbol` →
/// `BeginSymbol`); DSC comments (`%%BeginProlog`) keep their `%`.
fn marker(c: &str) -> &str {
@@ -645,8 +653,13 @@ impl<'a> Reader<'a> {
"," => {
if let Some(Frame { kind: Kind::Obj(o), base, .. }) = self.frames.last_mut() {
obj::add_entry(o, &mut self.stack, *base);
// Binary data in ASCII85 follows, up to its `~>`.
if o.ty == "Binary" && o.entries.last().is_some_and(|(k, _)| k.as_deref() == Some("ASCII85Decode")) {
// Binary data in ASCII85 follows, up to its `~>`: a `/Binary` dictionary's
// (`/ASCII85Decode ,`) or a non-native art object's (`/ForeignObject`'s
// `/Data ,`, the PDF it keeps), in comment lines. ASCII85 has `_`, so a line
// of it may start with `%_` and read as hidden tokens: a `(` there would open
// a string that swallows the rest of the layer.
let key = o.entries.last().and_then(|(k, _)| k.as_deref());
if (o.ty == "Binary" && key == Some("ASCII85Decode")) || (o.ty == "ForeignObject" && key == Some("Data")) {
self.lex.skip_past(b"~>");
}
}
@@ -826,6 +839,9 @@ impl<'a> Reader<'a> {
"Document" => self.document(&o),
"AI11Text" => self.text_slot(&o)?,
"SymbolInstance" => self.unreadable("symbols"),
// Art Illustrator shows but doesn't edit (a placed PDF's content): its PDF is kept in
// the dictionary, which nothing draws from yet, so the file opens without it.
"ForeignObject" => self.warn(NON_NATIVE_ART),
_ => {}
}
Ok(())
@@ -833,10 +849,11 @@ impl<'a> Reader<'a> {
/// A text object (`/AI11Text`): an empty group standing for it, named after its story.
fn text_slot(&mut self, o: &Obj) -> Result<(), String> {
let story = o.nums("StoryIndex").first().copied().filter(|v| (0.0..f64::from(u32::MAX)).contains(v)).map(|v| v as u32);
let index = |key: &str| o.nums(key).first().copied().filter(|v| (0.0..f64::from(u32::MAX)).contains(v)).map(|v| v as u32);
let (story, frame) = (index("StoryIndex"), index("FrameIndex").unwrap_or(0));
let gs = self.gs.clone();
let mut n = self.new_node(NodeKind::Group { children: vec![], clip: false }, &gs);
n.name = Some(story.map_or_else(|| TEXT_SLOT.to_string(), |s| format!("{TEXT_SLOT}{s}")));
n.name = Some(story.map_or_else(|| TEXT_SLOT.to_string(), |s| format!("{TEXT_SLOT}{s}:{frame}")));
let hidden = self.obj_hidden;
self.add(n, hidden)
}
+12
View File
@@ -329,6 +329,18 @@ fn sections_it_skips() {
assert_eq!(art(&doc).len(), 1);
}
/// Non-native art (a placed PDF's content) keeps its PDF as ASCII85 in comment lines after
/// `/Data ,`. ASCII85 has `_`, so a line may start with `%_`, which otherwise reads as hidden
/// tokens, and a `(` in it would swallow the rest of the layer (a letterhead saved by Illustrator
/// 28 wouldn't open: "it ends inside a layer"). The art is left out with a note.
#[test]
fn non_native_art_is_skipped_with_its_ascii85_data() {
let foreign = "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@<P2`V<S,pbuU7L]\\~>\n;\n0 0 Xd\n6 () XW\n0 Ae\n";
let s = read_ok(&layer(&format!("{foreign}{}", rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")));
assert_eq!(art(&s.doc).len(), 1);
assert!(s.warnings.iter().any(|w| w == read::NON_NATIVE_ART), "{:?}", s.warnings);
}
#[test]
fn cmyk_documents() {
let doc = read_ok(&format!("%AI9_ColorModel: 2\n{}", layer(""))).doc;
+328 -118
View File
@@ -20,9 +20,10 @@
use std::collections::BTreeMap;
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{CharStyle, Justify, Node, NodeId, NodeKind, ParaStyle, TextObject, TextRun};
use vectorcraft_geom::{Affine, Point};
use vectorcraft_doc::{CharStyle, Justify, Node, NodeId, NodeKind, ParaStyle, TextKind, TextObject, TextRun};
use vectorcraft_geom::{Affine, PathData, Point, Rect};
/// Longest story read (bytes).
const MAX_STORY: usize = 1 << 20;
@@ -54,13 +55,6 @@ impl Val {
}
}
fn at(&self, i: usize) -> Option<&Val> {
match self {
Val::List(l) => l.get(i),
_ => None,
}
}
fn num(&self) -> Option<f64> {
match self {
Val::Num(n) if n.is_finite() => Some(*n),
@@ -239,12 +233,32 @@ fn read(bytes: &[u8]) -> Option<Val> {
}
}
/// How a paragraph's lines sit against its anchor.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Align {
Left,
Center,
Right,
/// Most frames read of one story, and most path segments of a frame.
const MAX_FRAMES: usize = 4096;
const MAX_SEGMENTS: usize = 1 << 16;
/// Where a frame puts its story's text.
#[derive(Debug, Clone)]
enum FrameKind {
/// Point type: the matrix carries the layout (its anchor at the origin of its lines) onto the
/// canvas.
Point([f64; 6]),
/// Area type flowed inside a path: its cubic segments on the canvas, four points each.
Area(Vec<[f64; 8]>),
/// Type on a path, from `start` to `end` (segment index and the place in that segment).
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64 },
}
/// A paragraph's attributes, as the text document keeps them.
#[derive(Clone, Debug, Default, PartialEq)]
struct Para {
justify: u8,
first_indent: f64,
left_indent: f64,
right_indent: f64,
space_before: f64,
space_after: f64,
hyphenate: bool,
}
/// The text of one story, in the units of the text document.
@@ -252,13 +266,14 @@ enum Align {
pub(super) struct Story {
/// The characters, with `\r` ending paragraphs and `\x03` ending lines.
text: String,
/// The anchor of the layout.
/// The anchor of the first frame's layout.
anchor: (f64, f64),
/// Where each line starts, from the anchor.
/// Where each of the first frame's lines starts, from the anchor.
lines: Vec<(f64, f64)>,
/// Carries the layout onto the canvas.
matrix: [f64; 6],
align: Align,
/// The frames the story flows through, in order.
frames: Vec<FrameKind>,
/// `(characters, paragraph)` in order.
paras: Vec<(usize, Para)>,
/// `(characters, style)` in order.
runs: Vec<(usize, Style)>,
}
@@ -267,8 +282,14 @@ pub(super) struct Story {
struct Style {
font: Option<String>,
size: f64,
fill: Option<[f64; 4]>,
stroke: Option<[f64; 4]>,
/// `None`: auto.
leading: Option<f64>,
tracking: f64,
baseline_shift: f64,
h_scale: f64,
v_scale: f64,
fill: Option<Color>,
stroke: Option<Color>,
stroke_width: f64,
}
@@ -276,8 +297,9 @@ struct Style {
pub(super) struct Texts {
stories: Vec<Val>,
fonts: Vec<String>,
/// The character style a story starts from.
/// The character and paragraph styles a story starts from.
defaults: Val,
para_defaults: Val,
frames: Vec<Val>,
}
@@ -320,86 +342,135 @@ impl Texts {
stories: main.get("1")?.list().to_vec(),
fonts,
defaults: main.get("2")?.clone(),
para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())),
frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(),
})
}
/// Story `i`, if it is one of point type this reads.
/// Frame `i` of the document, if it is of a kind this reads.
fn frame(&self, i: usize) -> Option<FrameKind> {
let f = self.frames.get(i)?.get("0")?;
let carries = f.get("2")?;
let segments = || -> Option<Vec<[f64; 8]>> {
let n = f.get("1")?.get("0")?.nums()?;
let (chunks, rest) = n.as_chunks::<8>();
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.to_vec())
};
match carries.get("0").and_then(Val::num).unwrap_or(0.0) as i64 {
0 => Some(FrameKind::Point(carries.get("2")?.nums()?.try_into().ok()?)),
1 => Some(FrameKind::Area(segments()?)),
2 => {
let range = carries.get("6").and_then(Val::nums).unwrap_or_default();
let segments = segments()?;
let n = segments.len() as f64;
let start = range.first().copied().unwrap_or(0.0).clamp(0.0, n);
let end = range.get(1).copied().unwrap_or(n).clamp(start, n);
Some(FrameKind::OnPath { segments, start, end })
}
_ => None,
}
}
/// Story `i`, if its frames are of kinds this reads.
pub(super) fn story(&self, i: usize) -> Option<Story> {
let s = self.stories.get(i)?;
let text = s.get("0")?.get("0")?.str().filter(|t| t.len() <= MAX_STORY)?.to_string();
// The frame the story is in: a matrix and nothing else but its place.
let frame = self.frames.get(s.get("1")?.get("0")?.at(0)?.get("0")?.num()? as usize)?.get("0")?;
let carries = frame.get("2")?;
if carries.get("2").is_none() || carries.as_dict().is_some_and(|d| d.keys().any(|k| k != "2")) {
let view = s.get("1")?;
let frames: Vec<FrameKind> = view
.get("0")?
.list()
.iter()
.take(MAX_FRAMES)
.map(|f| f.get("0").and_then(Val::num).and_then(|n| self.frame(n as usize)))
.collect::<Option<_>>()?;
if frames.is_empty() {
return None;
}
let matrix: [f64; 6] = carries.get("2")?.nums()?.try_into().ok()?;
let f = find_node(s.get("1")?.get("2")?, "F")?;
let anchor = f.get("0")?.get("0")?.nums()?;
let anchor = (*anchor.first()?, *anchor.get(1)?);
let mut lines = vec![];
let mut found = vec![];
find_nodes(f, "L", &mut found);
for l in found {
let off = l.get("0").and_then(|o| o.get("0")).and_then(Val::nums).unwrap_or_else(|| vec![0.0, 0.0]);
let seg = l.get("6")?.list().iter().find(|c| c.is_node("S"))?;
let so = seg.get("0").and_then(|o| o.get("0")).and_then(Val::nums).unwrap_or_else(|| vec![0.0, 0.0]);
lines.push((off.first()? + so.first()?, *off.get(1)?));
// The first frame's layout, when the file keeps one: where its lines start.
let (mut anchor, mut lines) = ((0.0, 0.0), vec![]);
if let Some(f) = view.get("2").and_then(|l| find_node(l, "F")) {
if let Some(a) = f.get("0").and_then(|a| a.get("0")).and_then(Val::nums)
&& let [x, y, ..] = a.as_slice()
{
anchor = (*x, *y);
}
let mut found = vec![];
find_nodes(f, "L", &mut found);
for l in found {
let off = l.get("0").and_then(|o| o.get("0")).and_then(Val::nums).unwrap_or_else(|| vec![0.0, 0.0]);
let Some(seg) = l.get("6").map(Val::list).and_then(|c| c.iter().find(|c| c.is_node("S"))) else { continue };
let so = seg.get("0").and_then(|o| o.get("0")).and_then(Val::nums).unwrap_or_else(|| vec![0.0, 0.0]);
if let (Some(ox), Some(oy), Some(sx)) = (off.first(), off.get(1), so.first()) {
lines.push((ox + sx, *oy));
}
}
}
if lines.is_empty() {
return None;
let mut paras = vec![];
for run in s.get("0")?.get("5").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() {
let n = run.get("1").and_then(Val::num)? as usize;
let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("5"));
paras.push((n, self.para(props)));
}
let align = match s
.get("0")
.and_then(|t| t.get("5"))
.and_then(|p| p.get("0"))
.and_then(|p| p.at(0))
.and_then(|p| p.get("0"))
.and_then(|p| p.get("0"))
.and_then(|p| p.get("5"))
.and_then(|p| p.get("0"))
.and_then(Val::num)
{
Some(1.0) => Align::Right,
Some(2.0) => Align::Center,
_ => Align::Left,
};
let mut runs = vec![];
for run in s.get("0")?.get("6")?.get("0")?.list() {
let n = run.get("1")?.num()? as usize;
let style = run.get("0")?.get("0")?.get("6")?;
runs.push((n, self.style(style)));
for run in s.get("0")?.get("6").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() {
let n = run.get("1").and_then(Val::num)? as usize;
let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("6"));
runs.push((n, self.style(props)));
}
if runs.is_empty() {
runs.push((text.chars().count(), self.style(None)));
}
Some(Story { text, anchor, lines, frames, paras, runs })
}
/// A paragraph's attributes: its own keys, else the document's.
fn para(&self, p: Option<&Val>) -> Para {
let pick = |k: &str| p.and_then(|p| p.get(k)).or_else(|| self.para_defaults.get(k));
let num = |k: &str| pick(k).and_then(Val::num).filter(|v| v.abs() < 1e5).unwrap_or(0.0);
Para {
justify: pick("0").and_then(Val::num).map_or(0, |v| v.clamp(0.0, 6.0) as u8),
first_indent: num("1"),
left_indent: num("2"),
right_indent: num("3"),
space_before: num("4"),
space_after: num("5"),
hyphenate: !matches!(pick("9"), Some(Val::Bool(false))),
}
Some(Story { text, anchor, lines, matrix, align, runs })
}
/// A character style: its own keys, else the document's.
fn style(&self, s: &Val) -> Style {
let pick = |k: &str| s.get(k).or_else(|| self.defaults.get(k));
let paint = |k: &str| -> Option<[f64; 4]> {
let p = pick(k)?.get("0")?;
// Kind 2 is CMYK: an opacity, then the four inks.
(p.get("0")?.num()? == 2.0).then(|| p.get("1")?.nums()).flatten().and_then(|v| Some([*v.get(1)?, *v.get(2)?, *v.get(3)?, *v.get(4)?]))
};
fn style(&self, s: Option<&Val>) -> Style {
let pick = |k: &str| s.and_then(|s| s.get(k)).or_else(|| self.defaults.get(k));
let num = |k: &str| pick(k).and_then(Val::num);
let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false)));
let font = pick("0").and_then(Val::num).and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.is_empty()).cloned();
let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.is_empty()).cloned();
let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0);
Style {
font,
size: pick("1").and_then(Val::num).filter(|v| *v > 0.0).unwrap_or(12.0),
fill: if on("56") { Some(paint("53").unwrap_or([0.0, 0.0, 0.0, 1.0])) } else { None },
stroke: if matches!(pick("57"), Some(Val::Bool(true))) { paint("54") } else { None },
stroke_width: pick("63").and_then(Val::num).filter(|v| *v >= 0.0).unwrap_or(1.0),
size,
leading: if on("4") { None } else { num("5").filter(|v| *v > 0.0 && *v < 1e5) },
tracking: num("8").filter(|v| v.abs() < 1e5).unwrap_or(0.0),
baseline_shift: num("9").filter(|v| v.abs() < 1e5).unwrap_or(0.0),
h_scale: num("6").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0),
v_scale: num("7").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0),
fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None },
stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None },
stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0),
}
}
}
impl Val {
fn as_dict(&self) -> Option<&BTreeMap<String, Val>> {
match self {
Val::Dict(d) => Some(d),
_ => None,
}
/// The colour of a paint of the text document: kind 0 grey (`[alpha, level]`, 1 is white), 1 RGB
/// (`[alpha, r, g, b]`), 2 CMYK (`[alpha, c, m, y, k]`).
fn paint(p: &Val) -> Option<Color> {
let p = p.get("0")?;
let v = p.get("1")?.nums()?;
let unit = |i: usize| v.get(i).map(|c| c.clamp(0.0, 1.0) as f32);
match p.get("0")?.num()? as i64 {
0 => Some(Color::gray(1.0 - unit(1)?)),
1 => Some(Color::rgb(unit(1)?, unit(2)?, unit(3)?)),
2 => Some(Color::cmyk(unit(1)?, unit(2)?, unit(3)?, unit(4)?)),
_ => None,
}
}
@@ -429,57 +500,145 @@ fn find_nodes<'a>(v: &'a Val, name: &str, out: &mut Vec<&'a Val>) {
}
}
/// Where a story's first line starts: on the canvas of the app (what [`Story::place`] gives).
/// A point of the canvas (y down) in the units of the art (y up), given the centre `template` of
/// the file's template box.
fn to_art((x, y): (f64, f64), template: (f64, f64)) -> (f64, f64) {
(x - CANVAS_CENTRE + template.0, CANVAS_CENTRE + template.1 - y)
}
/// Segments of the canvas as a path of the document.
fn path_of(segments: &[[f64; 8]], template: (f64, f64), to_doc: Affine) -> PathData {
let at = |x: f64, y: f64| {
let (x, y) = to_art((x, y), template);
to_doc * Point::new(x, y)
};
let mut bp = BezPath::new();
for (i, [x0, y0, x1, y1, x2, y2, x3, y3]) in segments.iter().enumerate() {
if i == 0 {
bp.move_to(at(*x0, *y0));
}
bp.curve_to(at(*x1, *y1), at(*x2, *y2), at(*x3, *y3));
}
let closed = matches!((segments.first(), segments.last()), (Some(f), Some(l)) if (f[0] - l[6]).abs() < 1e-3 && (f[1] - l[7]).abs() < 1e-3);
if closed {
bp.close_path();
}
PathData::from_bezpath(&bp)
}
/// Where on `segments` the place `t` (segment index and the place in it) is, as a fraction of their
/// length.
fn length_fraction(segments: &[[f64; 8]], t: f64) -> f64 {
let cubic = |s: &[f64; 8]| CubicBez::new((s[0], s[1]), (s[2], s[3]), (s[4], s[5]), (s[6], s[7]));
let lengths: Vec<f64> = segments.iter().map(|s| cubic(s).arclen(0.01)).collect();
let total: f64 = lengths.iter().sum();
if !total.is_finite() || total <= 1e-9 {
return 0.0;
}
let whole = t.floor().max(0.0) as usize;
let before: f64 = lengths.iter().take(whole).sum();
let within = match segments.get(whole) {
Some(s) => cubic(s).subsegment(0.0..t.fract().clamp(0.0, 1.0)).arclen(0.01),
None => 0.0,
};
((before + within) / total).clamp(0.0, 1.0)
}
impl Story {
/// How many bytes of text the story has.
pub(super) fn len(&self) -> usize {
self.text.len()
}
/// The point frame's matrix (the first frame's, when it is one), else the identity.
fn matrix(&self) -> [f64; 6] {
match self.frames.first() {
Some(FrameKind::Point(m)) => *m,
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
}
}
/// The anchor of the story on the file's canvas: `(x, y)` in the units of the art, y up, given
/// the centre `(tx, ty)` of the file's template box.
pub(super) fn place(&self, template: (f64, f64)) -> (f64, f64) {
let [a, b, c, d, e, f] = self.matrix;
let (x, y) = (a * self.anchor.0 + c * self.anchor.1 + e, b * self.anchor.0 + d * self.anchor.1 + f);
(x - CANVAS_CENTRE + template.0, CANVAS_CENTRE + template.1 - y)
let [a, b, c, d, e, f] = self.matrix();
to_art((a * self.anchor.0 + c * self.anchor.1 + e, b * self.anchor.0 + d * self.anchor.1 + f), template)
}
/// Each line's characters and where it starts (in the units of the art, y up): where the page
/// draws the line when the type is shown.
pub(super) fn line_starts(&self, template: (f64, f64)) -> Vec<(String, (f64, f64))> {
let [a, b, c, d, e, f] = self.matrix;
let [a, b, c, d, e, f] = self.matrix();
let text: Vec<&str> = self.text.split(['\r', '\x03']).collect();
self.lines
.iter()
.enumerate()
.map(|(i, (lx, ly))| {
let (x, y) = (self.anchor.0 + lx, self.anchor.1 + ly);
let (x, y) = (a * x + c * y + e, b * x + d * y + f);
(text.get(i).copied().unwrap_or_default().to_string(), (x - CANVAS_CENTRE + template.0, CANVAS_CENTRE + template.1 - y))
(text.get(i).copied().unwrap_or_default().to_string(), to_art((a * x + c * y + e, b * x + d * y + f), template))
})
.collect()
}
/// The story as a text object whose anchor is at `at` on the document (`to_doc` takes the art's
/// units onto it), or `None` for type that is mirrored or has no size.
pub(super) fn node(&self, id: NodeId, template: (f64, f64), to_doc: Affine) -> Option<Node> {
let [a, b, c, d, ..] = self.matrix;
let scale = (a * d - b * c).abs().sqrt();
if !(scale.is_finite() && scale > 1e-6 && a * d - b * c > 0.0) {
return None;
}
let (x, y) = self.place(template);
let at = to_doc * Point::new(x, y);
let text: String = self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect();
if text.trim().is_empty() {
/// Roughly where the story's type lies on the document: its frame's box, or round its lines
/// for point type (what the page draws of it lies there).
pub(super) fn region(&self, template: (f64, f64), to_doc: Affine) -> Option<Rect> {
let size = self.runs.iter().map(|(_, s)| s.size).fold(0.0, f64::max);
let bounds = |segments: &[[f64; 8]]| path_of(segments, template, to_doc).bounds();
let r = match self.frames.first()? {
FrameKind::Area(s) => bounds(s)?,
FrameKind::OnPath { segments, .. } => bounds(segments)?.inflate(size * 1.5, size * 1.5),
FrameKind::Point(_) => {
let longest = self.text.split(['\r', '\x03']).map(|l| l.chars().count()).max().unwrap_or(0) as f64;
let reach = longest * size + size;
let points: Vec<Point> = self.line_starts(template).into_iter().map(|(_, (x, y))| to_doc * Point::new(x, y)).collect();
let first = points.first().copied().unwrap_or_else(|| {
let (x, y) = self.place(template);
to_doc * Point::new(x, y)
});
points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)).inflate(reach, size * 1.5)
}
};
r.is_finite().then_some(r)
}
/// The story as the text object of its frame `frame` (`to_doc` takes the art's units onto the
/// document), or `None` for type that is mirrored, has no size, or a frame past the first of
/// threaded type (the first frame holds the whole story).
pub(super) fn node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option<Node> {
let kind = self.frames.get(frame)?;
let threaded = frame > 0;
let (scale, xf, kind) = match kind {
FrameKind::Point(m) => {
let [a, b, c, d, ..] = *m;
let scale = (a * d - b * c).abs().sqrt();
if !(scale.is_finite() && scale > 1e-6 && a * d - b * c > 0.0) || threaded {
return None;
}
let (x, y) = self.place(template);
let at = to_doc * Point::new(x, y);
(scale, Affine::new([a / scale, b / scale, c / scale, d / scale, at.x, at.y]), TextKind::Point)
}
FrameKind::Area(s) => (1.0, Affine::IDENTITY, TextKind::Area { frame: path_of(s, template, to_doc) }),
FrameKind::OnPath { segments, start, end } => {
let n = segments.len() as f64;
let end = (*end < n - 0.02).then(|| length_fraction(segments, *end));
(1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end })
}
};
let text: String = if threaded {
String::new()
} else {
self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect()
};
if text.trim().is_empty() && !threaded {
return None;
}
let leading = self.lines.windows(2).map(|w| (w[1].1 - w[0].1) * scale).find(|l| l.is_finite() && *l > 0.0);
let chars: Vec<char> = text.chars().collect();
let mut runs = vec![];
let mut from = 0usize;
let styles: Vec<&(usize, Style)> = self.runs.iter().collect();
for (n, st) in styles {
for (n, st) in &self.runs {
let to = from.saturating_add(*n).min(chars.len());
let piece: String = chars.get(from..to).unwrap_or_default().iter().collect();
from = to;
@@ -492,35 +651,86 @@ impl Story {
let last = self.runs.last().map(|r| &r.1)?;
runs.push(TextRun::new(chars.get(from..).unwrap_or_default().iter().collect::<String>(), char_style(last, scale, leading)));
}
if runs.is_empty() {
return None;
let first = self.runs.first().map(|r| char_style(&r.1, scale, leading))?;
let mut t = TextObject::point(Point::ZERO, "", first);
if !runs.is_empty() {
t.runs = runs;
}
let mut t = TextObject::point(Point::ZERO, "", runs.first()?.style.clone());
t.runs = runs;
t.para = ParaStyle {
justify: match self.align {
Align::Left => Justify::Left,
Align::Center => Justify::Center,
Align::Right => Justify::Right,
},
..ParaStyle::default()
};
t.xf = Affine::new([a / scale, b / scale, c / scale, d / scale, at.x, at.y]);
let paras: Vec<ParaStyle> = self.paragraph_styles(&text, scale);
t.para = paras.first().cloned().unwrap_or_default();
if paras.len() > 1 && paras.iter().any(|p| *p != t.para) {
t.paras = paras;
}
t.kind = kind;
t.xf = xf;
Some(Node::new(id, NodeKind::Text(Box::new(t))))
}
/// The style of each paragraph of `text` (paragraphs split at `\n`).
fn paragraph_styles(&self, text: &str, scale: f64) -> Vec<ParaStyle> {
let count = text.split('\n').count();
let mut out = Vec::with_capacity(count);
let mut runs = self.paras.iter();
let mut current = runs.next();
let mut left = current.map_or(usize::MAX, |r| r.0);
for p in text.split('\n') {
let para = current.map(|r| r.1.clone()).unwrap_or_default();
out.push(para_style(&para, scale));
// Each paragraph and its ending `\r` count.
let mut used = p.chars().count() + 1;
while used > 0 {
if left > used {
left -= used;
used = 0;
} else {
used -= left;
current = runs.next();
left = current.map_or(usize::MAX, |r| r.0);
if current.is_none() {
break;
}
}
}
}
out
}
}
fn para_style(p: &Para, scale: f64) -> ParaStyle {
ParaStyle {
justify: match p.justify {
1 => Justify::Right,
2 => Justify::Center,
3 => Justify::JustifyLeft,
4 => Justify::JustifyRight,
5 => Justify::JustifyCenter,
6 => Justify::JustifyAll,
_ => Justify::Left,
},
left_indent: p.left_indent * scale,
right_indent: p.right_indent * scale,
first_line_indent: p.first_indent * scale,
space_before: p.space_before * scale,
space_after: p.space_after * scale,
hyphenate: p.hyphenate,
..ParaStyle::default()
}
}
fn char_style(s: &Style, scale: f64, leading: Option<f64>) -> CharStyle {
let (family, style) = s.font.as_deref().map_or_else(|| (CharStyle::default().font_family, "Regular".to_string()), crate::family_style);
let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family);
let ink = |c: [f64; 4]| Paint::solid(Color::cmyk(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32));
CharStyle {
font_family: family,
font_style: style,
size: s.size * scale,
leading,
fill: s.fill.map_or(Paint::None, ink),
stroke: s.stroke.map_or(Paint::None, ink),
leading: s.leading.map(|l| l * scale).or(leading),
tracking: s.tracking,
baseline_shift: s.baseline_shift * scale,
h_scale: s.h_scale * 100.0,
v_scale: s.v_scale * 100.0,
fill: s.fill.map_or(Paint::None, Paint::solid),
stroke: s.stroke.map_or(Paint::None, Paint::solid),
stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 },
..CharStyle::default()
}
+85 -32
View File
@@ -69,6 +69,8 @@ fn few(names: BTreeSet<String>) -> String {
/// A text slot of the layers.
struct SlotInfo {
story: Option<u32>,
/// Which of the story's frames it is.
frame: usize,
/// It, its layer and the objects round it show.
shown: bool,
}
@@ -78,7 +80,7 @@ fn collect_slots(nodes: &[Arc<Node>], shown: bool, out: &mut Vec<SlotInfo>) {
for n in nodes {
let shown = shown && n.visible;
if let Some(story) = slot_of(n.name.as_deref()) {
out.push(SlotInfo { story, shown });
out.push(SlotInfo { story, frame: ai::slot_frame(n.name.as_deref()), shown });
} else if let Some(c) = n.children().filter(|_| !matches!(n.kind, NodeKind::Compound { .. })) {
collect_slots(c, shown, out);
}
@@ -182,8 +184,10 @@ fn assign(objects: &[Vec<Arc<Node>>], slots: usize) -> Vec<Vec<&[Arc<Node>]>> {
enum Content {
/// Text objects (with the strokes round them) of the page.
Page(Vec<Arc<Node>>),
/// A text object made from the file's text document.
Made(Box<Node>),
/// A text object made from the file's text document, where it lies on the document, whether
/// the page has type where it is, and the page's type of no text object that is nearest it
/// (kept after it).
Made(Box<Node>, Option<Rect>, bool, Vec<Arc<Node>>),
/// Nothing the file lets this read.
Empty,
/// Its type is on the page with another text object's; there is nothing to put here.
@@ -199,13 +203,15 @@ fn fill_slots(
content: &mut std::vec::IntoIter<Content>,
names: &std::collections::HashMap<NodeId, String>,
empty: &mut usize,
made: &mut Vec<(u32, usize, NodeId)>,
) {
let mut i = 0;
while i < nodes.len() {
let Some(n) = nodes.get(i) else { break };
if slot_of(n.name.as_deref()).is_some() {
if let Some(story) = slot_of(n.name.as_deref()) {
let visible = n.visible;
let name = names.get(&n.id);
let frame = ai::slot_frame(n.name.as_deref());
let replacement = match content.next() {
Some(Content::Page(parts)) if !parts.is_empty() => {
// The page's type (and the strokes round it) take the slot's place as they are.
@@ -227,11 +233,20 @@ fn fill_slots(
i += n;
continue;
}
Some(Content::Made(mut text)) => {
Some(Content::Made(mut text, _, seen, extra)) => {
text.id = doc.alloc_id();
if let Some(story) = story {
made.push((story, frame, text.id));
}
text.visible = visible;
text.name = Some(format!("{MADE}{}", name.map_or("", String::as_str)));
Some(*text)
// Type the page shows is kept; other made type is weighed against the page.
text.name = if seen { name.cloned() } else { Some(format!("{MADE}{}", name.map_or("", String::as_str))) };
let mut parts = vec![Arc::new(*text)];
parts.extend(extra.iter().map(|p| reid(doc, p)));
let n = parts.len();
nodes.splice(i..=i, parts);
i += n;
continue;
}
Some(Content::Merged) => {
nodes.remove(i);
@@ -256,7 +271,7 @@ fn fill_slots(
&& !matches!(n.kind, NodeKind::Compound { .. })
&& let Some(c) = nodes.get_mut(i).map(Arc::make_mut).and_then(Node::children_mut)
{
fill_slots(doc, c, content, names, empty);
fill_slots(doc, c, content, names, empty, made);
}
i += 1;
}
@@ -399,6 +414,14 @@ fn join_pieces(parts: &mut Vec<Arc<Node>>, lines: &[(String, Point)]) {
});
}
/// Do the regions of made type cover most of `object`?
fn covered(object: &[Arc<Node>], content: &[Content]) -> bool {
let Some(r) = extent(object) else { return false };
let inside: f64 =
content.iter().filter_map(|c| if let Content::Made(_, Some(region), ..) = c { Some(region.intersect(r).area()) } else { None }).sum();
inside >= 0.5 * r.area().max(1e-9)
}
/// The box round `parts`.
fn extent(parts: &[Arc<Node>]) -> Option<Rect> {
parts.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b))
@@ -440,19 +463,46 @@ fn plan(
*o = Some(k);
}
}
// The file's text document is trusted where it agrees with the page about something, or where the
// page has no type to disagree with.
let trusted = owner.iter().any(Option::is_some) || shown.is_empty();
let readable = |k: usize| trusted && lines.get(k).is_some_and(Option::is_some);
// Type the text document makes, shown or not: the page's pieces of it aren't needed.
let mut content: Vec<Content> = infos.iter().map(|_| Content::Empty).collect();
if let Some(t) = template {
for (k, info) in infos.iter().enumerate() {
let Some(Some(story)) = stories.get(k) else { continue };
let Some(node) = story.node(NodeId(0), info.frame, t, to_doc) else { continue };
let region = story.region(t, to_doc);
if let Some(c) = content.get_mut(k) {
*c = Content::Made(Box::new(node), region.filter(|_| info.shown), false, vec![]);
}
}
}
// The file's text document is trusted where it agrees with the page about something (its lines
// start where the page's type does, or the page has type where it lays type out), or where the
// page has no type to disagree with.
let in_region = |object: &[Arc<Node>]| covered(object, &content);
let trusted = owner.iter().any(Option::is_some) || shown.is_empty() || shown.iter().any(|o| in_region(o));
if !trusted {
content.iter_mut().for_each(|c| *c = Content::Empty);
}
let mut spare: Vec<Vec<Arc<Node>>> = vec![];
for (j, object) in shown.iter().enumerate() {
match owner.get(j).copied().flatten().filter(|_| trusted) {
Some(k) => match content.get_mut(k) {
Some(Content::Made(_, _, seen, _)) => *seen = true,
Some(Content::Page(p)) => p.extend(object.iter().cloned()),
Some(c) => *c = Content::Page(object.clone()),
None => {}
},
// What lies where made type is, is that type as the page draws it.
None if covered(object, &content) => {
let r = extent(object).unwrap_or(Rect::ZERO);
for c in &mut content {
if let Content::Made(_, Some(region), seen, _) = c
&& !region.intersect(r).is_zero_area()
{
*seen = true;
}
}
}
None => spare.push(object.clone()),
}
}
@@ -461,23 +511,9 @@ fn plan(
join_pieces(parts, l);
}
}
// Type of the text document where the page has none: hidden type, and shown type off the page.
for (k, c) in content.iter_mut().enumerate() {
if matches!(c, Content::Empty)
&& readable(k)
&& let (Some(Some(story)), Some(t)) = (stories.get(k), template)
&& let Some(node) = story.node(NodeId(0), t, to_doc)
{
*c = Content::Made(Box::new(node));
}
}
// What is left of the page goes by painting order into the shown slots the file can't say.
let loose: Vec<usize> = infos
.iter()
.enumerate()
.filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty)) && !readable(*k))
.map(|(k, _)| k)
.collect();
let loose: Vec<usize> =
infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect();
if loose.is_empty() {
// Type of the page that no text object says it owns goes with the nearest text object that has
// type of the page; with none, it is left out.
@@ -485,6 +521,7 @@ fn plan(
for object in &spare {
let (centre, near) = (extent(object).map(|r| r.center()), |c: &Content| match c {
Content::Page(parts) => extent(parts).map(|r| r.center()),
Content::Made(_, region, ..) => region.map(|r| r.center()),
_ => None,
});
let nearest = content
@@ -492,7 +529,7 @@ fn plan(
.filter_map(|c| near(c).zip(centre).map(|(p, q)| ((p.x - q.x).hypot(p.y - q.y), c)))
.min_by(|a, b| a.0.total_cmp(&b.0));
match nearest {
Some((_, Content::Page(parts))) => parts.extend(object.iter().cloned()),
Some((_, Content::Page(parts) | Content::Made(_, _, _, parts))) => parts.extend(object.iter().cloned()),
_ => left_out = true,
}
}
@@ -658,7 +695,7 @@ fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered,
let differs: Vec<bool> = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).map(|(p, q)| differ(p, q)).collect();
let (w, h) = (x.width as usize, x.height as usize);
let at = |i: usize, j: usize| j.checked_mul(w).and_then(|row| row.checked_add(i)).and_then(|k| differs.get(k)).copied().unwrap_or(false);
let typed = covered(areas, w, h);
let typed = in_areas(areas, w, h);
// A pixel on the region's edge has neighbours outside it, which don't count as differing.
let solid = (1..h.saturating_sub(1))
.flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j)))
@@ -685,7 +722,7 @@ fn type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect>
}
/// Which of `w` × `h` pixels (row by row) lie in one of `areas`.
fn covered(areas: &[Rect], w: usize, h: usize) -> Vec<bool> {
fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec<bool> {
// Each area adds one inside it: corners marked, then summed along the rows and down the columns.
let stride = w + 1;
let mut count = vec![0i64; stride * (h + 1)];
@@ -814,8 +851,16 @@ fn build(data: &[u8], visible: Option<&Document>, page: Page, outlined: bool) ->
let content = plan(&infos, &stories, template, to_doc, [&shown, &hidden], &mut notes);
let mut empty = 0;
let mut layers = std::mem::take(&mut doc.layers);
fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty);
let mut made = vec![];
fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made);
doc.layers = layers;
// A story in several frames is threaded type: its frames in order (the first holds the story).
made.sort();
for thread in made.chunk_by(|a, b| a.0 == b.0) {
if thread.len() > 1 {
doc.text_threads.push(thread.iter().map(|(_, _, id)| *id).collect());
}
}
if empty > 0 {
notes.push(format!("{empty} {}", if frame.is_some() { TEXT_LEFT_OUT } else { TYPE_LEFT_OUT }));
}
@@ -891,6 +936,14 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u
return 0;
}
let mut with = view.difference(doc, rect).any;
// Taking a text object out changes only what is drawn in its box. When the art would still
// differ from the page by more than `compare` allows with every candidate gone, the layers
// aren't used whatever is pruned: don't draw them again for each one (#758).
let margin = OUTLINE_REACH + 1.0;
let boxes: f64 = found.iter().filter_map(|(_, b)| *b).map(|b| b.inflate(margin, margin).intersect(rect).area().max(0.0)).sum();
if with - boxes / rect.area().max(1e-9) > MAX_DIFFERENCE {
return 0;
}
let mut removed = 0;
for (id, bounds) in found {
if bounds.is_none_or(|b| b.intersect(rect).is_zero_area()) {
+120 -4
View File
@@ -360,9 +360,9 @@ fn type_on_a_hidden_layer_comes_from_the_text_document() {
#[test]
fn type_with_a_frame_it_cant_read_is_left_out_with_a_note() {
// A story whose frame says more than a matrix (a text area, say) isn't guessed at.
// A story whose frame is of a kind this doesn't know isn't guessed at.
let mut doc = text_document(&[("Area\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
doc = doc.replace("/2 << /2 [ 1 0 0 1 0 0 ] >>", "/2 << /2 [ 1 0 0 1 0 0 ] /7 1 >>");
doc = doc.replace("/2 << /2 [ 1 0 0 1 0 0 ] >>", "/2 << /0 9 /2 [ 1 0 0 1 0 0 ] >>");
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert!(text_of(&r.document.layers[1]).is_empty());
@@ -527,11 +527,11 @@ fn an_ai_file_without_its_pdf_part_reads_its_layers_and_makes_its_type() {
// Point type from the text document, shown or not; a story it can't read is left out, with a
// note that is a loss.
let mut doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Area\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]);
// Story 1 in frame 1, a frame that says more than a matrix.
// Story 1 in frame 1, a frame of a kind this doesn't know.
let at = doc.rfind("/1 << /0 [ << /0 0 >> ]").unwrap();
doc.replace_range(at..at + 23, "/1 << /0 [ << /0 1 >> ]");
let at = doc.rfind("/2 << /2 [ 1 0 0 1 0 0 ] >>").unwrap();
doc.replace_range(at..at + 27, "/2 << /2 [ 1 0 0 1 0 0 ] /7 1 >>");
doc.replace_range(at..at + 27, "/2 << /0 9 /2 [ 1 0 0 1 0 0 ] >>");
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &(text_object(0) + &text_object(1)))), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
assert_eq!(names(&d), ["Back", "Words"], "{notes:?}");
@@ -606,3 +606,119 @@ fn type_asked_for_as_outlines_leaves_a_file_whose_type_shows_as_its_pdf_part() {
let (d, w) = crate::layered_ai(&private(&hidden), pdf_part(10.0, 86.0), vec![], true);
assert_eq!(names(&d), ["Art", "Notes"], "{w:?}");
}
/// A point of the art (y up) on the canvas of a file whose template box is centred at (50, 50).
fn canvas(x: f64, y: f64) -> (f64, f64) {
(x + 8141.5, 8241.5 - y)
}
/// The segments (four points each) of the rectangle `x0 y0 x1 y1` of the art, on the canvas.
fn canvas_rect(x0: f64, y0: f64, x1: f64, y1: f64) -> String {
let corners = [canvas(x0, y1), canvas(x0, y0), canvas(x1, y0), canvas(x1, y1), canvas(x0, y1)];
corners
.windows(2)
.map(|w| format!("{} {} {} {} {} {} {} {}", w[0].0, w[0].1, w[0].0, w[0].1, w[1].0, w[1].1, w[1].0, w[1].1))
.collect::<Vec<_>>()
.join(" ")
}
/// A story of `text` in `frames`, one paragraph (`para`: its keys) and one style (`style`).
fn story(text: &str, frames: &[usize], para: &str, style: &str) -> String {
let n = text.chars().count();
let frames: String = frames.iter().map(|f| format!("<< /0 {f} >> ")).collect();
format!(
"<< /0 << /0 ({text}) /5 << /0 [ << /0 << /0 << /0 () /5 << {para} >> /6 0 >> >> /1 {n} >> ] >> \
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << {style} >> >> >> /1 {n} >> ] >> >> /1 << /0 [ {frames}] >> >>"
)
}
/// A text document of `frames` and `stories` (written by [`story`]).
fn document_of(frames: &[String], stories: &[String]) -> String {
format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} ] >> >>\n/1 << /1 [ {} ] /2 << /1 12.0 >> >>\n",
frames.join(" "),
stories.join(" ")
)
}
/// A text object of frame `frame` of story `story`.
fn frame_object(story: u32, frame: u32) -> String {
format!("/AI11Text :\n0 /FreeUndo ,\n{frame} /FrameIndex ,\n{story} /StoryIndex ,\n;\n")
}
#[test]
fn area_type_and_type_on_a_path_come_from_the_text_document() {
let area = format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 /7 18 /8 18 >> >> >>", canvas_rect(10.0, 20.0, 60.0, 40.0));
// An open path of two segments, the type from halfway along the first to the end.
let (a, b, c) = (canvas(10.0, 70.0), canvas(30.0, 70.0), canvas(50.0, 70.0));
let path = format!(
"<< /0 << /0 [ 0 0 ] /1 << /0 [ {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} ] >> /2 << /0 2 /6 [ 0.5 2.0 ] >> >> >>",
a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1, b.0, b.1, b.0, b.1, c.0, c.1, c.0, c.1
);
let red = "/1 9.0 /8 50 /6 1.5 /53 << /99 /CAITextPaint /0 << /0 1 /1 [ 1.0 1.0 0.0 0.0 ] >> >>";
let doc = document_of(
&[area, path],
&[story("Area type\\rSecond\\r", &[0], "/0 2 /1 4 /2 6 /4 3", red), story("On a path\\r", &[1], "/0 0", "/1 8.0")],
);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &(text_object(0) + &text_object(1)))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 2, "{:?}", r.warnings);
let (area, path) = (texts[0], texts[1]);
assert_eq!(area.plain_text(), "Area type\nSecond");
let vectorcraft_doc::TextKind::Area { frame } = &area.kind else { panic!("area type: {:?}", area.kind) };
// Art y 20..40 is 60..80 down the 100 pt page.
let b = frame.bounds().unwrap();
assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 60.0).abs() < 1e-6 && (b.x1 - 60.0).abs() < 1e-6 && (b.y1 - 80.0).abs() < 1e-6, "{b:?}");
assert_eq!(area.para.justify, vectorcraft_doc::Justify::Center);
assert_eq!((area.para.first_line_indent, area.para.left_indent, area.para.space_before), (4.0, 6.0, 3.0));
let style = &area.runs[0].style;
assert_eq!((style.size, style.tracking, style.h_scale), (9.0, 50.0, 150.0));
assert_eq!(style.fill.color(), Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
let vectorcraft_doc::TextKind::OnPath { path: p, start, end } = &path.kind else { panic!("type on a path: {:?}", path.kind) };
assert!((start - 0.25).abs() < 1e-3 && end.is_none(), "{start} {end:?}");
assert_eq!(p.bounds().unwrap().width(), 40.0);
assert_eq!(path.runs[0].style.size, 8.0);
assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings);
}
#[test]
fn threaded_area_type_flows_through_its_frames() {
let frames = [
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(10.0, 60.0, 40.0, 80.0)),
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 60.0, 80.0, 80.0)),
];
let doc = document_of(&frames, &[story("A story in two frames\\r", &[0, 1], "/0 0", "/1 10.0")]);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &(frame_object(0, 0) + &frame_object(0, 1)))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 2, "{:?}", r.warnings);
assert_eq!(texts[0].plain_text(), "A story in two frames");
assert_eq!(texts[1].plain_text(), "");
let ids: Vec<_> = r.document.layers[1].children().unwrap().iter().map(|n| n.id).collect();
assert_eq!(r.document.text_threads, [ids]);
}
#[test]
fn shown_type_the_page_draws_in_pieces_comes_whole_from_the_text_document() {
// Type on a path the page draws letter by letter: the letters lie on the path, and only the
// text document's type object comes in.
let (a, b) = (canvas(10.0, 50.0), canvas(90.0, 50.0));
let path = format!(
"<< /0 << /0 [ 0 0 ] /1 << /0 [ {} {} {} {} {} {} {} {} ] >> /2 << /0 2 /6 [ 0 0.99 ] >> >> >>",
a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1
);
let doc = document_of(&[path], &[story("Letters\\r", &[0], "/0 0", "/1 12.0")]);
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
let letters: String = "Letters".chars().enumerate().map(|(i, c)| format!("{} 50 moveto ({c}) show ", 12 + 7 * i)).collect();
let page = format!("0 0 0 1 setcmykcolor /Helvetica findfont 12 scalefont setfont {letters}");
let r = import(&eps(&page, &art)).unwrap();
let mut all = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
all.push(t.plain_text());
}
});
assert_eq!(all, ["Letters"], "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("page's type")), "{:?}", r.warnings);
}
+103
View File
@@ -1,5 +1,6 @@
//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed
//! or interrupted write never leaves a damaged file behind (the old one stays as it was).
//! [`write_new_with`] creates a file the same way without ever replacing one.
use std::fs::{File, OpenOptions};
use std::io::{self, Write as _};
@@ -26,6 +27,48 @@ pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result
})
}
/// Create `path` with the content `fill` writes, never replacing a file or a link of that name. The
/// content goes to a temporary file beside it, which is then linked in under `path`
/// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was
/// taken meanwhile). The file appears whole or not at all. Where hard links fail for another
/// reason, `path` is created with `create_new` and the content copied in; a failed copy removes
/// it. The temporary file is always removed.
pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path))
}
/// [`write_new_with`], with `link` linking the temporary file in under `path`.
fn write_new_linking(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
link: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
let tmp = temp_path(path)?;
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
let filled = fill(&mut f).and_then(|()| f.sync_all());
drop(f);
let placed = filled.and_then(|()| match link(&tmp, path) {
Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path),
linked => linked,
});
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&tmp);
placed
}
/// Create `path` (never replacing anything) with the content of the file `from`; a failed copy
/// removes it again.
fn copy_new(from: &Path, path: &Path) -> io::Result<()> {
let mut to = OpenOptions::new().write(true).create_new(true).open(path)?;
let copied = File::open(from).and_then(|mut f| io::copy(&mut f, &mut to)).and_then(|_| to.sync_all());
drop(to);
if copied.is_err() {
// Best effort: the part copied is all there is to clean up.
let _ = std::fs::remove_file(path);
}
copied
}
/// A symbolic link keeps pointing at its file: write the file it names.
fn resolve_link(path: &Path) -> io::Result<PathBuf> {
match std::fs::symlink_metadata(path) {
@@ -93,4 +136,64 @@ mod tests {
assert!(write_atomic(&d.join("missing").join("x.vectorcraft"), b"x").is_err());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn write_new_never_replaces_what_is_there() {
let d = dir("new");
let path = d.join("a.otf");
write_new_with(&path, |f| f.write_all(b"first")).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"first");
assert!(leftovers(&d, "a.otf").is_empty(), "the temporary file is removed");
let r = write_new_with(&path, |f| f.write_all(b"second"));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert_eq!(std::fs::read(&path).unwrap(), b"first");
assert!(leftovers(&d, "a.otf").is_empty());
// A failed write leaves nothing.
let failed = d.join("b.otf");
assert!(write_new_with(&failed, |f| f.write_all(b"half").and(Err(io::Error::other("disk full")))).is_err());
assert!(!failed.exists() && leftovers(&d, "a.otf").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// Where hard links fail (a file system without them), the content is copied in, and a taken
/// name stays as it was. A link that fails because the name is taken copies nothing.
#[test]
fn write_new_copies_where_hard_links_fail() {
let d = dir("new-copy");
let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported));
let path = d.join("c.otf");
write_new_linking(&path, |f| f.write_all(b"copied"), unsupported).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"copied");
assert!(leftovers(&d, "c.otf").is_empty(), "the temporary file is removed");
let r = write_new_linking(&path, |f| f.write_all(b"second"), unsupported);
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert_eq!(std::fs::read(&path).unwrap(), b"copied");
let taken = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::AlreadyExists));
let other = d.join("d.otf");
let r = write_new_linking(&other, |f| f.write_all(b"other"), taken);
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert!(!other.exists() && leftovers(&d, "c.otf").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// A link of that name, even one to nothing, is never replaced or written through.
#[cfg(unix)]
#[test]
fn write_new_leaves_links_alone() {
let d = dir("new-links");
let target = d.join("target.otf");
std::fs::write(&target, b"target").unwrap();
std::os::unix::fs::symlink(&target, d.join("link.otf")).unwrap();
std::os::unix::fs::symlink(d.join("nothing.otf"), d.join("dangling.otf")).unwrap();
for name in ["link.otf", "dangling.otf"] {
let r = write_new_with(&d.join(name), |f| f.write_all(b"new"));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists), "{name}");
}
assert_eq!(std::fs::read(&target).unwrap(), b"target");
assert!(!d.join("nothing.otf").exists());
let mut names: Vec<String> = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
names.sort();
assert_eq!(names, ["dangling.otf", "link.otf", "target.otf"], "no temporary file is left");
let _ = std::fs::remove_dir_all(&d);
}
}
+1 -1
View File
@@ -43,7 +43,7 @@ use serde::{Deserialize, Serialize};
use vectorcraft_doc::{Document, ImageBlob};
#[cfg(not(target_arch = "wasm32"))]
pub use atomic::{write_atomic, write_atomic_with};
pub use atomic::{write_atomic, write_atomic_with, write_new_with};
/// v4: large data after the JSON (v1 to v3 files still load).
pub const VERSION: u32 = 4;
+18
View File
@@ -129,3 +129,21 @@ fn conventions_resources_and_versioned_results() {
rpc(&mut s, "initialize", json!({"protocolVersion":"2025-06-18"}));
assert!(rpc(&mut s, "tools/list", json!({}))["result"].get("resultType").is_none());
}
/// #785: a batch step can use an earlier step's result (`"$N.path"`); a reference to nothing
/// fails that step.
#[test]
fn batch_steps_refer_to_earlier_results() {
let mut s = Server::new(Box::new(Headless::with_document()));
let steps = json!([
{"id":"text.create","params":{"x":10,"y":60,"text":"plain and bold words","size":30}},
{"id":"shape.rectangle","params":{"x":0,"y":0,"width":20,"height":20}},
{"id":"text.setRangeStyle","params":{"id":"$0.id","start":10,"end":14,"style":"Bold"}},
{"id":"text.setRangeStyle","params":{"id":"$9.id","start":0,"end":1,"style":"Bold"}}
]);
let r = call(&mut s, "command_batch", json!({"steps":steps,"stop_on_error":false}));
let p = payload(&r);
assert_eq!((p["completed"].clone(), p["failed"].clone()), (json!(3), json!(1)), "{p}");
assert_eq!(p["results"][2]["result"]["id"], p["results"][0]["result"]["id"], "the text, not the selected rectangle");
assert!(p["results"][3]["error"].as_str().unwrap().contains("$9.id"), "{p}");
}
+6 -2
View File
@@ -96,7 +96,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"command_batch",
"Run several commands",
"Run steps in order; each edit is its own undo step. Returns completed, failed and results. Stops on the first error by default.",
"Run steps in order; each edit is its own undo step. A param string that is exactly \"$N.path\" (N: 0-based step index) or \"$last.path\" takes that value from an earlier step's result, e.g. {\"id\":\"$1.id\"}; \"$$\" starts a literal \"$\". Returns completed, failed and results. Stops on the first error by default.",
obj(
json!({"steps": {"type":"array", "items":obj(json!({"id":string("Command id"),"params":{"type":"object"}}), &["id"])}, "stop_on_error":{"type":"boolean", "default":true}}),
&["steps"],
@@ -899,6 +899,8 @@ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
Some(v) => v.as_bool().ok_or("`stop_on_error` must be a boolean")?,
};
let (mut completed, mut failed, mut results) = (0, 0, Vec::new());
// Each step's result (null for a failed one), for later steps' `"$N.path"` references.
let mut values: Vec<Value> = vec![];
for step in steps {
let result = vectorcraft_engine::guard::catch_panic(|| {
let args = step.as_object().ok_or("each step must be an object")?;
@@ -908,7 +910,7 @@ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
let id = req_str(args, "id")?;
let params = match args.get("params") {
None | Some(Value::Null) => json!({}),
Some(v @ Value::Object(_)) => v.clone(),
Some(v @ Value::Object(_)) => vectorcraft_engine::steps::resolve(v, &values)?,
Some(_) => return Err("`params` must be an object".into()),
};
b.call("engine.execute", json!({"command":id,"params":params}))
@@ -917,10 +919,12 @@ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
match result {
Ok(v) => {
completed += 1;
values.push(v.clone());
results.push(json!({"ok":true,"result":v}));
}
Err(e) => {
failed += 1;
values.push(Value::Null);
results.push(json!({"ok":false,"error":e}));
if stop {
break;
+26
View File
@@ -135,6 +135,9 @@ fn group_layer(
pub const OFF_ARTBOARD_NOTE: &str =
"only the PDF-compatible part of this file was read: art outside its artboards is kept in the editor's private data alone, so it doesn't open";
/// Warning: art reaching past the page box was clipped to it.
pub(crate) const PAST_PAGE_NOTE: &str = "art reaching past the page was clipped to it, as PDF viewers show it";
/// Import a PDF, returning the document plus warnings about content that was approximated or skipped.
pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportReport, PdfError> {
let original = crate::pages::open(bytes, opts.password.as_deref())?;
@@ -227,6 +230,29 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
}
parts.retain(|(_, art)| !art.is_empty());
}
// Viewers show a page through its crop box, so art reaching past it (a mock-up backdrop
// around the page, say) never showed. A clip to the page box that the file states is
// dropped as redundant (by hayro and by `push_clip_path`), so restore the box here:
// each object reaching past it keeps its own clip, which Fit to Artwork Bounds and
// `CropTo::Bounding` then respect.
// The crop box is what viewers show, whichever box the artboard takes. Not in a
// PDF-compatible `.ai`: its PDF part stands in for the editable document, whose art
// crossing the artboard edge isn't clipped, so it opens whole (#646).
let shown = xf.transform_rect_bbox(crate::pages::page_box(page, CropTo::Crop));
let page_box = shown.inflate(0.01, 0.01);
let mut clipped = false;
for (_, art) in parts.iter_mut().filter(|_| !ai) {
for n in art.iter_mut() {
if n.visual_bounds().is_some_and(|r| !contains(page_box, r)) {
let clip = Arc::new(b.clip_node(&shown.to_path(0.1), FillRule::NonZero));
*n = Arc::new(Node::new(b.id(), NodeKind::Group { children: vec![clip, n.clone()], clip: true }));
clipped = true;
}
}
}
if clipped {
b.warn(PAST_PAGE_NOTE);
}
let children: Vec<Arc<Node>> = parts.iter().flat_map(|(_, v)| v.iter().cloned()).collect();
placeholder &= ai && only_text(&children);
let mut right = ab.x1;
+18
View File
@@ -446,3 +446,21 @@ fn a_stroke_under_a_stretched_transform_stays_a_stroke() {
let b = objs[0].geometric_bounds().unwrap();
assert!((b.x0 - 20.0).abs() < 1e-6 && (b.x1 - 80.0).abs() < 1e-6, "{b:?}");
}
#[test]
fn art_past_the_page_clip_keeps_the_clip() {
// A page-sized clip, then a backdrop far larger than the page and a square on it: the square
// needs no clip, the backdrop keeps it, so the art's bounds stay on the page.
let r = open_with(&one_page("0 0 100 100 re W n 0 g -500 -500 1100 1100 re f 1 0 0 rg 10 10 20 20 re f", "", &[]), |_| {});
let d = &r.document;
let art = d.art_bounds().expect("art");
assert!(art.x0 >= -0.01 && art.y0 >= -0.01 && art.x1 <= 100.01 && art.y1 <= 100.01, "the art stays on the page: {art:?}");
let clips: Vec<Node> = all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).collect();
let [c] = clips.as_slice() else { panic!("one clip group, the backdrop's: {clips:?}") };
assert_eq!(c.children().map(Vec::len), Some(2), "the clip path and the backdrop");
assert!(r.warnings.iter().any(|w| w == crate::import::PAST_PAGE_NOTE), "{:?}", r.warnings);
// Art inside the page gets no clip and no warning.
let r = open_with(&one_page("0 0 100 100 re W n 1 0 0 rg 10 10 20 20 re f", "", &[]), |_| {});
assert!(!all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })));
assert!(!r.warnings.iter().any(|w| w == crate::import::PAST_PAGE_NOTE), "{:?}", r.warnings);
}
+19
View File
@@ -367,6 +367,25 @@ fn art_past_the_scan_limit_of_shown_layers_stays_shown() {
assert!(r.warnings.iter().any(|w| w.contains("went to its page's layer")), "{:?}", r.warnings);
}
/// Art reaching past the page keeps a clip to it in a plain PDF (as viewers show it), but not in
/// a PDF-compatible `.ai`, whose art crossing the artboard edge opens whole and editable (#646).
#[test]
fn art_past_the_page_is_clipped_in_a_pdf_but_not_in_an_ai_file() {
for ai in [false, true] {
let page = PdfPage {
entries: if ai { "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into() } else { String::new() },
..PdfPage::new(100.0, 100.0, "0 0 100 100 re W n 1 0 0 rg 50 50 200 200 re f")
};
let r = import_with_report(&pdf_with_catalog(&[page], &[], "", None), &ImportOptions::default()).unwrap();
let mut clips = 0;
r.document.walk(|n| clips += usize::from(matches!(n.kind, NodeKind::Group { clip: true, .. })));
let past = r.warnings.iter().any(|w| w == crate::import::PAST_PAGE_NOTE);
assert_eq!((clips, past), if ai { (0, false) } else { (1, true) }, "ai: {ai}: {:?}", r.warnings);
let art = r.document.art_bounds().unwrap();
assert_eq!(art.x1 > 100.5, ai, "ai: {ai}: {art:?}");
}
}
/// The editor's private data of a `.ai` is its `AIPrivateData` streams, joined in order.
#[test]
fn an_ai_files_private_data_is_its_streams_joined() {
+3 -1
View File
@@ -87,7 +87,7 @@ impl RasterExportOptions {
}
/// What the renderer draws for `format`: template layers and guides left out, over the background
/// (white for a JPEG or a flat PSD without one).
/// (white for a JPEG or a flat PSD without one), composited in floating point.
pub fn render_options(&self, format: RasterFormat) -> RenderOptions {
let flat = format == RasterFormat::Jpeg || (format == RasterFormat::Psd && !self.psd.layers);
let background = self.background.or(flat.then_some([255; 3]));
@@ -95,6 +95,8 @@ impl RasterExportOptions {
background: background.map(|[r, g, b]| [r, g, b, 255]),
skip_templates: true,
anti_alias: self.anti_alias,
// Opaque art stays exactly opaque where translucent edges cross it (#787).
precise: true,
..Default::default()
}
}
+38
View File
@@ -110,6 +110,44 @@ fn backgrounds_are_opaque_or_transparent() {
assert_eq!(webp.get_pixel(0, 0).0, [0, 0, 0, 255]);
}
/// #787: translucent art over opaque art (or a background) stays exactly opaque, its anti-aliased
/// edges too, so the file is written as RGB.
#[test]
fn translucent_edges_over_opaque_art_stay_opaque() {
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let under = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
let mut over =
Node::path(d.alloc_id(), shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 90.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
over.opacity = 0.5;
let only_over = {
let mut d = d.clone();
d.insert(Some(l), 0, over.clone()).unwrap();
d
};
d.insert(Some(l), 0, under).unwrap();
d.insert(Some(l), 1, over).unwrap();
// Over a black background at 72 ppi, and over an opaque rectangle at a scale that puts the
// edges on fractions of a pixel.
for (doc, o) in [
(&only_over, RasterExportOptions { background: Some([0, 0, 0]), ..Default::default() }),
(&d, RasterExportOptions { ppi: 72.0 * 0.3515625, ..Default::default() }),
] {
let png = Renderer::new().export_region(doc, doc.artboards[0].rect, RasterFormat::Png, &o).unwrap();
let img = image::load_from_memory(&png).unwrap().to_rgba8();
let below: Vec<_> = img.pixels().filter(|p| p[3] < 255).collect();
assert!(below.is_empty(), "ppi {}: {} pixels below alpha 255, e.g. {:?}", o.ppi, below.len(), below.first());
assert_eq!(png[25], 2, "IHDR colour type: RGB");
}
// The inside is half white over black.
let img = export(&only_over, RasterFormat::Png, &RasterExportOptions { background: Some([0, 0, 0]), ..Default::default() });
assert!(img.get_pixel(50, 50).0[..3].iter().all(|c| (127..=128).contains(c)), "{:?}", img.get_pixel(50, 50));
}
#[test]
fn interlaced_export_decodes_to_the_same_pixels() {
let d = circle_doc();
+5 -41
View File
@@ -187,10 +187,6 @@ fn shadow_filter(dx: f64, dy: f64, blur: f64, color: peniko::Color) -> Filter {
})
}
fn blur_filter(sigma: f64) -> Filter {
Filter::from_primitive(FilterPrimitive::GaussianBlur { std_deviation: sigma.max(0.0) as f32, edge_mode: EdgeMode::None })
}
fn pcolor(ink: Ink, c: &vectorcraft_doc::color::Color) -> peniko::Color {
let [r, g, b] = ink.rgb(c);
peniko::Color::new([r, g, b, 1.0])
@@ -495,44 +491,12 @@ impl Renderer {
c.pop_layer();
});
}
// The content itself (blurred / feathered / filtered).
let blur: f64 = rfx
.iter()
.map(|fx| match fx {
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => radius.max(0.0),
_ => 0.0,
})
.sum();
if rfx.iter().any(|fx| matches!(fx, RasterFx::Pixel(_))) {
// The content itself (blurred / feathered / filtered), on its pixels: a filter layer's blur
// works on a coarser grid tied to the canvas, so the blurred art shifted by up to a pixel
// and looked blocky as the view moved by parts of a pixel (#755).
let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } if *radius > 0.0));
if blurs || rfx.iter().any(|fx| matches!(fx, RasterFx::Pixel(_))) {
self.pixel_content(ctx, f, content, rfx, paint);
} else if blur > 0.0 {
self.with_filters(ctx, f, reach, blur, None, |r, c, fr, _| {
let mut layers = 0;
for fx in rfx {
match fx {
RasterFx::Feather { radius } if *radius > 0.0 => {
c.set_transform(fr.view);
if let Some((g, rule)) = content.outline {
c.set_fill_rule(fill_rule(rule));
c.push_clip_layer(g);
layers += 1;
}
c.push_layer(None, None, None, None, Some(blur_filter(radius / 2.0)));
layers += 1;
}
RasterFx::GaussianBlur { radius } if *radius > 0.0 => {
c.set_transform(fr.view);
c.push_layer(None, None, None, None, Some(blur_filter(radius / 2.0)));
layers += 1;
}
_ => {}
}
}
paint(r, c, fr);
for _ in 0..layers {
c.pop_layer();
}
});
} else {
paint(self, ctx, f);
}
+2 -2
View File
@@ -137,7 +137,7 @@ impl Renderer {
fn flatten(&mut self, ctx: &mut RenderContext, r: Region) -> Arc<Pixmap> {
ctx.flush();
let mut all = Pixmap::new(ctx.width(), ctx.height());
ctx.render(&mut all, &mut self.resources);
ctx.render_with(&mut all, &mut self.resources, self.raster);
ctx.reset();
let crop = if (r.x, r.y, r.w, r.h) == (0, 0, all.width(), all.height()) {
None
@@ -171,7 +171,7 @@ impl Renderer {
(self.nested, self.backdrop, self.clip_paths) = outer;
ctx.flush();
let mut pm = Pixmap::new(r.w, r.h);
ctx.render(&mut pm, &mut self.resources);
ctx.render_with(&mut pm, &mut self.resources, self.raster);
pm
}
+85 -2
View File
@@ -107,8 +107,18 @@ pub struct RenderOptions {
/// 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,
/// Screen view in isolation mode: the isolated group or layer. Everything around it draws
/// dimmed ([`ISOLATION_DIM`]).
pub isolated: Option<NodeId>,
/// Composite in floating point (exports): translucent art over opaque art comes out exactly
/// opaque, where 8-bit compositing leaves alpha 254 on some anti-aliased edges (#787). Off,
/// the faster 8-bit pipeline (the canvas).
pub precise: bool,
}
/// The opacity of the art around an isolated group or layer.
pub const ISOLATION_DIM: f32 = 0.5;
/// How edges are rasterized (raster export option).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AntiAlias {
@@ -174,6 +184,8 @@ impl Default for RenderOptions {
progressive_placed: false,
trace_views: false,
smooth_images: true,
isolated: None,
precise: false,
}
}
}
@@ -355,6 +367,14 @@ pub struct Renderer {
/// Inline graphics being drawn inside inline graphics (a symbol whose art holds text showing
/// it): drawing stops at [`MAX_INLINE_DEPTH`].
inline_depth: u32,
/// How the frame being drawn is rasterized ([`RenderOptions::precise`]): its offscreen groups,
/// masks and patterns too.
raster: vello_cpu::RasterizerSettings,
/// [`RenderOptions::isolated`]'s layers and groups, from the top layer down to it, for the
/// frame (`stamp`) and document they were found in.
isolation: Option<(u64, usize, NodeId, Vec<NodeId>)>,
/// Drawing inside the isolated container or a dimmed object: nothing further dims.
isolation_settled: bool,
}
/// How deep inline graphics nest (text in a symbol shown inline in text…) before they draw nothing.
@@ -441,6 +461,9 @@ impl Renderer {
adjusted: Default::default(),
dim_images: None,
inline_depth: 0,
raster: vello_cpu::RasterizerSettings::default(),
isolation: None,
isolation_settled: false,
}
}
@@ -518,6 +541,8 @@ impl Renderer {
};
// `reset` keeps the threshold of the previous render: set it every time.
ctx.set_aliasing_threshold(opts.anti_alias.threshold());
let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed };
self.raster = vello_cpu::RasterizerSettings { render_mode, ..Default::default() };
if let Some(bg) = opts.background {
ctx.set_transform(Affine::IDENTITY);
ctx.set_paint(f.ink.fixed(bg));
@@ -546,7 +571,7 @@ impl Renderer {
}
ctx.flush();
let mut pm = Pixmap::new(w, h);
ctx.render(&mut pm, &mut self.resources);
ctx.render_with(&mut pm, &mut self.resources, self.raster);
if threads == 0 {
self.ctx_st = Some(ctx);
} else {
@@ -781,7 +806,7 @@ impl Renderer {
(self.knockout, self.nested, self.backdrop, self.clip_paths) = outer;
mctx.flush();
let mut pm = Pixmap::new(w, h);
mctx.render(&mut pm, &mut self.resources);
mctx.render_with(&mut pm, &mut self.resources, self.raster);
pm.data().iter().map(|p| mask_value(p.r, p.g, p.b, p.a, m.clip, m.invert)).collect()
}
@@ -876,6 +901,46 @@ impl Renderer {
/// [`Self::draw_node`] after culling and Layer Options.
fn draw_layer_node(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node) {
// Isolation mode: the art around the isolated container draws dimmed (#833).
if let Some((isolated, path)) = self.isolation_path(f) {
// A container on the way down to it draws as usual: its members decide.
if path.contains(&n.id) && n.id != isolated {
return self.draw_layer_node_now(ctx, f, n);
}
self.isolation_settled = true;
if n.id == isolated {
self.draw_layer_node_now(ctx, f, n);
} else {
self.dimmed(ctx, f, &mut |r, c, fr| r.draw_layer_node_now(c, fr, n));
}
self.isolation_settled = false;
return;
}
self.draw_layer_node_now(ctx, f, n);
}
/// In isolation mode, while drawing outside the isolated container and the art dimmed around
/// it: the isolated container and its layers and groups, from the top layer down to it.
fn isolation_path(&mut self, f: &Frame) -> Option<(NodeId, Vec<NodeId>)> {
let isolated = f.opts.isolated.filter(|_| !self.isolation_settled)?;
let doc = std::ptr::from_ref(f.doc) as usize;
if !self.isolation.as_ref().is_some_and(|(stamp, d, id, _)| (*stamp, *d, *id) == (self.stamp, doc, isolated)) {
self.isolation = Some((self.stamp, doc, isolated, f.doc.ancestry(isolated).unwrap_or_default()));
}
let path = self.isolation.as_ref().map(|(.., path)| path.clone()).filter(|p| !p.is_empty())?;
Some((isolated, path))
}
/// `draw` at [`ISOLATION_DIM`], with nothing inside dimmed again.
fn dimmed(&mut self, ctx: &mut RenderContext, f: &Frame, draw: &mut group::Content) {
let settled = std::mem::replace(&mut self.isolation_settled, true);
let comp = Composite { opacity: ISOLATION_DIM, ..Default::default() };
self.group(ctx, f, comp, draw);
self.isolation_settled = settled;
}
/// [`Self::draw_layer_node`] past isolation mode's dimming.
fn draw_layer_node_now(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node) {
if fx::has_object_fx(n) {
return self.draw_object_fx(ctx, f, &Arc::new(n.clone()), false);
}
@@ -998,6 +1063,22 @@ impl Renderer {
fn draw_children(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>], knockout: bool) {
if knockout {
self.draw_knockout(ctx, f, children);
} else if let Some((_, path)) = self.isolation_path(f) {
// Isolation mode, in a container on the way down to the isolated one: each run of
// members around it draws dimmed as one (#833).
let mut rest = children;
while let Some(i) = rest.iter().position(|c| path.contains(&c.id)) {
let (around, from) = rest.split_at(i);
if !around.is_empty() {
self.dimmed(ctx, f, &mut |r, c, fr| around.iter().for_each(|n| r.draw_arc(c, fr, n)));
}
let Some((on_path, after)) = from.split_first() else { break };
self.draw_arc(ctx, f, on_path);
rest = after;
}
if !rest.is_empty() {
self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n)));
}
} else {
for c in children {
self.draw_arc(ctx, f, c);
@@ -1760,6 +1841,8 @@ mod tests_fontchange;
#[cfg(test)]
mod tests_freeform;
#[cfg(test)]
mod tests_fxzoom;
#[cfg(test)]
mod tests_isolation;
#[cfg(test)]
mod tests_knockout;
+1 -1
View File
@@ -88,7 +88,7 @@ fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, w
}
ctx.flush();
let mut pm = Pixmap::new(w, h);
ctx.render(&mut pm, &mut r.resources);
ctx.render_with(&mut pm, &mut r.resources, r.raster);
pm
}
+142
View File
@@ -0,0 +1,142 @@
//! Raster effects stay where they are, and look the same, at every zoom and pan (#755).
use serde_json::json;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::text::{CharStyle, TextObject};
use vectorcraft_doc::{Appearance, Effect, Node, NodeKind};
use vectorcraft_geom::{Point, shapes};
use super::*;
/// Type blurred by `radius` points (Gaussian Blur, or Feather when `feather`) over a rectangle
/// that overlays at half opacity; without the type when `radius` is `None`.
fn scene(radius: Option<f64>, feather: bool) -> Document {
let mut d = Document::new(200.0, 100.0);
let l = d.layers[0].id;
let mut back = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)),
Appearance::basic(Paint::solid(Color::rgb(0.2, 0.4, 0.9)), Paint::None, 0.0),
);
back.blend = BlendMode::Overlay;
back.opacity = 0.5;
d.insert(Some(l), 0, back).unwrap();
if let Some(radius) = radius {
let style = CharStyle { size: 36.0, ..CharStyle::default() };
let mut t = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(30.0, 60.0), "Hello", style))));
let id = if feather { "stylize.feather" } else { "blur.gaussian" };
t.appearance.effects.push(Effect { id: id.into(), params: json!({"radius": radius}), visible: true });
d.insert(Some(l), 1, t).unwrap();
}
d
}
/// `d` with its layer's art in one group: the overlay and the type grouped, as in #755's report.
fn grouped(mut d: Document) -> Document {
let l = d.layers[0].id;
let id = d.alloc_id();
let members = d.children_mut(Some(l)).map(std::mem::take).unwrap();
d.insert(Some(l), 0, Node::new(id, NodeKind::Group { children: members, clip: false })).unwrap();
d
}
/// The canvas's options: art on nothing, no artboards.
fn screen() -> RenderOptions {
RenderOptions { background: None, artboards: false, ..Default::default() }
}
fn render(d: &Document, threads: u16, view: Affine, (w, h): (u32, u32)) -> Rendered {
let mut r = Renderer::new();
r.threads = threads;
r.render(d, w, h, view, &screen())
}
/// Where the type's ink is on the document (its centroid), rendered `threads`-threaded through
/// `view` on a `w` × `h` canvas.
fn ink_centre(radius: f64, threads: u16, view: Affine, size: (u32, u32)) -> Point {
let with = render(&scene(Some(radius), false), threads, view, size);
let without = render(&scene(None, false), threads, view, size);
let (mut sx, mut sy, mut sw) = (0.0, 0.0, 0.0);
for (i, (p, q)) in with.pixels.chunks(4).zip(without.pixels.chunks(4)).enumerate() {
let d: f64 = (0..4).map(|c| f64::from(p[c].abs_diff(q[c]))).sum();
let (x, y) = ((i % size.0 as usize) as f64 + 0.5, (i / size.0 as usize) as f64 + 0.5);
sx += d * x;
sy += d * y;
sw += d;
}
assert!(sw > 0.0, "the type shows");
view.inverse() * Point::new(sx / sw, sy / sw)
}
#[test]
fn blurred_type_stays_in_place_at_every_zoom_and_pan() {
for (radius, threads) in [(3.0, 0), (3.0, 4), (12.0, 0), (12.0, 4)] {
let base = ink_centre(radius, threads, Affine::IDENTITY, (200, 100));
// The whole document in view, at other zooms and moved by parts of a pixel.
for (zoom, pan) in
[(1.0, (13.3, 7.6)), (2.0, (41.7, 20.2)), (3.3, (15.25, 9.5)), (0.5, (10.4, 5.1)), (6.0, (30.6, 25.3)), (1.37, (0.5, 0.25))]
{
let view = Affine::translate(pan) * Affine::scale(zoom);
let size = ((200.0 * zoom + 2.0 * pan.0).ceil() as u32, (100.0 * zoom + 2.0 * pan.1).ceil() as u32);
let at = ink_centre(radius, threads, view, size);
assert!(
(at.x - base.x).abs() < 1.0 && (at.y - base.y).abs() < 1.0,
"radius {radius}, threads {threads}, zoom {zoom}, pan {pan:?}: {at:?} vs {base:?}"
);
}
}
}
/// Scrolling moves the blurred type with the page and nothing else: two views a whole number of
/// pixels apart draw the same pixels where they overlap, whether the type fits on the canvas or
/// runs off it.
#[test]
fn scrolling_moves_blurred_type_without_changing_it() {
for (feather, group) in [(false, false), (true, false), (false, true)] {
let d = scene(Some(12.0), feather);
let d = if group { grouped(d) } else { d };
for threads in [0, 4] {
for (zoom, (w, h)) in [(1.0, (240, 140)), (4.0, (500, 300)), (8.0, (400, 300))] {
let at = |dx: f64, dy: f64| render(&d, threads, Affine::translate((-dx, -dy)) * Affine::scale(zoom), (w, h));
let a = at(20.0, 10.0);
for (sx, sy) in [(1u32, 0u32), (3, 2), (37, 23), (101, 57)] {
let b = at(20.0 + f64::from(sx), 10.0 + f64::from(sy));
let mut worst = 0;
for y in sy..h {
for x in sx..w {
let i = ((y * w + x) * 4) as usize;
let j = (((y - sy) * w + x - sx) * 4) as usize;
for c in 0..4 {
worst = worst.max(a.pixels[i + c].abs_diff(b.pixels[j + c]));
}
}
}
assert!(
worst <= 3,
"feather {feather}, grouped {group}, threads {threads}, zoom {zoom}, scrolled by ({sx}, {sy}): a pixel changed by {worst}"
);
}
}
}
}
}
/// Scrolling by parts of a pixel (a trackpad, a zoom about the pointer) moves heavily blurred type
/// by just that: its ink stays put on the page within a tenth of a pixel, at any zoom.
#[test]
fn blurred_type_doesnt_wobble_as_the_view_moves_by_parts_of_a_pixel() {
for threads in [0, 4] {
for zoom in [1.0, 4.0] {
let at = |p: f64| {
ink_centre(30.0, threads, Affine::translate((400.0 - 75.0 * zoom + p, 330.0 - 48.0 * zoom + p)) * Affine::scale(zoom), (800, 660))
};
let base = at(0.0);
for k in 1..10 {
let c = at(f64::from(k) * 0.1);
// How far it moved on the screen, besides the view's own move.
let (dx, dy) = ((c.x - base.x) * zoom, (c.y - base.y) * zoom);
assert!(dx.abs() < 0.1 && dy.abs() < 0.1, "threads {threads}, zoom {zoom}, moved by {}: off by ({dx}, {dy}) px", f64::from(k) * 0.1);
}
}
}
}
+27
View File
@@ -218,3 +218,30 @@ fn copying_the_backdrop_changes_nothing_without_blending() {
let worst = a.iter().zip(&b).map(|(x, y)| (*x as i32 - *y as i32).abs()).max().unwrap();
assert!(worst <= 1, "differs by {worst}/255");
}
/// Isolation mode (#833): the art around the isolated group draws at half opacity, above it as
/// well as below; the group's own art as usual.
#[test]
fn isolation_mode_dims_the_art_around_the_isolated_group() {
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let below = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), [0.0, 0.0, 0.0]);
let inside = rect(&mut d, Rect::new(60.0, 60.0, 100.0, 100.0), [0.0, 0.0, 0.0]);
let above = rect(&mut d, Rect::new(60.0, 0.0, 100.0, 40.0), [0.0, 0.0, 0.0]);
let g = group(&mut d, vec![inside], 1.0, Blend::Normal, false);
let gid = g.id;
for n in [below, g, above] {
d.insert(Some(l), usize::MAX, n).unwrap();
}
let alpha = |img: &Rendered, x: usize, y: usize| img.pixels[(y * 100 + x) * 4 + 3];
let plain = render(&d);
let isolated = |id| render_with(&mut Renderer::new(), &d, &RenderOptions { isolated: Some(id), ..Default::default() });
let dimmed = isolated(gid);
assert_eq!(alpha(&dimmed, 80, 80), 255, "the isolated group's art");
for (x, y) in [(20, 20), (80, 20)] {
assert_eq!(alpha(&plain, x, y), 255);
assert!((120..=135).contains(&alpha(&dimmed, x, y)), "({x}, {y}): {}", alpha(&dimmed, x, y));
}
// An object that isn't in the document dims nothing.
assert_eq!(isolated(NodeId(u64::MAX)).pixels, plain.pixels);
}
+69
View File
@@ -0,0 +1,69 @@
//! Font files for tests, made from the bundled fonts when a test runs: no font file is committed.
/// The bundled Source Sans 3 Regular with its family renamed `family` in every record of its name
/// table, UTF-16 and ASCII alike. `family` must be as long as "Source Sans 3" (13 bytes). The
/// PostScript name stays `SourceSans3-Regular`.
pub fn renamed(family: &str) -> Vec<u8> {
const ORIGINAL: &str = "Source Sans 3";
assert_eq!(family.len(), ORIGINAL.len(), "`{family}` must be 13 bytes long");
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
let mut data = std::fs::read(path).unwrap();
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(utf16(ORIGINAL), utf16(family)), (ORIGINAL.as_bytes().to_vec(), family.as_bytes().to_vec())] {
let mut i = 0;
while let Some(at) = data[i..].windows(from.len()).position(|w| w == from) {
data[i + at..i + at + to.len()].copy_from_slice(&to);
i += at + to.len();
}
}
data
}
/// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as a font
/// utility writes a suitcase font's fork, and as vectorcraft-text's suitcase tests build one. macOS
/// keeps a file's resource fork at `<file>/..namedfork/rsrc`.
pub fn suitcase_fork(fonts: &[Vec<u8>]) -> Vec<u8> {
let mut data = Vec::new();
let mut offsets = Vec::new();
for body in fonts.iter().map(Vec::as_slice).chain([&b"1.0"[..]]) {
offsets.push(data.len() as u32);
data.extend_from_slice(&(body.len() as u32).to_be_bytes());
data.extend_from_slice(body);
}
let n = fonts.len();
// The type list: `vers` (1 resource) then `sfnt`, each entry pointing at its references.
let list = 2 + 2 * 8;
let mut types = Vec::new();
types.extend_from_slice(&1u16.to_be_bytes());
types.extend_from_slice(b"vers");
types.extend_from_slice(&0u16.to_be_bytes());
types.extend_from_slice(&(list as u16).to_be_bytes());
types.extend_from_slice(b"sfnt");
types.extend_from_slice(&((n - 1) as u16).to_be_bytes());
types.extend_from_slice(&((list + 12) as u16).to_be_bytes());
let reference = |id: i16, offset: u32| {
let mut r = Vec::new();
r.extend_from_slice(&id.to_be_bytes());
r.extend_from_slice(&0xFFFFu16.to_be_bytes());
r.extend_from_slice(&offset.to_be_bytes());
r.extend_from_slice(&[0; 4]);
r
};
types.extend(reference(1, offsets[n]));
for (i, o) in offsets[..n].iter().enumerate() {
types.extend(reference(5000 + i as i16, *o));
}
// The map: a copy of the header, a handle, attributes, then the offsets of the lists.
let mut map = vec![0; 24];
map.extend_from_slice(&28u16.to_be_bytes());
map.extend_from_slice(&((28 + types.len()) as u16).to_be_bytes());
map.extend(types);
let mut fork = Vec::new();
for v in [256u32, 256 + data.len() as u32, data.len() as u32, map.len() as u32] {
fork.extend_from_slice(&v.to_be_bytes());
}
fork.resize(256, 0);
fork.extend(data);
fork.extend(map);
fork
}
+2
View File
@@ -12,6 +12,7 @@
//! - [`pdf`]: hand-written PDF files (page boxes, colour spaces, encryption) for import tests.
//! - [`ai`]: hand-written Illustrator editing data, and the EPS and `.ai` files that carry it.
//! - [`ase`]: hand-written swatch exchange (`.ase`) files for swatch library tests.
//! - [`fonts`]: font files made from the bundled fonts (a renamed family) for font tests.
//!
//! This crate may only be used as a dev-dependency (enforced by `cargo xtask layers`).
// Test support only (a dev-dependency of every crate that uses it): a failed setup or assertion
@@ -23,6 +24,7 @@
pub mod ai;
pub mod ase;
pub mod fixtures;
pub mod fonts;
pub mod geom;
pub mod invariants;
pub mod pdf;
+208 -15
View File
@@ -801,28 +801,45 @@ fn font_files(path: &Path) -> Vec<Vec<u8>> {
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
/// The styles of every face in the font file at `path` ([`face_styles`]), reading only its table
/// directories and `name` and `fvar` tables: a scan opens hundreds of font files, many of them
/// megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table) are
/// left out.
/// directories and `name`, `fvar` and `OS/2` tables: a scan opens hundreds of font files, many of
/// them megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table)
/// are left out.
#[cfg(not(target_arch = "wasm32"))]
fn file_face_names(path: &Path) -> Vec<FaceStyle> {
/// The most faces read from a (possibly damaged) collection.
const MAX_FACES: u32 = 256;
file_face_names_within(path, MAX_FACES, u64::MAX)
}
/// [`file_face_names`], reading at most `max_faces` faces and `max_read` bytes of the file in all.
/// A suitcase font's resource fork is read whole when it is at most `max_read` bytes long, and the
/// limits then apply to each of its fonts; a longer fork gives none.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn file_face_names_within(path: &Path, max_faces: u32, max_read: u64) -> Vec<FaceStyle> {
if crate::suitcase::is_suitcase(path) {
return crate::suitcase::read_fonts(path).into_iter().flat_map(|font| reader_face_names(std::io::Cursor::new(font))).collect();
if crate::suitcase::fork_len(path) > max_read {
return vec![];
}
return crate::suitcase::read_fonts(path)
.into_iter()
.flat_map(|font| reader_face_names_within(std::io::Cursor::new(font), max_faces, max_read))
.collect();
}
match std::fs::File::open(path) {
Ok(file) => reader_face_names(file),
Ok(file) => reader_face_names_within(file, max_faces, max_read),
Err(_) => vec![],
}
}
/// [`file_face_names`] for the font file `file` reads.
/// [`file_face_names_within`] for the font file `file` reads.
#[cfg(not(target_arch = "wasm32"))]
fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceStyle> {
fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, max_read: u64) -> Vec<FaceStyle> {
use std::io::SeekFrom;
/// Caps on what a (possibly damaged) file can make the scan read.
const MAX_FACES: u32 = 256;
/// The largest table read from a (possibly damaged) file.
const MAX_NAME_TABLE: u32 = 1 << 20;
let mut read = 0u64;
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?;
let mut buf = vec![0; len];
file.seek(SeekFrom::Start(offset)).ok()?;
file.read_exact(&mut buf).ok()?;
@@ -832,7 +849,7 @@ fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceSt
let Some(head) = read_at(0, 12) else { return vec![] };
// A collection lists where each face's table directory starts.
let starts: Vec<u32> = if head.starts_with(b"ttcf") {
let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize;
let n = be32(&head, 8).unwrap_or(0).min(max_faces) as usize;
read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default()
} else {
vec![0]
@@ -874,6 +891,157 @@ fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceSt
.collect()
}
/// Whether the file at `path` is a font file by its extension (`.ttf`, `.otf`, `.ttc` or `.otc`,
/// in any case), as the font scan reads the files in a folder.
pub fn is_font_file(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| ["ttf", "otf", "ttc", "otc"].iter().any(|x| e.eq_ignore_ascii_case(x)))
}
/// Whether the file at `path` is a suitcase font ([`crate::suitcase`]): on macOS, a file with
/// nothing in its data and its fonts in its resource fork. Never on the web.
pub fn is_suitcase(path: &Path) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
crate::suitcase::is_suitcase(path)
}
#[cfg(target_arch = "wasm32")]
{
let _ = path;
false
}
}
/// A font a document names that isn't available, to look for in font files ([`WantedFonts`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WantedFont {
pub family: String,
pub style: String,
/// When the family is installed but not the style ([`FontMatch::Style`]): the family of the
/// face [`FontDb::resolve`] gives instead. `None` when the family is missing.
pub installed: Option<String>,
}
/// Fonts to look for in font files: [`WantedFonts::provided_by`] tells which of them a file
/// provides.
#[derive(Debug, Default)]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub struct WantedFonts {
fonts: Vec<WantedFont>,
/// The indexes of the fonts by every name a face could answer to them by: the family as given
/// and the installed family (ASCII-lowercased), and the family normalized ([`norm`]).
by_name: HashMap<String, Vec<usize>>,
}
impl WantedFonts {
/// The most faces and bytes of one file a search reads.
#[cfg(not(target_arch = "wasm32"))]
const SEARCH_FACES: u32 = 64;
#[cfg(not(target_arch = "wasm32"))]
const SEARCH_READ: u64 = 8 << 20;
pub fn new(fonts: &[WantedFont]) -> Self {
let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
for (i, w) in fonts.iter().enumerate() {
let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family)];
names.extend(w.installed.as_ref().map(|c| c.to_ascii_lowercase()));
names.sort();
names.dedup();
for n in names.into_iter().filter(|n| !n.is_empty()) {
by_name.entry(n).or_default().push(i);
}
}
Self { fonts: fonts.to_vec(), by_name }
}
pub fn len(&self) -> usize {
self.fonts.len()
}
pub fn is_empty(&self) -> bool {
self.fonts.is_empty()
}
/// The indexes of the fonts that the font file at `path` provides: copied into a folder the
/// font scan reads, the file makes [`FontDb::resolve`] find each of them exactly, in one of its
/// faces or a variable font's named instances. The file is read as the scan reads it (its
/// table directories and its `name`, `fvar` and `OS/2` tables), at most 64 faces and 8 MB of
/// it, when it is a font file by its extension ([`is_font_file`]) or a suitcase font whose
/// resource fork is at most 8 MB long. Sorted; none on the web.
pub fn provided_by(&self, path: &Path) -> Vec<usize> {
#[cfg(not(target_arch = "wasm32"))]
{
if !is_font_file(path) && !crate::suitcase::is_suitcase(path) {
return Vec::new();
}
let faces = file_face_names_within(path, Self::SEARCH_FACES, Self::SEARCH_READ);
self.provided_by_faces(&faces)
}
#[cfg(target_arch = "wasm32")]
{
let _ = path;
Vec::new()
}
}
/// [`Self::provided_by`] for the faces of a file.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn provided_by_faces(&self, faces: &[FaceStyle]) -> Vec<usize> {
let mut candidates: Vec<usize> = Vec::new();
for f in faces {
let names = std::iter::once(f.family.to_ascii_lowercase())
.chain(f.keys.families.iter().cloned())
.chain(f.keys.legacy.iter().map(|(family, _)| family.clone()))
.chain(f.keys.postscript.iter().cloned());
for n in names {
candidates.extend(self.by_name.get(&n).into_iter().flatten());
}
}
candidates.sort_unstable();
candidates.dedup();
candidates.retain(|i| self.fonts.get(*i).is_some_and(|w| provides(w, faces)));
candidates
}
}
/// Whether the faces of a font file, cataloged by a rescan, make [`FontDb::resolve`] find `w`
/// exactly in one of them: [`FontDb::canonical`] and [`FontDb::find`] over these faces, as they
/// would run once the file is cataloged.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn provides(w: &WantedFont, faces: &[FaceStyle]) -> bool {
let sk = norm(&w.style);
// A face of `family` with the style among its style names, as `find` looks for it once the
// family's files are loaded.
let styled = |family: &str| faces.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.keys.styles.contains(&sk));
let named_as_given = faces.iter().any(|f| f.family.eq_ignore_ascii_case(&w.family));
if let Some(installed) = &w.installed {
// A family cataloged by the name as given is found by it.
if named_as_given && !w.family.eq_ignore_ascii_case(installed) {
return styled(&w.family);
}
// The installed family is loaded: a face of it is loaded from the file only when its own
// style is the one asked for (`is_cataloged`).
return faces.iter().any(|f| f.family.eq_ignore_ascii_case(installed) && norm(&f.style) == sk);
}
if named_as_given {
return styled(&w.family);
}
let key = norm(&w.family);
if key.is_empty() {
return false;
}
// Another of a family's names keeps the style asked for.
if let Some(f) = faces.iter().find(|f| f.keys.families.contains(&key)) {
return styled(&f.family);
}
// A legacy family with its legacy style, or a PostScript name, names its face whatever style
// is asked for.
if faces.iter().any(|f| f.keys.legacy.iter().any(|(family, style)| *family == key && *style == sk) || f.keys.postscript.contains(&key)) {
return true;
}
// A legacy family with another style: that style of the family.
faces.iter().find(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).is_some_and(|f| styled(&f.family))
}
/// A font file holding `tables` (tag, data), sorted by tag as table directories are.
#[cfg(any(test, not(target_arch = "wasm32")))]
pub(crate) fn sfnt_of(tables: &[(&[u8; 4], &[u8])]) -> Option<Vec<u8>> {
@@ -947,9 +1115,34 @@ pub fn user_font_dirs() -> Vec<PathBuf> {
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`].
/// VectorCraft's own Fonts folder, set by the app ([`set_app_font_dir`]).
#[cfg(not(target_arch = "wasm32"))]
static APP_FONT_DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Have [`system_font_dirs`] read `dir` with its subfolders: VectorCraft's own Fonts folder, which
/// `text.addFontFiles` copies font files into. The desktop app and `vectorcraft-cli` set it before
/// the first scan, as they install [`set_platform_font_files`]. A folder that doesn't exist yet is
/// read once it does. Only the first call counts. Ignored on wasm.
pub fn set_app_font_dir(dir: PathBuf) {
#[cfg(not(target_arch = "wasm32"))]
// A second call keeps the first folder, as documented.
let _ = APP_FONT_DIR.set(dir);
#[cfg(target_arch = "wasm32")]
let _ = dir;
}
/// The folder [`set_app_font_dir`] set: none before that, and none on wasm.
pub fn app_font_dir() -> Option<&'static Path> {
#[cfg(not(target_arch = "wasm32"))]
return APP_FONT_DIR.get().map(PathBuf::as_path);
#[cfg(target_arch = "wasm32")]
None
}
/// The platform's font folders (the system's and the user's), VectorCraft's own Fonts folder
/// ([`set_app_font_dir`]), the font files known to the platform outside them (on Windows those
/// registered with it, and those [`set_platform_font_files`] lists) and the folders the user added
/// ([`set_user_font_dirs`]), scanned by [`FontDb::global`].
pub fn system_font_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
if cfg!(target_arch = "wasm32") {
@@ -990,6 +1183,7 @@ pub fn system_font_dirs() -> Vec<PathBuf> {
// In a Flatpak sandbox, the host's fonts (system, local and the user's).
dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));
}
dirs.extend(app_font_dir().map(Path::to_path_buf));
#[cfg(not(target_arch = "wasm32"))]
if let Some(list) = PLATFORM_FONT_FILES.get() {
let files = fonts_outside(list(), &dirs);
@@ -1402,8 +1596,7 @@ impl FontDb {
// A file named by itself is a font whatever its name (font services keep fonts in
// files without an extension); one of a folder's only with a font's extension, or
// a suitcase font (whose fonts are in its resource fork, whatever its name).
let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
if !named && !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) && !crate::suitcase::is_suitcase(&p) {
if !named && !is_font_file(&p) && !crate::suitcase::is_suitcase(&p) {
continue;
}
for FaceStyle { family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
+2 -2
View File
@@ -27,8 +27,8 @@ pub mod thread;
pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont};
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, set_user_font_dirs,
style_weight, system_font_dirs, user_font_dirs,
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, WantedFont, WantedFonts, app_font_dir,
is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, style_weight, system_font_dirs, user_font_dirs,
};
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
+2 -2
View File
@@ -78,7 +78,7 @@ fn fork_path(path: &Path) -> std::path::PathBuf {
}
#[cfg(target_os = "macos")]
fn fork_len(path: &Path) -> u64 {
pub(crate) fn fork_len(path: &Path) -> u64 {
std::fs::metadata(fork_path(path)).map_or(0, |m| m.len())
}
@@ -91,7 +91,7 @@ fn read_fork(path: &Path) -> Option<Vec<u8>> {
}
#[cfg(not(target_os = "macos"))]
fn fork_len(_: &Path) -> u64 {
pub(crate) fn fork_len(_: &Path) -> u64 {
0
}
+229
View File
@@ -318,3 +318,232 @@ fn the_scan_reads_suitcase_fonts() {
assert_eq!(bold.path(), Some(suitcase.as_path()));
assert_eq!(db.find_family("SysfontSans3").as_deref(), Some(FAMILY), "by a PostScript-style name, as an EPS names it");
}
/// The bundled Source Sans 3 Regular with a `name` table of `records` (platform, language, name id,
/// text): Windows Unicode (UTF-16) or Mac Roman (ASCII here).
fn named(records: &[(u16, u16, u16, &str)]) -> Vec<u8> {
let mut records = records.to_vec();
records.sort_by_key(|r| (r.0, r.1, r.2));
let (mut name, mut strings) = (vec![], vec![]);
let n = records.len() as u16;
for v in [0, n, 6 + 12 * n] {
name.extend_from_slice(&v.to_be_bytes());
}
for &(platform, lang, id, s) in &records {
let bytes: Vec<u8> = if platform == 3 { s.encode_utf16().flat_map(u16::to_be_bytes).collect() } else { s.as_bytes().to_vec() };
let encoding = if platform == 3 { 1 } else { 0 };
for v in [platform, encoding, lang, id, bytes.len() as u16, strings.len() as u16] {
name.extend_from_slice(&v.to_be_bytes());
}
strings.extend(bytes);
}
name.extend(strings);
let base = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf")).unwrap();
let font = skrifa::FontRef::new(&base).unwrap();
let mut builder = write_fonts::FontBuilder::new();
builder.add_raw(write_fonts::types::Tag::new(b"name"), name);
for r in font.table_directory.table_records() {
let tag = write_fonts::types::Tag::new(&r.tag().to_be_bytes());
if !builder.contains(tag) {
builder.add_raw(tag, font.table_data(r.tag()).unwrap().as_bytes());
}
}
builder.build()
}
const EN: u16 = 0x0409;
const JA: u16 = 0x0411;
/// Copying a file a search offers into a folder the scan reads makes the font resolve exactly from
/// that file, and a file it doesn't offer doesn't: the search matches fonts as `resolve` finds
/// them. Each case resolves the font, copies the file into a scanned folder, rescans and resolves
/// again, as the app does.
#[test]
fn wanted_fonts_match_as_resolve_finds_them() {
let one = named(&[(3, EN, 1, "Parity One"), (3, EN, 2, "Regular"), (3, EN, 6, "ParityOne-Regular")]);
let two = named(&[
(3, EN, 1, "Parity Two"),
(3, EN, 2, "Regular"),
(3, EN, 6, "ParityTwo-Regular"),
(3, EN, 16, "Parity Two"),
(3, JA, 16, "パリティ二"),
(3, EN, 17, "Regular"),
]);
// Laid out like Hiragino Sans W3: a legacy family per weight, paired with its legacy style, and
// a PostScript name that reads as the legacy family.
let three = |postscript: &str| {
named(&[
(1, 0, 1, "Parity Three"),
(1, 0, 2, "W3"),
(3, EN, 1, "Parity Three W3"),
(3, EN, 2, "Regular"),
(3, EN, 6, postscript),
(3, EN, 16, "Parity Three"),
(3, EN, 17, "W3"),
(3, JA, 1, "パリティ三 W3"),
(3, JA, 2, "Regular"),
(3, JA, 16, "パリティ三"),
(3, JA, 17, "W3"),
])
};
let (three, three_ps) = (three("ParityThree-W3"), three("PThree-W3"));
// A PostScript name that is the family's name.
let findme = named(&[(3, EN, 1, "Findme"), (3, EN, 2, "Regular"), (3, EN, 6, "Findme")]);
let psdiff = named(&[(3, EN, 1, "Psdiff Sans"), (3, EN, 2, "Regular"), (3, EN, 6, "PsdiffSans-Regular")]);
let variable = crate::test_fonts::variable_font().unwrap();
let four = |style: &str, ja_style: &str| {
named(&[
(3, EN, 1, "Parity Four"),
(3, EN, 2, style),
(3, EN, 6, &format!("ParityFour-{style}")),
(3, EN, 16, "Parity Four"),
(3, EN, 17, style),
(3, JA, 16, "パリティ四"),
(3, JA, 17, ja_style),
])
};
let (four_regular, four_bold) = (four("Regular", "標準"), four("Bold", "太字"));
let five = named(&[(3, EN, 1, "Parity Five"), (3, EN, 2, "Bold"), (3, EN, 6, "ParityFive-Bold"), (3, EN, 17, "Bold"), (3, JA, 17, "太字")]);
// (family, style, Parity Four Regular installed, candidate file, provides it)
let cases: Vec<(&str, &str, bool, &[u8], bool)> = vec![
("Parity One", "Regular", false, &one, true),
("parity one", "REGULAR", false, &one, true),
("Parity One", "Bold", false, &one, false),
("Parity One", "Regular", false, &four_bold, false),
("パリティ二", "Regular", false, &two, true),
("パリティ二", "Bold", false, &two, false),
("Parity Three W3", "Regular", false, &three_ps, true),
("Parity Three W3", "Bold", false, &three_ps, false),
("PThree-W3", "Bold", false, &three_ps, true),
// The legacy family reads as the PostScript name, which names the W3 face.
("Parity Three W3", "Bold", false, &three, true),
("パリティ三", "W3", false, &three, true),
("パリティ三", "Bold", false, &three, false),
("Findme", "Bold", false, &findme, false),
("Find-me", "Regular", false, &findme, true),
// A family's name goes before a PostScript name that reads the same.
("Find-me", "Bold", false, &findme, false),
("PsdiffSans-Regular", "Bold", false, &psdiff, true),
("Varitest Sans", "SemiBold", false, &variable, true),
("Varitest Sans", "Normal", false, &variable, true),
("VaritestSans-Bold", "Regular", false, &variable, true),
("Varitest Sans", "Black", false, &variable, false),
("Parity Five", "太字", false, &five, true),
("Parity Four", "Bold", true, &four_bold, true),
("パリティ四", "Bold", true, &four_bold, true),
("Parity Four", "太字", true, &four_bold, false),
("Parity Four", "Bold", true, &one, false),
];
for (i, (family, style, installed, candidate, provides)) in cases.into_iter().enumerate() {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-wanted-{i}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (base, new) = (dir.join("base"), dir.join("new"));
std::fs::create_dir_all(&base).unwrap();
std::fs::create_dir_all(&new).unwrap();
if installed {
std::fs::write(base.join("ParityFour-Regular.ttf"), &four_regular).unwrap();
}
let db = FontDb::with_font_dirs(vec![base, new.clone()]);
let (face, m) = db.resolve(family, style).unwrap();
assert_eq!(m, if installed { FontMatch::Style } else { FontMatch::Missing }, "case {i}: {family} {style}");
let wanted = WantedFont { family: family.into(), style: style.into(), installed: (m == FontMatch::Style).then(|| face.family.clone()) };
let file = new.join("Candidate.ttf");
std::fs::write(&file, candidate).unwrap();
db.load_system_fonts();
let (face, m) = db.resolve(family, style).unwrap();
let exact = m == FontMatch::Exact && face.path().map(|p| std::fs::canonicalize(p).unwrap()) == Some(std::fs::canonicalize(&file).unwrap());
assert_eq!(exact, provides, "case {i}: resolve gave {face:?} {m:?} for {family} {style}");
assert_eq!(WantedFonts::new(&[wanted]).provided_by(&file) == [0], provides, "case {i}: the search, for {family} {style}");
let _ = std::fs::remove_dir_all(&dir);
}
}
/// A search reads only so much of a file: of a collection whose header gives 300 faces it reads
/// the first 64, and a cap on the bytes read ends it early.
#[test]
fn a_search_reads_at_most_its_share_of_a_font_file() {
use crate::fontdb::file_face_names_within;
let face = renamed("SourceSans3-Regular.ttf");
let tables = u16::from_be_bytes([face[4], face[5]]) as usize;
let len = |tag: &[u8]| {
let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap();
u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap()))
};
// What one face costs: its table directory and its name and OS/2 tables.
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2");
let n = 300;
let base = 12 + 4 * n;
let mut ttc = b"ttcf".to_vec();
ttc.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
ttc.extend_from_slice(&(n as u32).to_be_bytes());
for _ in 0..n {
ttc.extend_from_slice(&(base as u32).to_be_bytes());
}
// Every face is the one font, whose table offsets count from the start of the collection.
let mut f = face.clone();
for r in 0..tables {
let at = 12 + r * 16 + 8;
let off = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) + base as u32;
f[at..at + 4].copy_from_slice(&off.to_be_bytes());
}
ttc.extend(f);
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-many", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Many.ttc");
std::fs::write(&file, ttc).unwrap();
assert_eq!(file_face_names_within(&file, 256, u64::MAX).len(), 256);
assert_eq!(file_face_names_within(&file, 64, u64::MAX).len(), 64);
// The header, 64 offsets and three faces.
assert_eq!(file_face_names_within(&file, 64, 12 + 4 * 64 + 3 * per_face).len(), 3);
let wanted = WantedFonts::new(&[WantedFont { family: FAMILY.into(), style: "Regular".into(), installed: None }]);
assert_eq!(wanted.provided_by(&file), [0]);
assert!(wanted.provided_by(&dir.join("No Such.ttf")).is_empty());
}
/// A search reads a suitcase font only when its whole resource fork fits in the 8 MB a search reads
/// of one file.
#[cfg(target_os = "macos")]
#[test]
fn a_search_reads_a_suitcase_font_only_within_its_share() {
use crate::fontdb::file_face_names_within;
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-big-suitcase", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let suitcase = dir.join("Sysfont Sans3");
std::fs::write(&suitcase, b"").unwrap();
let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]);
let len = fork.len() as u64;
std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap();
assert_eq!(file_face_names_within(&suitcase, 64, len).len(), 1);
assert!(file_face_names_within(&suitcase, 64, len - 1).is_empty());
let wanted = WantedFonts::new(&[WantedFont { family: FAMILY.into(), style: "Regular".into(), installed: None }]);
assert_eq!(wanted.provided_by(&suitcase), [0]);
// Past the 8 MB a search reads of one file.
let mut big = fork;
big.resize((8 << 20) + 1, 0);
std::fs::write(suitcase.join("..namedfork/rsrc"), big).unwrap();
assert!(wanted.provided_by(&suitcase).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn font_files_are_told_by_their_extension() {
for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] {
assert!(is_font_file(Path::new(name)), "{name}");
}
for name in ["f.ttf.txt", "ttf", ".29457", "g.woff2", "h.fon"] {
assert!(!is_font_file(Path::new(name)), "{name}");
}
}
/// VectorCraft's own Fonts folder joins the scan once set, even before it exists; only the first
/// folder set counts.
#[test]
fn the_app_font_folder_is_read_by_the_scan() {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-app-fonts", std::process::id()));
set_app_font_dir(dir.clone());
set_app_font_dir(dir.join("Other"));
assert_eq!(app_font_dir(), Some(dir.as_path()));
let dirs = system_font_dirs();
assert_eq!(dirs.iter().filter(|d| **d == dir).count(), 1, "{dirs:?}");
assert!(!dirs.contains(&dir.join("Other")));
}
+10 -1
View File
@@ -15,7 +15,7 @@ use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath};
use crate::{Action, Tool, ToolContext};
pub use anchor::AnchorTool;
pub use curvature::CurvatureTool;
pub use curvature::{CurvatureTool, EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
pub use family::FamilyTool;
pub use gesture::GestureTool;
@@ -94,6 +94,15 @@ fn candidate_paths(cx: &ToolContext) -> Vec<NodeId> {
v
}
/// The selected paths the Pen and the Curvature tool edit (not guides, nor locked or hidden ones).
pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
cx.selection
.objects
.iter()
.copied()
.filter(|&id| cx.doc.is_editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// Nearest anchor within `tol`: (path, subpath, anchor).
pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
anchor_in(cx, candidate_paths(cx), p, tol)
+685 -30
View File
@@ -5,28 +5,293 @@
//! first point to close; Backspace/Delete removes the last touched point; Esc/Enter ends the path.
//! A rubber band shows the curve to the cursor (Enable Rubber Band for Curvature Tool). Each point
//! placed or dragged snaps to Smart Guides ([`DrawSnap`]), as the Pen's anchors do.
//!
//! It edits any selected path too, whatever drew it, keeping its shape except where edited
//! (#798). A click on one of its points makes that the current point (direct-selected); a drag
//! moves it, re-curving only the two segments at it ([`curvature_move`]); Alt-click or
//! double-click toggles it between smooth and corner and Backspace/Delete removes it. A click on
//! a segment adds a smooth point there without changing the shape ([`curvature_insert`]), and a
//! drag moves the new point at once. While the current point is an end of an open path, clicks go
//! on from it ([`curvature_extend`]): the old segments keep their shape, the new ones curve
//! through the new points, and a click on the path's other end closes it. Each edit is one
//! `path.curvatureEdit`, `path.convertAnchor` or `path.removeAnchor` (one undo step).
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, Selection};
use vectorcraft_geom::Point;
use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2};
use super::{FEEDBACK, catmull_rom};
use super::{FEEDBACK, anchor_in, catmull_rom, editable_paths, remove_anchor, segment_in};
use crate::guides::{DrawSnap, Leave, Targets};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// The command that edits a selected path.
const EDIT: &str = "path.curvatureEdit";
#[derive(Default)]
pub struct CurvatureTool {
pts: Vec<(Point, bool)>,
closed: bool,
id: Option<NodeId>,
/// Point being dragged: (index, began).
drag: Option<(usize, Point, bool)>,
/// Last touched point (Backspace removes it).
/// The point being dragged, the pointer at the press, and whether the drag began.
drag: Option<(Grab, Point, bool)>,
/// Last touched point of the path being drawn (Backspace removes it).
current: Option<usize>,
hover: Option<Point>,
/// The end the last click on a selected path placed.
placed: Option<Placed>,
snap: DrawSnap,
}
/// What a press grabbed for a drag.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Grab {
/// A point of the path being drawn.
Drawn(usize),
/// An anchor of a selected path: (path, subpath, anchor).
Anchor(NodeId, usize, usize),
/// The anchor the press added on a segment of a selected path: (path, subpath, segment, t).
Inserted(NodeId, usize, usize, f64),
}
/// The end a click on a selected path placed, while it still is that end (its subpath has as many
/// anchors as then): going on from it, it curves through its neighbours, or stays a corner when it
/// was Alt-clicked. Any other end keeps its curve.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Placed {
id: NodeId,
si: usize,
start: bool,
anchors: usize,
corner: bool,
}
/// The current point of a selected path while it is an end of an open subpath: where clicks go on
/// from (its start with `start`), and the other end, which a click closes the subpath on.
#[derive(Clone, Copy)]
struct End {
id: NodeId,
si: usize,
start: bool,
anchors: usize,
p: Point,
other: Point,
}
impl End {
/// `end` for `path.curvatureEdit`.
fn name(&self) -> &'static str {
if self.start { "start" } else { "end" }
}
}
/// How the end a path goes on from bends into the new segment ([`curvature_extend`],
/// [`curvature_close`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EndCurve {
/// The segment it ends keeps its shape: the new handle goes on along its handle, or along the
/// curve where it has none, and with both it is smooth.
#[default]
Keep,
/// Smooth through its neighbours, as [`catmull_rom`] curves a point (a point the Curvature tool
/// placed: its segment re-curves).
Smooth,
/// A corner, without handles.
Corner,
}
impl EndCurve {
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"keep" => Self::Keep,
"smooth" => Self::Smooth,
"corner" => Self::Corner,
_ => return None,
})
}
pub fn name(self) -> &'static str {
match self {
Self::Keep => "keep",
Self::Smooth => "smooth",
Self::Corner => "corner",
}
}
}
/// The anchors before and after anchor `i` of `sp` (round the start of a closed one).
fn neighbours(sp: &SubPath, i: usize) -> [Option<usize>; 2] {
let n = sp.anchors.len();
let wrap = sp.closed && n > 1;
let prev = if i > 0 { Some(i - 1) } else { wrap.then(|| n - 1) };
let next = if i + 1 < n { Some(i + 1) } else { wrap.then_some(0) };
[prev, next]
}
/// Move anchor `i` of `sp` to `q` as the Curvature tool drags a point: only the two segments at it
/// change. A smooth anchor turns along the line through its neighbours; the neighbours' handles on
/// those segments, and a corner's own handles, keep their directions, their lengths scaling with
/// their segment's chord, so the segments beyond don't move and a corner without handles keeps
/// none. False when there is no anchor `i`.
pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool {
let Some(&a) = sp.anchors.get(i) else { return false };
let mut own = [a.h_in - a.p, a.h_out - a.p];
let mut ends = [None; 2];
for (side, j) in neighbours(sp, i).into_iter().enumerate() {
let Some(b) = j.and_then(|j| sp.anchors.get_mut(j)) else { continue };
let old = a.p.distance(b.p);
let s = if old > 1e-9 { q.distance(b.p) / old } else { 1.0 };
let h = if side == 0 { &mut b.h_out } else { &mut b.h_in };
*h = b.p + (*h - b.p) * s;
own[side] *= s;
ends[side] = Some(b.p);
}
let mut m = Anchor { p: q, h_in: q + own[0], h_out: q + own[1], kind: a.kind };
if let (AnchorKind::Smooth, [Some(prev), Some(next)]) = (a.kind, ends) {
let d = next - prev;
let l = d.hypot();
if l > 1e-9 {
// A handle it lacks comes out a third of the way to that side's neighbour.
let len = |h: Vec2, to: Point| if h.hypot() > 1e-9 { h.hypot() } else { q.distance(to) / 3.0 };
m.h_in = q - d * (len(own[0], prev) / l);
m.h_out = q + d * (len(own[1], next) / l);
}
}
if let Some(x) = sp.anchors.get_mut(i) {
*x = m;
}
true
}
/// Add a smooth anchor at `t` on segment `seg` of `sp` without changing its shape (on a straight
/// segment its handles lie along it, so a drag curves it): the new anchor's index. None when there
/// is no such segment.
pub fn curvature_insert(sp: &mut SubPath, seg: usize, t: f64) -> Option<usize> {
if seg >= sp.segment_count() {
return None;
}
let line = sp.segment_is_line(seg);
let i = sp.insert_anchor(seg, if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.5 });
if line {
sp.smooth_anchor(i);
}
Some(i)
}
/// Go on from an end of the open subpath `sp` (its start with `start`) to a new end at `p`, which
/// has no handles; the old end bends into the new segment as `how` says.
pub fn curvature_extend(sp: &mut SubPath, start: bool, p: Point, how: EndCurve) {
if start {
sp.reverse();
}
bend_last(sp, p, how);
sp.anchors.push(Anchor::corner(p));
if start {
sp.reverse();
}
}
/// Close the open subpath `sp` from its end (its start with `start`): that end bends into the
/// closing segment as `how` says, and the other keeps its curve.
pub fn curvature_close(sp: &mut SubPath, start: bool, how: EndCurve) {
if start {
sp.reverse();
}
if let (Some(first), Some(last)) = (sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)) {
bend_last(sp, first, how);
sp.reverse();
bend_last(sp, last, EndCurve::Keep);
sp.reverse();
sp.closed = true;
}
if start {
sp.reverse();
}
}
/// Bend the last anchor of `sp` into a new segment on to `to`, as `how` says.
fn bend_last(sp: &mut SubPath, to: Point, how: EndCurve) {
let prev = sp.anchors.len().checked_sub(2).and_then(|j| sp.anchors.get(j)).copied();
let Some(e) = sp.anchors.last_mut() else { return };
match how {
EndCurve::Corner => e.retract(),
EndCurve::Smooth => {
let t = prev.map_or(Vec2::ZERO, |b| (to - b.p) / 6.0);
if t.hypot() > 1e-9 {
*e = Anchor { p: e.p, h_in: e.p - t, h_out: e.p + t, kind: AnchorKind::Smooth };
} else {
e.retract();
}
}
EndCurve::Keep => {
// The way the curve comes in: from its handle, or else the segment's tangent there.
let back = if e.has_in() { Some(e.h_in) } else { prev.map(|b| if b.h_out.distance(e.p) > 1e-9 { b.h_out } else { b.p }) };
let d = back.map_or(Vec2::ZERO, |b| e.p - b);
let l = d.hypot();
e.h_out = if l > 1e-9 { e.p + d * (e.p.distance(to) / 3.0 / l) } else { e.p };
if e.has_in() && e.has_out() {
e.kind = AnchorKind::Smooth;
}
}
}
}
/// Subpath `si` of `id`, a selected path the tool edits.
fn subpath<'a>(cx: &ToolContext<'a>, id: NodeId, si: usize) -> Option<&'a SubPath> {
if !editable_paths(cx).any(|e| e == id) {
return None;
}
cx.doc.node(id)?.path_data()?.subpaths.get(si)
}
/// The current point of a selected path: its one direct-selected anchor (path, subpath, anchor).
fn current_point(cx: &ToolContext) -> Option<(NodeId, usize, usize)> {
let mut sets = cx.selection.anchors.iter().filter(|(_, set)| !set.is_empty());
let (&id, set) = sets.next()?;
if set.len() != 1 || sets.next().is_some() {
return None;
}
let &(si, ai) = set.first()?;
subpath(cx, id, si).filter(|sp| ai < sp.anchors.len()).map(|_| (id, si, ai))
}
/// The current point while it is an end of an open subpath.
fn current_end(cx: &ToolContext) -> Option<End> {
let (id, si, ai) = current_point(cx)?;
let sp = subpath(cx, id, si)?;
let n = sp.anchors.len();
let (first, last) = (sp.anchors.first()?.p, sp.anchors.last()?.p);
if sp.closed || (ai > 0 && ai + 1 < n) {
return None;
}
// A one-anchor subpath goes on from its end.
let start = ai == 0 && n > 1;
let (p, other) = if start { (first, last) } else { (last, first) };
Some(End { id, si, start, anchors: n, p, other })
}
/// Make anchor `(id, si, ai)` the current point.
fn select_point((id, si, ai): (NodeId, usize, usize)) -> Action {
Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))
}
/// Toggle anchor `(id, si, ai)` of a selected path between smooth and corner.
fn toggle(cx: &ToolContext, (id, si, ai): (NodeId, usize, usize)) -> Option<Action> {
let a = subpath(cx, id, si)?.anchors.get(ai)?;
let to = if a.kind == AnchorKind::Smooth { "corner" } else { "smooth" };
Some(Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": to})))
}
/// Snap targets for dragging anchors `anchors` of subpath `si` of `id` (the rest of the path
/// pulls).
fn hold_targets(snap: &mut DrawSnap, cx: &ToolContext, id: NodeId, si: usize, anchors: &[usize]) {
let sel = Selection { objects: vec![id], anchors: [(id, anchors.iter().map(|&ai| (si, ai)).collect())].into(), ..Selection::default() };
snap.hold(cx, || Targets::for_anchor_drag(cx.doc, &sel));
}
/// How near a press picks a point.
fn point_tol(cx: &ToolContext) -> f64 {
cx.tol(5.0).max(cx.point_tol())
}
impl CurvatureTool {
/// The path being drawn, if it is still the single selected object and matches our points.
fn active(&self, cx: &ToolContext) -> Option<NodeId> {
@@ -58,12 +323,70 @@ impl CurvatureTool {
self.id = None;
self.drag = None;
self.current = None;
self.placed = None;
self.snap.clear();
}
/// The segment to the next point leaves the last one.
fn leave(&self, cx: &ToolContext) -> Option<Leave> {
self.pts.last().map(|(p, _)| Leave::segment(cx, *p, false))
/// The path the next click goes on (left out of the snap targets, its anchors still pulling)
/// and the segment to it: the path being drawn, or the selected one whose end is current.
fn leave(&self, cx: &ToolContext) -> Option<(NodeId, Leave)> {
match self.active(cx) {
Some(id) => self.pts.last().map(|(p, _)| (id, Leave::segment(cx, *p, false))),
None => current_end(cx).map(|e| (e.id, Leave::segment(cx, e.p, false))),
}
}
/// How end `e` bends into the next segment: as [`Placed`] says for the end the last click
/// placed, else it keeps its curve.
fn how(&self, e: &End) -> EndCurve {
match self.placed {
Some(pl) if (pl.id, pl.si, pl.start, pl.anchors) == (e.id, e.si, e.start, e.anchors) => {
if pl.corner {
EndCurve::Corner
} else {
EndCurve::Smooth
}
}
_ => EndCurve::Keep,
}
}
/// A press on a selected path the tool isn't drawing: on the other end of the open path going
/// on (it closes), on a point, anywhere while an end is current (the path goes on), or on a
/// segment. None elsewhere: a new path starts.
fn press_selected(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
let (p, tol) = (ev.pos, point_tol(cx));
let end = current_end(cx);
if let Some(e) = end.filter(|e| e.anchors >= 3 && p.distance(e.other) <= tol) {
let how = self.how(&e);
self.placed = None;
let v = json!({"id": e.id.0, "subpath": e.si, "op": "close", "end": e.name(), "from": how.name()});
return Some(vec![Action::Exec(EDIT.into(), v)]);
}
if let Some(hit) = anchor_in(cx, editable_paths(cx), p, tol) {
let mut out = vec![select_point(hit)];
if ev.mods.alt {
out.extend(toggle(cx, hit));
return Some(out);
}
let (id, si, ai) = hit;
hold_targets(&mut self.snap, cx, id, si, &[ai]);
self.drag = Some((Grab::Anchor(id, si, ai), p, false));
return Some(out);
}
if let Some(e) = end {
let q = self.snap.press(cx, p, &[e.id], Some(&Leave::segment(cx, e.p, false)));
let how = self.how(&e);
self.placed = Some(Placed { id: e.id, si: e.si, start: e.start, anchors: e.anchors + 1, corner: ev.mods.alt });
let v = json!({"id": e.id.0, "subpath": e.si, "op": "extend", "end": e.name(), "x": q.x, "y": q.y, "from": how.name()});
return Some(vec![Action::Exec(EDIT.into(), v)]);
}
let (id, si, seg, t) = segment_in(cx, editable_paths(cx), p, tol)?;
let n = subpath(cx, id, si)?.anchors.len().max(1);
hold_targets(&mut self.snap, cx, id, si, &[seg, (seg + 1) % n]);
self.drag = Some((Grab::Inserted(id, si, seg, t), p, true));
let v = json!({"id": id.0, "subpath": si, "op": "insert", "segment": seg, "t": t});
Some(vec![Action::Begin("Curvature".into()), Action::Preview(EDIT.into(), v)])
}
}
@@ -82,8 +405,8 @@ impl Tool for CurvatureTool {
}
match ev.kind {
PointerKind::Move => {
let from = active.and_then(|_| self.leave(cx));
self.hover = Some(self.snap.hover(cx, p, active.as_slice(), from.as_ref()));
let (on, from) = self.leave(cx).unzip();
self.hover = Some(self.snap.hover(cx, p, on.as_slice(), from.as_ref()));
vec![]
}
PointerKind::Down => {
@@ -99,19 +422,21 @@ impl Tool for CurvatureTool {
return vec![Action::Exec("path.curvature".into(), self.params())];
}
// The point dragged and the curve through it move: the rest pull.
let sel = Selection { objects: vec![id], anchors: [(id, [(0, i)].into())].into(), ..Selection::default() };
self.snap.hold(cx, || Targets::for_anchor_drag(cx.doc, &sel));
self.drag = Some((i, p, false));
hold_targets(&mut self.snap, cx, id, 0, &[i]);
self.drag = Some((Grab::Drawn(i), p, false));
return vec![];
}
if !self.closed {
let from = self.leave(cx);
let from = self.leave(cx).map(|l| l.1);
let p = self.snap.press(cx, p, &[id], from.as_ref());
self.pts.push((p, ev.mods.alt));
self.current = Some(self.pts.len() - 1);
return vec![Action::Exec("path.curvature".into(), self.params())];
}
}
if let Some(out) = self.press_selected(cx, ev) {
return out;
}
// Start a new path.
self.reset();
let p = self.snap.press(cx, p, &[], None);
@@ -120,20 +445,30 @@ impl Tool for CurvatureTool {
vec![Action::Exec("path.curvature".into(), self.params()), Action::Notify("created".into())]
}
PointerKind::Drag => {
let Some((i, start, began)) = self.drag else { return vec![] };
let Some((grab, start, began)) = self.drag else { return vec![] };
let mut out = vec![];
if !began {
if p.distance(start) < cx.tol(3.0) {
return out;
}
out.push(Action::Begin("Curvature".into()));
self.drag = Some((i, start, true));
self.drag = Some((grab, start, true));
}
let p = self.snap.drag(cx, p, None);
if let Some(pt) = self.pts.get_mut(i) {
pt.0 = p;
}
out.push(Action::Preview("path.curvature".into(), self.params()));
out.push(match grab {
Grab::Drawn(i) => {
if let Some(pt) = self.pts.get_mut(i) {
pt.0 = p;
}
Action::Preview("path.curvature".into(), self.params())
}
Grab::Anchor(id, si, ai) => {
Action::Preview(EDIT.into(), json!({"id": id.0, "subpath": si, "op": "move", "anchor": ai, "x": p.x, "y": p.y}))
}
Grab::Inserted(id, si, seg, t) => {
Action::Preview(EDIT.into(), json!({"id": id.0, "subpath": si, "op": "insert", "segment": seg, "t": t, "x": p.x, "y": p.y}))
}
});
out
}
PointerKind::Up => {
@@ -145,7 +480,7 @@ impl Tool for CurvatureTool {
}
PointerKind::DoubleClick => {
if active.is_none() {
return vec![];
return anchor_in(cx, editable_paths(cx), p, point_tol(cx)).and_then(|hit| toggle(cx, hit)).into_iter().collect();
}
let Some(i) = self.hit_point(cx, p) else { return vec![] };
self.pts[i].1 = !self.pts[i].1;
@@ -158,14 +493,30 @@ impl Tool for CurvatureTool {
self.id = Some(cx.selection.objects[0]);
}
}
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Backspace | ToolKey::Delete)
&& self.drag.is_none()
&& if self.active(cx).is_some() { self.pts.len() > 1 } else { current_point(cx).is_some() }
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec<Action> {
match key {
ToolKey::Escape | ToolKey::Enter => {
let dragging = self.drag.is_some_and(|d| d.2);
let drawing = self.active(cx).is_some();
self.reset();
if dragging { vec![Action::Cancel] } else { vec![] }
if dragging {
return vec![Action::Cancel];
}
// A selected path's current point goes: clicks no longer go on from it.
if drawing || current_point(cx).is_none() {
return vec![];
}
vec![Action::Exec("select.set".into(), json!({"ids": crate::json_ids(&cx.selection.objects)}))]
}
ToolKey::Backspace | ToolKey::Delete if self.active(cx).is_some() && self.pts.len() > 1 && self.drag.is_none() => {
ToolKey::Backspace | ToolKey::Delete if self.claims_key(cx, key) => {
if self.active(cx).is_none() {
return current_point(cx).map(remove_anchor).into_iter().collect();
}
let i = self.current.unwrap_or(self.pts.len() - 1).min(self.pts.len() - 1);
self.pts.remove(i);
if self.pts.len() < 3 {
@@ -184,19 +535,34 @@ impl Tool for CurvatureTool {
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut o = self.snap.guides().to_vec();
let band = cx.curvature_rubber_band && self.drag.is_none();
let mut bp = BezPath::new();
if self.active(cx).is_none() {
// The curve on from the current end of a selected path: its last segment and the next.
if band
&& let (Some(e), Some(h)) = (current_end(cx), self.hover)
&& let Some(sp) = subpath(cx, e.id, e.si)
{
let n = sp.anchors.len();
let near = if e.start {
sp.anchors.iter().take(2).rev().map(Anchor::reversed).collect()
} else {
sp.anchors.iter().skip(n.saturating_sub(2)).copied().collect()
};
let mut tail = SubPath::new(near, false);
curvature_extend(&mut tail, false, h, self.how(&e));
tail.to_bezpath_into(&mut bp);
o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false });
}
return o;
}
if cx.curvature_rubber_band
if band
&& !self.closed
&& self.drag.is_none()
&& let Some(h) = self.hover
{
let mut pts = self.pts.clone();
pts.push((h, false));
let sp = catmull_rom(&pts, false);
let mut bp = vectorcraft_geom::BezPath::new();
sp.to_bezpath_into(&mut bp);
catmull_rom(&pts, false).to_bezpath_into(&mut bp);
o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false });
}
for (i, (p, _)) in self.pts.iter().enumerate() {
@@ -204,7 +570,33 @@ impl Tool for CurvatureTool {
}
o
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
if self.active(cx).is_some() {
return match self.hit_point(cx, p) {
Some(0) if !self.closed && self.pts.len() >= 3 => Cursor::PenClose,
Some(_) if m.alt => Cursor::PenConvert,
Some(_) => Cursor::Move,
None => Cursor::Pen,
};
}
let tol = point_tol(cx);
let end = current_end(cx);
if end.is_some_and(|e| e.anchors >= 3 && p.distance(e.other) <= tol) {
return Cursor::PenClose;
}
if let Some((id, si, ai)) = anchor_in(cx, editable_paths(cx), p, tol) {
let open_end = subpath(cx, id, si).is_some_and(|sp| !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()));
return if m.alt {
Cursor::PenConvert
} else if open_end {
Cursor::PenContinue
} else {
Cursor::Move
};
}
if end.is_none() && segment_in(cx, editable_paths(cx), p, tol).is_some() {
return Cursor::PenAdd;
}
Cursor::Pen
}
}
@@ -213,7 +605,8 @@ impl Tool for CurvatureTool {
mod tests {
use super::*;
use crate::testutil::*;
use vectorcraft_doc::Selection;
use vectorcraft_doc::{Appearance, Document, Node, Selection};
use vectorcraft_geom::{ParamCurve, PathData};
#[test]
fn first_click_creates_then_notify_tracks_path() {
@@ -252,4 +645,266 @@ mod tests {
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 202.0, 99.0));
assert!(t.overlays(&cx).is_empty());
}
fn pt(x: f64, y: f64) -> Point {
Point::new(x, y)
}
/// An open pen-style path: a corner start, two smooth anchors with uneven handles, a cusp and
/// an end with only an incoming handle.
fn wave() -> SubPath {
SubPath::new(
vec![
Anchor::corner(pt(0.0, 100.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(60.0, 10.0), pt(160.0, -15.0)),
Anchor::with_handles(pt(250.0, 80.0), pt(220.0, 30.0), pt(280.0, 130.0)),
Anchor::with_handles(pt(350.0, 150.0), pt(320.0, 160.0), pt(380.0, 100.0)),
Anchor::with_handles(pt(450.0, 60.0), pt(420.0, 90.0), pt(450.0, 60.0)),
],
false,
)
}
/// Every point of `a` lies on `b` (within 1e-6), sampled.
fn lies_on(a: &SubPath, b: &SubPath) -> bool {
let b = PathData::single(b.clone());
(0..a.segment_count()).all(|i| (0..=20).all(|k| b.nearest(a.segment(i).eval(k as f64 / 20.0)).is_some_and(|n| n.4 < 1e-6)))
}
fn collinear(a: Vec2, b: Vec2) -> bool {
a.cross(b).abs() < 1e-6 * a.hypot().max(1.0) * b.hypot().max(1.0)
}
#[test]
fn moving_a_point_recurves_only_its_two_segments() {
let before = wave();
let mut sp = before.clone();
assert_eq!(sp.anchors[2].kind, AnchorKind::Smooth);
assert!(curvature_move(&mut sp, 2, pt(260.0, 140.0)));
assert_eq!(sp.anchors[2].p, pt(260.0, 140.0));
// The segments beyond its neighbours are bit-identical.
assert_eq!(sp.segment(0), before.segment(0));
assert_eq!(sp.segment(3), before.segment(3));
// The neighbours keep their handle directions on its segments, and their other handles.
assert!(collinear(sp.anchors[1].h_out - sp.anchors[1].p, before.anchors[1].h_out - before.anchors[1].p));
assert!(collinear(sp.anchors[3].h_in - sp.anchors[3].p, before.anchors[3].h_in - before.anchors[3].p));
assert_eq!((sp.anchors[1].h_in, sp.anchors[3].h_out), (before.anchors[1].h_in, before.anchors[3].h_out));
// The moved smooth point turns along the line through its neighbours.
let a = sp.anchors[2];
assert_eq!(a.kind, AnchorKind::Smooth);
assert!(collinear(a.h_out - a.p, sp.anchors[3].p - sp.anchors[1].p) && collinear(a.h_in - a.p, a.h_out - a.p));
assert!((a.h_out - a.p).dot(sp.anchors[3].p - sp.anchors[1].p) > 0.0);
// A cusp keeps its handle directions; a moved end changes its one segment only.
assert_eq!(sp.anchors[3].kind, AnchorKind::Corner);
assert!(curvature_move(&mut sp, 3, pt(360.0, 170.0)));
assert!(collinear(sp.anchors[3].h_out - sp.anchors[3].p, before.anchors[3].h_out - before.anchors[3].p));
let mut end = before.clone();
assert!(curvature_move(&mut end, 4, pt(470.0, 20.0)));
assert_eq!(end.segment(2), before.segment(2));
assert!(!curvature_move(&mut end, 5, pt(0.0, 0.0)));
}
#[test]
fn moving_a_corner_without_handles_keeps_its_sides_straight() {
let (d, id) = doc_with_rect();
let mut sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
assert!(curvature_move(&mut sp, 0, pt(80.0, 70.0)));
assert!((0..sp.segment_count()).all(|i| sp.segment_is_line(i)));
assert_eq!(sp.anchors[0], Anchor::corner(pt(80.0, 70.0)));
}
#[test]
fn going_on_from_an_end_keeps_the_old_segments() {
let before = wave();
let mut sp = before.clone();
curvature_extend(&mut sp, false, pt(550.0, 120.0), EndCurve::Keep);
assert_eq!(sp.anchors.len(), 6);
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
// The old end turns smooth, going on along its incoming handle, a third of the chord out.
let e = sp.anchors[4];
assert_eq!(e.kind, AnchorKind::Smooth);
assert!(collinear(e.h_out - e.p, e.p - e.h_in) && (e.h_out - e.p).dot(e.p - e.h_in) > 0.0);
assert!((e.h_out.distance(e.p) - e.p.distance(pt(550.0, 120.0)) / 3.0).abs() < 1e-9);
assert_eq!(sp.anchors[5], Anchor::corner(pt(550.0, 120.0)));
// The point placed then curves through its neighbours as a drawn path's points do.
curvature_extend(&mut sp, false, pt(650.0, 60.0), EndCurve::Smooth);
let drawn = catmull_rom(&[(pt(450.0, 60.0), false), (pt(550.0, 120.0), false), (pt(650.0, 60.0), false)], false);
assert_eq!((sp.anchors[5].h_in, sp.anchors[5].h_out), (drawn.anchors[1].h_in, drawn.anchors[1].h_out));
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
// A corner stays one.
curvature_extend(&mut sp, false, pt(700.0, 100.0), EndCurve::Corner);
assert!(!sp.anchors[6].has_in() && !sp.anchors[6].has_out());
// From the start: the old segments come one later, and the new end is the first anchor.
let mut sp = before.clone();
curvature_extend(&mut sp, true, pt(-100.0, 50.0), EndCurve::Keep);
assert_eq!(sp.anchors[0], Anchor::corner(pt(-100.0, 50.0)));
assert!((0..4).all(|i| sp.segment(i + 1) == before.segment(i)));
// A corner end without handles goes on along its segment's tangent.
let old = sp.anchors[1];
assert!(old.has_in() && !old.has_out());
assert!(collinear(old.h_in - old.p, old.p - before.anchors[1].h_in) && (old.h_in - old.p).dot(old.p - before.anchors[1].h_in) > 0.0);
}
#[test]
fn closing_keeps_the_old_segments() {
let before = wave();
let mut sp = before.clone();
curvature_close(&mut sp, false, EndCurve::Keep);
assert!(sp.closed && sp.anchors.len() == 5);
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
// The first anchor gains an incoming handle along its tangent: no kink there.
let f = sp.anchors[0];
assert!(f.has_in() && collinear(f.p - f.h_in, before.anchors[1].h_in - f.p));
}
#[test]
fn inserting_a_point_keeps_the_shape() {
let before = wave();
let mut sp = before.clone();
assert_eq!(curvature_insert(&mut sp, 1, 0.3), Some(2));
assert_eq!(sp.anchors.len(), 6);
assert_eq!(sp.anchors[2].kind, AnchorKind::Smooth);
assert!(lies_on(&sp, &before) && lies_on(&before, &sp));
// On a straight side the point is smooth too, its handles along the side.
let (d, id) = doc_with_rect();
let rect = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
let mut sp = rect.clone();
let i = curvature_insert(&mut sp, 0, 0.5).unwrap();
assert_eq!(sp.anchors[i].kind, AnchorKind::Smooth);
assert!(sp.anchors[i].has_in() && sp.anchors[i].has_out());
assert!(lies_on(&sp, &rect) && lies_on(&rect, &sp));
assert_eq!(curvature_insert(&mut sp, 99, 0.5), None);
}
/// A document with one path, `sp`.
fn doc_with(sp: SubPath) -> (Document, NodeId) {
let mut d = Document::new(800.0, 600.0);
let l = d.layers[0].id;
let id = d.alloc_id();
d.insert(Some(l), 0, Node::path(id, PathData::single(sp), Appearance::default_art())).unwrap();
(d, id)
}
/// Path `id` selected, anchor `current` of its first subpath direct-selected (or none).
fn selected(id: NodeId, current: Option<usize>) -> Selection {
let mut s = Selection::default();
s.set([id]);
if let Some(ai) = current {
s.anchors.insert(id, [(0, ai)].into());
}
s
}
/// A context without snapping.
fn quiet<'a>(d: &'a Document, s: &'a Selection, p: &'a crate::PaintDefaults) -> ToolContext<'a> {
ToolContext { smart_guides: false, snap_to_point: false, ..cx(d, s, p) }
}
fn press(t: &mut CurvatureTool, cx: &ToolContext, x: f64, y: f64, alt: bool) -> Vec<Action> {
let ev = PointerEvent::new(PointerKind::Down, x, y).with_mods(Mods { alt, ..Mods::default() });
let mut a = t.pointer(cx, &ev);
a.extend(t.pointer(cx, &PointerEvent::new(PointerKind::Up, x, y)));
a
}
/// The op and params of a `path.curvatureEdit` action.
fn edit_op(a: &Action) -> Option<(&str, &Value)> {
match a {
Action::Exec(c, v) | Action::Preview(c, v) if c == EDIT => Some((v["op"].as_str()?, v)),
_ => None,
}
}
#[test]
fn a_press_on_a_point_selects_it_and_a_drag_moves_it() {
let (d, id) = doc_with(wave());
let (s, p) = (selected(id, None), paint());
let cx = quiet(&d, &s, &p);
let mut t = CurvatureTool::default();
assert_eq!(t.cursor(&cx, pt(250.0, 81.0), Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&cx, pt(450.0, 61.0), Mods::default()), Cursor::PenContinue);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 251.0, 81.0));
assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 2]], "mode": "set"}))]);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 140.0));
assert_eq!(a[0], Action::Begin("Curvature".into()));
let moved = edit_op(&a[1]).map(|(op, v)| (op, v["anchor"].clone(), v["x"].clone(), v["y"].clone()));
assert_eq!(moved, Some(("move", json!(2), json!(260.0), json!(140.0))));
assert!(t.busy());
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 260.0, 140.0)), vec![Action::Commit]);
// A press without a drag only selects.
assert_eq!(press(&mut t, &cx, 100.0, 0.0, false).len(), 1);
}
#[test]
fn alt_click_or_double_click_toggles_and_delete_removes() {
let (d, id) = doc_with(wave());
let p = paint();
let s = selected(id, None);
let cx = quiet(&d, &s, &p);
let mut t = CurvatureTool::default();
let to = |a: &[Action]| a.iter().find(|a| matches!(a, Action::Exec(c, _) if c == "path.convertAnchor")).cloned();
let a = press(&mut t, &cx, 100.0, 0.0, true);
assert!(matches!(to(&a), Some(Action::Exec(_, v)) if v["anchor"] == 1 && v["to"] == "corner"), "{a:?}");
assert_eq!(t.cursor(&cx, pt(100.0, 0.0), Mods { alt: true, ..Mods::default() }), Cursor::PenConvert);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 0.0, 100.0));
assert!(matches!(to(&a), Some(Action::Exec(_, v)) if v["anchor"] == 0 && v["to"] == "smooth"), "{a:?}");
// Delete is the tool's while a point is current, and removes it.
assert!(!t.claims_key(&cx, ToolKey::Delete));
let s = selected(id, Some(2));
let cx = quiet(&d, &s, &p);
assert!(t.claims_key(&cx, ToolKey::Backspace));
assert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![remove_anchor((id, 0, 2))]);
// Esc lets go of the point.
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]);
}
#[test]
fn a_press_on_a_segment_adds_a_point_and_a_drag_moves_it_in_one_step() {
let (d, id) = doc_with(wave());
let (s, p) = (selected(id, None), paint());
let cx = quiet(&d, &s, &p);
let mut t = CurvatureTool::default();
let on = wave().segment(1).eval(0.5);
assert_eq!(t.cursor(&cx, on, Mods::default()), Cursor::PenAdd);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on.x, on.y));
assert_eq!(a[0], Action::Begin("Curvature".into()));
assert!(
matches!(edit_op(&a[1]), Some(("insert", v)) if v["segment"] == 1 && (v["t"].as_f64().unwrap() - 0.5).abs() < 1e-3 && v.get("x").is_none())
);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, on.x + 1.0, on.y + 40.0));
assert!(matches!(edit_op(&a[0]), Some(("insert", v)) if v["segment"] == 1 && v["y"] == on.y + 40.0), "{a:?}");
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, on.x, on.y + 40.0)), vec![Action::Commit]);
}
#[test]
fn clicks_go_on_from_a_current_end_and_the_other_end_closes() {
let p = paint();
let mut sp = wave();
let mut t = CurvatureTool::default();
let (d, id) = doc_with(sp.clone());
let s = selected(id, Some(4));
let a = press(&mut t, &quiet(&d, &s, &p), 550.0, 120.0, false);
assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["end"] == "end" && v["from"] == "keep" && v["x"] == 550.0), "{a:?}");
// As the engine does it: the new end is current, and the next click curves through it.
curvature_extend(&mut sp, false, pt(550.0, 120.0), EndCurve::Keep);
let (d, id) = doc_with(sp.clone());
let s = selected(id, Some(5));
let cx = quiet(&d, &s, &p);
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 650.0, 60.0));
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { .. })), "the rubber band shows");
let a = press(&mut t, &cx, 650.0, 60.0, true);
assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["from"] == "smooth"), "{a:?}");
curvature_extend(&mut sp, false, pt(650.0, 60.0), EndCurve::Smooth);
let (d, id) = doc_with(sp.clone());
let s = selected(id, Some(6));
let cx = quiet(&d, &s, &p);
// The Alt-clicked point stays a corner; a click on the first point closes.
assert_eq!(t.cursor(&cx, pt(0.0, 100.0), Mods::default()), Cursor::PenClose);
let a = press(&mut t, &cx, 0.0, 100.0, false);
assert!(matches!(edit_op(&a[0]), Some(("close", v)) if v["from"] == "corner" && v["end"] == "end"), "{a:?}");
// Any other end keeps its curve; the start goes on from the start.
let s = selected(id, Some(0));
let a = press(&mut t, &quiet(&d, &s, &p), -50.0, 150.0, false);
assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["end"] == "start" && v["from"] == "keep"), "{a:?}");
}
}
+35 -5
View File
@@ -365,11 +365,16 @@ impl Targets {
/// View → Snap to Point: only these targets' anchors pull, and the ruler guides (shown and
/// unlocked, as the selection tools pick them) pull the pointer into line where they run.
fn for_snap_to_point(self, cx: &ToolContext) -> Self {
let mut t = self.anchors_only();
self.anchors_only().with_rulers(cx)
}
/// These targets and the ruler guides, when they are shown (and so unlocked to the selection
/// tools): they pull a point into line where they run.
fn with_rulers(mut self, cx: &ToolContext) -> Self {
if cx.guides {
t.rulers = cx.doc.guides.iter().map(|g| Ruler { vertical: g.vertical, pos: g.pos, span: cx.doc.guide_span(g) }).collect();
self.rulers = cx.doc.guides.iter().map(|g| Ruler { vertical: g.vertical, pos: g.pos, span: cx.doc.guide_span(g) }).collect();
}
t
self
}
/// What a dragged selection's grabbed point snaps to with View → Snap to Point and Smart
@@ -486,8 +491,10 @@ impl Targets {
if d.abs() <= 1e-9 {
continue;
}
// The ruler guides that way count as lines too (#812).
let rulers: Vec<(f64, Point, Kind)> = self.rulers.iter().filter(|r| r.vertical == vertical).filter_map(|r| r.line_at(q, reach)).collect();
// A line that far across the way crosses it at least that far along.
for (t, from, _) in lines_near(lines, v, reach) {
for (t, from, _) in lines_near(lines, v, reach).iter().chain(&rulers) {
let s = (t - a) / d;
// Exactly on the line, whatever the rounding along the way.
let hit = if vertical { Point::new(*t, at.y + dir.y * s) } else { Point::new(at.x + dir.x * s, *t) };
@@ -827,7 +834,9 @@ impl PointSnap {
let targets = if cx.snap_to_pixel || cx.snap_to_grid {
None
} else if cx.smart_guides {
Some((targets().styled(cx), cx.snapping_tolerance))
// Snap to Point keeps pulling points onto the ruler guides with Smart Guides on (#812).
let t = targets().styled(cx);
Some((if cx.snap_to_point { t.with_rulers(cx) } else { t }, cx.snapping_tolerance))
} else if cx.snap_to_point {
Some((targets().for_snap_to_point(cx), cx.snap_tolerance))
} else {
@@ -1397,6 +1406,27 @@ mod tests {
}
}
/// #812: with Smart Guides on, ruler guides pull a drawn point too (Snap to Point), horizontal
/// and vertical alike, also while it slides along a construction guide or Shift's angle.
#[test]
fn drawn_points_snap_to_ruler_guides_with_smart_guides_on() {
let (mut d, _) = doc_with_rect();
d.guides.push(vectorcraft_doc::Guide::new(false, 313.0));
d.guides.push(vectorcraft_doc::Guide::new(true, 331.0));
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let mut snap = DrawSnap::default();
assert_eq!(snap.press(&c, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 313.0), "the horizontal guide");
assert_eq!(snap.press(&c, Point::new(329.0, 260.0), &[], None), Point::new(331.0, 260.0), "the vertical guide");
// On the 45° construction guide from (210, 210), where the horizontal guide crosses it.
let from = Leave::segment(&c, Point::new(210.0, 210.0), false);
let q = snap.press(&c, Point::new(312.0, 311.0), &[], Some(&from));
assert!((q - Point::new(313.0, 313.0)).hypot() < 1e-9, "{q:?}");
// Snap to Point off: Smart Guides alone don't use the ruler guides.
let off = ToolContext { snap_to_point: false, ..cx(&d, &s, &p) };
assert_eq!(snap.press(&off, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 315.0));
}
/// A drawing tool's snapper reuses its targets while hovering over the same document state, and
/// gathers them again when it changes, and on every press.
#[test]
+1 -10
View File
@@ -27,7 +27,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{BezPath, Point};
use crate::direct::hit_handle;
use crate::draw2::AnchorTool;
use crate::draw2::{AnchorTool, editable_paths};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -122,15 +122,6 @@ fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
|| crate::draw2::segment_in(cx, editable_paths(cx), p, cx.pick_tol()).is_some())
}
/// The selected paths the pen edits (not guides, nor locked or hidden ones).
fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
cx.selection
.objects
.iter()
.copied()
.filter(|&id| cx.doc.is_editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// Preview the outgoing handle of anchor `ai` of subpath `si` at `h`, the incoming one left alone.
fn set_out_handle(id: NodeId, si: usize, ai: usize, h: Point) -> Action {
Action::Preview(
+73 -1
View File
@@ -71,6 +71,8 @@ pub struct SelectionTool {
targets: Option<Targets>,
moving: Option<MoveSnap>,
guide: GuideEdit,
/// Smart Guides: the centre or anchor under the pointer, and its label ([`Self::hover_point`]).
hover: Option<(Point, &'static str)>,
}
/// Snapping for the selection moved as a whole, its targets gathered when the move begins: View →
@@ -163,10 +165,36 @@ fn box_hit(cx: &ToolContext, b: &OrientedBox, p: Point) -> Option<BoxHit> {
in_rotate_zone(b.rect, lp, tol, cx.tol(18.0)).map(|_| BoxHit::Rotate)
}
/// How near (screen points) the pointer must come to an object's centre or anchor for Smart Guides
/// to label it while hovering.
const HOVER_REACH: f64 = 6.0;
impl SelectionTool {
fn drag_threshold(cx: &ToolContext) -> f64 {
cx.tol(3.0)
}
/// With Smart Guides on, the anchor or the centre of an object near `p` (the one under the
/// pointer, else a selected one) and its label, "anchor" or "center", as Illustrator shows
/// them while hovering (#812). A press there grabs the object by that point.
fn hover_point(cx: &ToolContext, p: Point) -> Option<(Point, &'static str)> {
if !cx.smart_guides {
return None;
}
let reach = cx.tol(HOVER_REACH);
let under = hit_test(cx.doc, p, cx.hit_options()).map(|h| h.top_object(cx.isolation));
let nearest = |points: &mut dyn Iterator<Item = Point>| {
points.filter(|q| q.distance(p) <= reach).min_by(|a, b| a.distance(p).total_cmp(&b.distance(p)))
};
under.into_iter().chain(cx.selection.objects.iter().copied()).find_map(|id| {
let n = cx.doc.node(id)?;
let anchor = n.path_data().and_then(|pd| nearest(&mut pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))));
anchor.map(|q| (q, "anchor")).or_else(|| {
let c = cx.doc.bounds_of(&[id], cx.preview_bounds)?.center();
(c.distance(p) <= reach).then_some((c, "center"))
})
})
}
}
impl Tool for SelectionTool {
@@ -188,6 +216,11 @@ impl Tool for SelectionTool {
}
let p = ev.pos;
let m = ev.mods;
// A press near the hovered centre or anchor grabs the object by it.
let grab = self.hover.take().map(|(q, _)| q).filter(|q| q.distance(p) <= cx.tol(HOVER_REACH)).unwrap_or(p);
if matches!(ev.kind, PointerKind::Move) && matches!(self.state, State::Idle) {
self.hover = Self::hover_point(cx, p);
}
match (ev.kind, self.state.clone()) {
(PointerKind::DoubleClick, _) => {
self.state = State::Idle;
@@ -278,7 +311,7 @@ impl Tool for SelectionTool {
} else if cx.selection.objects.len() > 1 && !m.cmd && !m.alt {
key = Some(top);
}
self.state = State::Moving { start: p, began: false, deselect, key };
self.state = State::Moving { start: grab, began: false, deselect, key };
out
}
None => {
@@ -397,6 +430,12 @@ impl Tool for SelectionTool {
}
o.extend(self.guides.iter().cloned());
o.extend(self.guide.overlays(cx));
if let (Some((q, label)), State::Idle) = (self.hover, &self.state) {
let style = crate::guides::GuideStyle::of(cx);
if style.labels {
o.push(Overlay::Label { p: q, text: label.into(), color: style.color });
}
}
if let Some((p, t)) = &self.measure {
o.push(Overlay::Measure { p: *p, text: t.clone() });
}
@@ -483,6 +522,39 @@ mod tests {
PointerEvent::new(kind, x, y)
}
/// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a
/// press there grabs the object by that point.
#[test]
fn hovering_labels_the_centre_and_anchors_and_a_press_grabs_by_them() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let label = |t: &SelectionTool| {
t.overlays(&cx).iter().find_map(|o| match o {
Overlay::Label { p, text, .. } => Some((*p, text.clone())),
_ => None,
})
};
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Move, 152.0, 151.0));
assert_eq!(label(&t), Some((Point::new(150.0, 150.0), "center".to_string())));
t.pointer(&cx, &ev(PointerKind::Move, 102.0, 101.0));
assert_eq!(label(&t), Some((Point::new(100.0, 100.0), "anchor".to_string())));
t.pointer(&cx, &ev(PointerKind::Move, 130.0, 170.0));
assert_eq!(label(&t), None, "away from both");
// Grabbed by its centre, the object's centre follows the pointer.
t.pointer(&cx, &ev(PointerKind::Move, 152.0, 151.0));
t.pointer(&cx, &ev(PointerKind::Down, 152.0, 151.0));
let a = t.pointer(&cx, &ev(PointerKind::Drag, 250.0, 250.0));
assert!(a.iter().any(|a| matches!(a, Action::Preview(_, v) if v["matrix"][4] == 100.0 && v["matrix"][5] == 100.0)), "{a:?}");
// With Smart Guides off, nothing is labelled.
let off = ToolContext { smart_guides: false, ..cx };
let mut t = SelectionTool::default();
t.pointer(&off, &ev(PointerKind::Move, 152.0, 151.0));
assert!(!t.overlays(&off).iter().any(|o| matches!(o, Overlay::Label { .. })));
}
#[test]
fn click_selects_object() {
let (d, id) = doc_with_rect();
+4 -1
View File
@@ -346,7 +346,10 @@ impl Tool for ArtboardTool {
for h in Handle::ALL {
o.push(Overlay::Anchor { p: h.pos(r), color: BLUE, filled: false, size: 7.0 });
}
o.push(Overlay::Label { p: Point::new(r.x0, r.y0 - cx.tol(14.0)), text: format!("{:02} - {}", self.active + 1, ab.name), color: BLUE });
// Where the canvas names the other artboards: on the top edge, flush with the left one
// (labels are drawn 8 px right of and 14 px above their point).
let at = Point::new(r.x0 - cx.tol(8.0), r.y0 - cx.tol(4.0));
o.push(Overlay::Label { p: at, text: format!("{:02} - {}", self.active + 1, ab.name), color: BLUE });
if let (Some(Drag::Resize { began: true, .. }), true) = (self.drag, cx.measurement_labels) {
o.push(Overlay::Measure {
p: Point::new(r.x1, r.y1) + Vec2::new(cx.tol(12.0), cx.tol(12.0)),
+85 -41
View File
@@ -249,6 +249,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
placed: vectorcraft_render::placed_document::generation(),
pixel,
smooth_images,
isolated: st.isolation.map(|id| id.0),
};
// Placed documents' bitmaps are being made: draw again when they are ready.
if vectorcraft_render::placed_document::busy() {
@@ -298,6 +299,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
progressive_placed: true,
trace_views: true,
smooth_images,
// Isolation mode: the art around the isolated group or layer is dimmed (#833).
isolated: key.isolated.map(vectorcraft_doc::NodeId),
..opts
};
// Light documents render synchronously (no lag vs overlays); heavy ones go to the worker.
@@ -349,8 +352,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.ui.view.pixel_preview && v.zoom >= PIXEL_GRID_ZOOM && app.session.prefs.show_pixel_grid {
grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false });
}
// Artboard edges and names.
// Artboard edges and names. The Artboard tool labels its active artboard itself (following
// a move or resize): that one isn't named twice.
let active_ab = 0;
let artboard_tool = app.session.tool_id() == "artboard";
let tool_labelled = artboard_tool.then(|| app.session.tool_options()["active"].as_u64()).flatten();
for (i, ab) in doc.artboards.iter().enumerate() {
let r = xf.rect_to_screen(ab.rect);
let c = if i == active_ab { Color32::from_gray(0) } else { Color32::from_gray(120) };
@@ -359,7 +365,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if doc.setup.has_bleed() {
painter.add(Shape::closed_line(xf.quad(doc.setup.bleed_rect(ab.rect)), Stroke::new(1.0, t.bleed)));
}
if app.session.tool_id() == "artboard" || doc.artboards.len() > 1 {
if (artboard_tool || doc.artboards.len() > 1) && tool_labelled != u64::try_from(i).ok() {
painter.text(
r.left_top() - vec2(0.0, 4.0),
egui::Align2::LEFT_BOTTOM,
@@ -1078,47 +1084,46 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, unit: Unit,
let step = unit.ruler_step(xf.zoom);
let minor = step / 10.0;
let font = egui::FontId::proportional(9.5);
let a = xf.to_doc(top.left_top());
let b = xf.to_doc(top.right_top());
let clip_top = p.with_clip_rect(top);
let mut x = (a.x / per / minor).floor() * minor;
while x * per <= b.x {
let sx = xf.to_screen(Point::new(x * per, 0.0)).x;
let is_major = ((x / step).round() * step - x).abs() < minor * 0.01;
let is_mid = ((x / (step / 2.0)).round() * (step / 2.0) - x).abs() < minor * 0.01;
let len = if is_major {
let near = |v: f64, every: f64| ((v / every).round() * every - v).abs() < minor * 0.01;
// A tick's length: the labelled ones longest, the halves between them shorter.
let tick = |v: f64| {
if near(v, step) {
RULER
} else if is_mid {
} else if near(v, step / 2.0) {
7.0
} else {
4.0
};
clip_top.line_segment([pos2(sx, top.bottom() - len), pos2(sx, top.bottom())], Stroke::new(1.0, t.ruler_tick));
if is_major {
}
};
// Each ruler measures along its own edge, in the canvas's coordinates turned with the view
// (#826): at 0° the top one reads x and the left one y. `draw` gets each tick's distance
// (screen points) from `from` along the ruler, and its value in `unit`.
let ticks = |from: Pos2, to: Pos2, axis: vectorcraft_geom::Vec2, draw: &mut dyn FnMut(f32, f64)| {
let along = |s: Pos2| xf.to_doc(s).to_vec2().dot(axis);
let (a, b) = (along(from), along(to));
let mut v = (a / per / minor).floor() * minor;
while v * per <= b {
draw(((v * per - a) * xf.zoom) as f32, v);
v += minor;
}
};
// The canvas's directions along the screen's x and y.
let (sn, cs) = xf.rot.sin_cos();
let clip_top = p.with_clip_rect(top);
ticks(top.left_top(), top.right_top(), vectorcraft_geom::Vec2::new(cs, -sn), &mut |d, x| {
let sx = top.left() + d;
clip_top.line_segment([pos2(sx, top.bottom() - tick(x)), pos2(sx, top.bottom())], Stroke::new(1.0, t.ruler_tick));
if near(x, step) {
clip_top.text(pos2(sx + 2.0, top.top() + 1.0), egui::Align2::LEFT_TOP, ruler_label(x, step), font.clone(), t.ruler_tick);
}
x += minor;
}
let a = xf.to_doc(left.left_top());
let b = xf.to_doc(left.left_bottom());
});
let clip_left = p.with_clip_rect(left);
let mut y = (a.y / per / minor).floor() * minor;
while y * per <= b.y {
let sy = xf.to_screen(Point::new(0.0, y * per)).y;
let is_major = ((y / step).round() * step - y).abs() < minor * 0.01;
let is_mid = ((y / (step / 2.0)).round() * (step / 2.0) - y).abs() < minor * 0.01;
let len = if is_major {
RULER
} else if is_mid {
7.0
} else {
4.0
};
clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick));
if is_major {
ticks(left.left_top(), left.left_bottom(), vectorcraft_geom::Vec2::new(sn, cs), &mut |d, y| {
let sy = left.top() + d;
clip_left.line_segment([pos2(left.right() - tick(y), sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick));
if near(y, step) {
// Vertical labels read top-to-bottom, one digit per line like Illustrator.
let s = ruler_label(y, step);
for (k, ch) in s.chars().enumerate() {
for (k, ch) in ruler_label(y, step).chars().enumerate() {
clip_left.text(
pos2(left.left() + 4.0, sy + 2.0 + k as f32 * 8.5),
egui::Align2::LEFT_TOP,
@@ -1128,8 +1133,7 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, unit: Unit,
);
}
}
y += minor;
}
});
if let Some(h) = hover {
let s = xf.to_screen(h);
clip_top.line_segment([pos2(s.x, top.top()), pos2(s.x, top.bottom())], Stroke::new(1.0, t.text));
@@ -1846,10 +1850,9 @@ fn recent(app: &mut VectorcraftApp, ui: &mut 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);
if r.clicked() {
// A failure is reported to the user there.
let _ = crate::io::open_reporting(app, &path);
}
});
}
@@ -2050,6 +2053,47 @@ mod tests {
use vectorcraft_engine::Session;
use vectorcraft_geom::Shape as _;
/// #826: in a turned view each ruler still has ticks along its whole length; at 0° the top one
/// reads x where the canvas has it.
#[test]
fn rulers_cover_their_length_at_any_rotation() {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let full = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
let [top, left, _] = ruler_rects(full);
for deg in [0.0_f64, 30.0, 90.0, 135.0, 200.0] {
let xf = Xf { rect: full, zoom: 1.0, center: Point::new(300.0, 200.0), rot: deg.to_radians() };
let mut out = ctx.run_ui(Default::default(), |ui| rulers(ui, full, &xf, None, Unit::Points, &Tokens::get(ui.ctx())));
out.textures_delta.clear();
// The ticks' positions along each ruler.
let along = |ruler: egui::Rect, x: bool| -> Vec<f32> {
let mut at: Vec<f32> = out
.shapes
.iter()
.filter(|c| c.clip_rect == ruler)
.filter_map(|c| match &c.shape {
Shape::LineSegment { points: [a, b], .. } if x && a.x == b.x => Some(a.x),
Shape::LineSegment { points: [a, b], .. } if !x && a.y == b.y => Some(a.y),
_ => None,
})
.collect();
at.sort_by(f32::total_cmp);
at
};
for (ruler, x) in [(top, true), (left, false)] {
let at = along(ruler, x);
let (start, end) = if x { (ruler.left(), ruler.right()) } else { (ruler.top(), ruler.bottom()) };
let (Some(first), Some(last)) = (at.first(), at.last()) else { panic!("{deg}°: no ticks") };
assert!(first - start < 20.0 && end - last < 20.0, "{deg}°: ticks from {first} to {last} on {start}..{end}");
assert!(at.windows(2).all(|w| w[1] - w[0] < 20.0), "{deg}°: a gap in the ticks");
}
if deg == 0.0 {
let origin = xf.to_screen(Point::ZERO).x;
assert!(along(top, true).iter().any(|x| (x - origin).abs() < 0.01), "a tick at x = 0");
}
}
}
#[test]
fn shaper_selection_highlights_only_the_visible_result() {
let mut s = Session::new();
+1 -17
View File
@@ -265,23 +265,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
return;
}
// Align buttons.
for (icon, tip, p) in [
("align-start-vertical", "Horizontal Align Left", json!({"horizontal": "left"})),
("align-center-vertical", "Horizontal Align Center", json!({"horizontal": "center"})),
("align-end-vertical", "Horizontal Align Right", json!({"horizontal": "right"})),
("align-start-horizontal", "Vertical Align Top", json!({"vertical": "top"})),
("align-center-horizontal", "Vertical Align Center", json!({"vertical": "center"})),
("align-end-horizontal", "Vertical Align Bottom", json!({"vertical": "bottom"})),
] {
if widgets::icon_button(ui, icon, tl!(tip), false, 24.0).clicked() {
let mut p = p;
if sel.len() == 1 {
p["to"] = json!("artboard");
}
app.run("object.align", p).ok();
}
}
crate::panels::align::align_buttons(app, ui, 24.0);
ui.separator();
// The Transform link opens the whole Transform panel (reference point, rotate,
// shear, options) in a popover; X/Y/W/H follow inline while the bar has room.
+3 -4
View File
@@ -335,10 +335,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
// No save dialog for an agent: the bytes come back, as in headless mode.
None => wrap(app.run("document.export", p.clone())),
},
"app.quit" => {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
ok(Value::Null)
}
// As the menu's Quit: `{"pending": "saveChanges"}` while a modified document is asked
// about; otherwise null, and the host closes the window (#830).
"app.quit" => wrap(app.run("app.quit", json!({}))),
other => err(format!("unknown method `{other}`")),
}
}
+11
View File
@@ -36,6 +36,17 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str,
app.ui.dialog = Some(Dialog::new(KIND, fields));
}
/// The dialog kind of a message with a Close button only ([`tell`]).
pub const MESSAGE: &str = "message";
pub(super) const MESSAGE_SPEC: DialogSpec = DialogSpec { ok: None, ..SPEC };
/// Tell the user `message` (with an optional `detail` line), both in the UI language, in a dialog
/// they close.
pub fn tell(app: &mut VectorcraftApp, message: &str, detail: &str) {
app.ui.dialog = Some(Dialog::new(MESSAGE, json!({"message": message, "detail": detail})));
}
/// Closes before running, so a dialog the command opens stays open.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let params = d.fields.get("__params").cloned().unwrap_or_else(|| json!({}));
+18
View File
@@ -158,6 +158,8 @@ fn choices(effect: &str, key: &str) -> Option<form::Choices> {
("blur.radial", "method") => Some(&[("Spin", "spin"), ("Zoom", "zoom")]),
("blur.radial", "quality") => Some(&[("Draft", "draft"), ("Good", "good"), ("Best", "best")]),
("blur.smart", "quality") => Some(&[("Low", "low"), ("Medium", "medium"), ("High", "high")]),
("path.offsetPath", "joins") => Some(&[("Miter", "miter"), ("Round", "round"), ("Bevel", "bevel")]),
("distort.roughen" | "distort.zigZag", "points") => Some(&[("Smooth", "smooth"), ("Corner", "corner")]),
_ => None,
}
}
@@ -371,3 +373,19 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
app.ui.dialog = None;
r
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fields_that_pick_a_value_are_dropdowns_of_its_values() {
// The values come from the effect's parameter documentation (`joins: "miter"|"round"|…`).
for (effect, key) in [("path.offsetPath", "joins"), ("distort.zigZag", "points"), ("distort.roughen", "points")] {
let doc = vectorcraft_effects::effect_info(effect).unwrap().params;
let listed = doc.split(&format!("{key}: ")).nth(1).unwrap().split([',', '}', ' ']).next().unwrap().to_string();
let values: Vec<String> = choices(effect, key).unwrap().iter().map(|(_, v)| format!("\"{v}\"")).collect();
assert_eq!(values.join("|"), listed, "{effect} {key}");
}
}
}
+16 -4
View File
@@ -215,7 +215,9 @@ pub(super) fn param_fields(
d.fields.iter().filter(|(k, _)| !k.starts_with("__") && k.as_str() != "preview").map(|(k, v)| (k.clone(), v.clone())).collect();
keys.sort_by_key(|(k, _)| rank(k));
for (k, v) in keys {
ui.label(egui::RichText::new(humanized(&k)).color(t.text));
// A size's Relative / Absolute pair (Roughen, Zig Zag, Tweak) is its own label.
let relative = k == "relative" && v.is_boolean();
ui.label(egui::RichText::new(if relative { String::new() } else { humanized(&k) }).color(t.text));
if let Some(cur) = crate::widgets::blend_param(&k, &v) {
if let Some(m) = crate::widgets::blend_param_dropdown(ui, ("fx-blend", &k), cur) {
d.fields.insert(k, m);
@@ -247,9 +249,19 @@ pub(super) fn param_fields(
changed = true;
}
}
Value::Bool(mut b) => {
if ui.checkbox(&mut b, "").changed() {
d.fields.insert(k, json!(b));
Value::Bool(b) if relative => {
ui.horizontal(|ui| {
for (label, on) in [(tl!("Relative"), true), (tl!("Absolute"), false)] {
if crate::widgets::radio(ui, label, b == on, true) && b != on {
d.fields.insert(k.clone(), json!(on));
changed = true;
}
}
});
}
Value::Bool(b) => {
if crate::widgets::check(ui, "", b, true) {
d.fields.insert(k, json!(!b));
changed = true;
}
}
+60 -3
View File
@@ -90,12 +90,19 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let screen =
d.fields.get("screen").and_then(Value::as_array).and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32)));
let chip = Point::new(d.f64("x", 0.0), d.f64("y", 0.0));
let pos = screen.unwrap_or_else(|| {
app.canvas_rect.zip(app.view().copied()).map_or(ctx.content_rect().center(), |(r, v)| Xf::new(r, &v).to_screen(chip) + vec2(14.0, 14.0))
let area = egui::Id::new("gradient-stop-popover");
let size = ctx.memory(|m| m.area_rect(area)).map_or(POPOVER_SIZE, |r| r.size());
let pos = screen.unwrap_or_else(|| match app.canvas_rect.zip(app.view().copied()) {
Some((canvas, v)) => {
let xf = Xf::new(canvas, &v);
let at = xf.to_screen(chip);
selection_on_screen(app, &xf).map_or(at + vec2(14.0, 14.0), |art| beside_art(at, art, size, canvas))
}
None => ctx.content_rect().center(),
});
let swatches = d.str("tab") == "swatches";
let mut tab = None;
let resp = egui::Area::new(egui::Id::new("gradient-stop-popover"))
let resp = egui::Area::new(area)
.order(egui::Order::Foreground)
.fixed_pos(pos)
.constrain(true)
@@ -150,6 +157,34 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
/// The popover's size before it has been drawn.
const POPOVER_SIZE: egui::Vec2 = vec2(272.0, 360.0);
/// The selected art's box on the screen.
fn selection_on_screen(app: &VectorcraftApp, xf: &Xf) -> Option<egui::Rect> {
let st = app.session.active()?;
let b = st.doc.bounds_of(&st.selection.objects, false)?;
Some(egui::Rect::from_points(&xf.quad(b)))
}
/// Where the popover opened from a stop's chip at `chip` goes: beside the selected `art` on the
/// first side of it with room for a popover of `size` in `room` (right, left, below, above), so
/// the art it recolours stays in view (#862); else beside the chip.
fn beside_art(chip: egui::Pos2, art: egui::Rect, size: egui::Vec2, room: egui::Rect) -> egui::Pos2 {
const GAP: f32 = 12.0;
let x = (chip.x - size.x / 2.0).clamp(room.left(), (room.right() - size.x).max(room.left()));
let y = (chip.y - size.y / 2.0).clamp(room.top(), (room.bottom() - size.y).max(room.top()));
[
egui::pos2(art.right() + GAP, y),
egui::pos2(art.left() - GAP - size.x, y),
egui::pos2(x, art.bottom() + GAP),
egui::pos2(x, art.top() - GAP - size.y),
]
.into_iter()
.find(|p| room.contains_rect(egui::Rect::from_min_size(*p, size)))
.unwrap_or(chip + vec2(14.0, 14.0))
}
/// Document swatches as tiles: a click gives the stop (or point) that colour.
fn swatch_grid(app: &mut VectorcraftApp, ui: &mut egui::Ui, target: &Target) {
let colors = swatch_colors(app);
@@ -248,6 +283,28 @@ mod tests {
app
}
/// #862: the popover goes beside the art, on the first side with room, not over it.
#[test]
fn the_popover_goes_beside_the_art_it_edits() {
let room = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1200.0, 800.0));
let size = egui::vec2(272.0, 360.0);
let place = |art: egui::Rect| egui::Rect::from_min_size(beside_art(art.center(), art, size, room), size);
// Room on the right.
let art = egui::Rect::from_min_max(egui::pos2(300.0, 300.0), egui::pos2(500.0, 450.0));
assert!(place(art).left() > art.right() && room.contains_rect(place(art)));
// Against the right edge: on the left.
let art = egui::Rect::from_min_max(egui::pos2(900.0, 300.0), egui::pos2(1150.0, 450.0));
assert!(place(art).right() < art.left());
// As wide as the room: below it, or above it near the bottom.
let art = egui::Rect::from_min_max(egui::pos2(100.0, 20.0), egui::pos2(1100.0, 300.0));
assert!(place(art).top() > art.bottom());
let art = egui::Rect::from_min_max(egui::pos2(100.0, 420.0), egui::pos2(1100.0, 780.0));
assert!(place(art).bottom() < art.top());
// Nowhere to go: beside the chip, as before.
let art = room.shrink(10.0);
assert_eq!(beside_art(art.center(), art, size, room), art.center() + egui::vec2(14.0, 14.0));
}
fn stops(app: &VectorcraftApp) -> Vec<GradientStop> {
match selected(app) {
Some(Target::Stop(stops, _)) => stops,
+763
View File
@@ -0,0 +1,763 @@
//! The fonts a document opened without (`text.missingFonts`), listed once the missing linked file
//! questions (dialog `missingLinks`) are answered, one document at a time ([`super::settle`]), with
//! Find Fonts (Type › Find Font on the first of them, to replace it) and Close. Neither brings the
//! dialog back for that open. Search Fonts Folder (the `Fonts` folder next to the document, as
//! File › Package writes it) and Find in Folder… look for their files (`text.findFontFiles`, on
//! separate threads), and Add Fonts copies the files the user chooses into VectorCraft's own Fonts
//! folder (`text.addFontFiles`). Type › Find Font's Find in Folder… opens it too
//! (`ui.findFontsInFolder`), and so does `ui.missingFontsDialog`.
//!
//! Fields: `document` (the document's uid), `fonts` (`text.missingFonts`'s rows),
//! `fontsNextToDocument` (or empty), `state` (empty, `searching`, `done`, `stopped` or `failed`),
//! `search` (the search's `id`), `folder`, `found` (`text.findFontFiles`'s `fonts`, with the files
//! found), `searched`, `skipped`, `unreadable`, `stopped`, `error`, `chosen` (the files to add; a
//! font's first file is chosen when it is found), `searchFolder` (set it and confirm to search that
//! folder) and `discard` (set it and confirm for Find Fonts; confirming without either adds the
//! chosen files).
use std::time::Duration;
use serde_json::{Value, json};
use super::DialogSpec;
use crate::picks::PickRequest;
use crate::state::Dialog;
use crate::theme::{self, Tokens};
use crate::{VectorcraftApp, widgets};
/// The dialog kind of the fonts a document opened without.
pub const KIND: &str = "missingFonts";
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Missing Fonts").into(),
body,
confirm,
// Close, with Find Fonts beside it; Add Fonts is a button of the body.
ok: None,
discard: Some("Find Fonts"),
min_width: 440.0,
max_width: Some(540.0),
..DialogSpec::FORM
};
/// After a document opened (`document.open`'s result `r`): its Missing Fonts dialog waits for the
/// dialog slot. On the web the status line shows how many fonts are missing instead, unless it
/// shows the open's notes.
pub fn after_open(app: &mut VectorcraftApp, r: &Value) {
after_open_for(app, r, cfg!(target_arch = "wasm32"));
}
fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) {
let Some(st) = app.session.active() else { return };
let uid = st.uid;
if web {
let n = vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).len();
if n > 0 && r["warnings"].as_array().is_none_or(Vec::is_empty) {
app.status(format!("{n} font(s) aren't available here: their text shows in another font"));
}
return;
}
if !app.ui.pending_fonts.contains(&uid) {
app.ui.pending_fonts.push(uid);
}
}
/// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available.
fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option<Dialog> {
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref());
let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?;
let next = r["fontsNextToDocument"].as_str().unwrap_or_default();
Some(Dialog::new(KIND, json!({ "document": uid, "fonts": fonts, "fontsNextToDocument": next, "state": "", "chosen": [] })))
}
/// With no dialog open: the dialog of the first queued document that is still open and still
/// misses fonts.
pub(super) fn open_next(app: &mut VectorcraftApp) {
while app.ui.dialog.is_none() && !app.ui.pending_fonts.is_empty() {
let uid = app.ui.pending_fonts.remove(0);
app.ui.dialog = dialog_for(app, uid);
if app.ui.dialog.is_some() {
app.ui.fonts_dialog = Some(uid);
}
}
}
/// Put the document `uid` at the front of the queue.
fn queue_first(app: &mut VectorcraftApp, uid: u64) {
app.ui.pending_fonts.retain(|u| *u != uid);
app.ui.pending_fonts.insert(0, uid);
}
/// Once the Missing Fonts dialog on show is gone: when another dialog took its place (Import PDF
/// for a file opened after the document, for example), its document goes back to the front of the
/// queue, and the dialog opens again once no dialog is open. A dialog closed by Cancel, Add Fonts
/// or Escape stays closed.
pub(super) fn requeue_replaced(app: &mut VectorcraftApp) {
let Some(uid) = app.ui.fonts_dialog else { return };
let Some(d) = &app.ui.dialog else {
app.ui.fonts_dialog = None;
return;
};
if d.kind != KIND || d.fields.get("document").and_then(Value::as_u64) != Some(uid) {
app.ui.fonts_dialog = None;
queue_first(app, uid);
}
}
/// Stop the search the dialog started once the dialog is gone (closed, or another in its place).
pub(super) fn stop_when_closed(app: &mut VectorcraftApp) {
let Some(id) = app.ui.dialog_search else { return };
let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.fields.get("search").and_then(Value::as_u64) == Some(id));
if !open {
app.ui.dialog_search = None;
vectorcraft_engine::cmd::fontfiles::stop(&mut app.session, id);
}
}
/// `ui.missingFontsDialog`: the dialog for the active document; with `folder`, searching it.
pub(crate) fn open_command(app: &mut VectorcraftApp, folder: Option<String>) -> Result<Value, String> {
let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?;
let mut d = dialog_for(app, uid).ok_or("No fonts are missing in this document")?;
if let Some(folder) = folder {
start_search(app, &mut d, &folder)?;
}
show_for(app, uid, d);
Ok(Value::Null)
}
/// Show `d`, the dialog of the document `uid`, in place of the open dialog (another document's
/// Missing Fonts dialog asks again later).
fn show_for(app: &mut VectorcraftApp, uid: u64, d: Dialog) {
requeue_replaced(app);
if let Some(shown) = app.ui.fonts_dialog.filter(|shown| *shown != uid) {
queue_first(app, shown);
}
app.ui.pending_fonts.retain(|u| *u != uid);
app.ui.fonts_dialog = Some(uid);
app.ui.dialog = Some(d);
}
/// `ui.findFontsInFolder` (Type › Find Font's Find in Folder…): ask for a folder (or take
/// `folder`), then open the dialog for the active document, searching it.
pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option<String>) -> Result<Value, String> {
let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?;
// Nothing to look for: no folder is asked for.
let mut d = dialog_for(app, uid).ok_or("No fonts are missing in this document")?;
let folder = match folder {
Some(f) => f,
None => crate::picks::folder(app).ok_or("cancelled")?,
};
start_search(app, &mut d, &folder)?;
show_for(app, uid, d);
Ok(Value::Null)
}
/// Start looking in `folder` for the files of the dialog's fonts; what an earlier search found is
/// dropped.
fn start_search(app: &mut VectorcraftApp, d: &mut Dialog, folder: &str) -> Result<(), String> {
let fonts: Vec<Value> = d
.fields
.get("fonts")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|f| json!({ "family": f["family"], "style": f["style"] }))
.collect();
let r = app.run("text.findFontFiles", json!({ "folder": folder, "fonts": fonts }))?;
for k in ["found", "searched", "skipped", "unreadable", "stopped", "error"] {
d.fields.remove(k);
}
d.fields.insert("chosen".into(), json!([]));
d.fields.insert("search".into(), r["id"].clone());
d.fields.insert("folder".into(), json!(folder));
update(d, &r);
app.ui.dialog_search = r["id"].as_u64();
Ok(())
}
/// The files a search found for the font `f` (`{family, style}`): the answer's `fonts` row with
/// the same family and style.
fn files_for<'a>(found: &'a [Value], f: &Value) -> &'a [Value] {
found.iter().find(|r| r["family"] == f["family"] && r["style"] == f["style"]).and_then(|r| r["files"].as_array()).map_or(&[], Vec::as_slice)
}
/// A search's answer `r` into the dialog. A font that gets its first file has that file chosen; a
/// file the user unchecked stays unchecked.
fn update(d: &mut Dialog, r: &Value) {
let before = d.fields.get("found").and_then(Value::as_array).cloned().unwrap_or_default();
let mut chosen = d.fields.get("chosen").and_then(Value::as_array).cloned().unwrap_or_default();
for font in r["fonts"].as_array().into_iter().flatten() {
let had = !files_for(&before, font).is_empty();
if let Some(first) = font["files"].as_array().and_then(|f| f.first()).filter(|f| !had && !chosen.contains(f)) {
chosen.push(first.clone());
}
}
d.fields.insert("chosen".into(), json!(chosen));
d.fields.insert("found".into(), r["fonts"].clone());
for k in ["state", "searched", "skipped", "unreadable", "stopped", "error"] {
match r.get(k) {
Some(v) => d.fields.insert(k.into(), v.clone()),
None => d.fields.remove(k),
};
}
}
/// While searching: the search's progress into the dialog. A search started elsewhere since
/// stopped this one.
fn follow(app: &mut VectorcraftApp, d: &mut Dialog) {
// Polled through `session.execute`.
let Ok(r) = app.session.execute("text.findFontFiles", &json!({})) else { return };
if d.fields.get("search") != Some(&r["id"]) {
d.fields.insert("state".into(), json!("stopped"));
return;
}
update(d, &r);
if let Some(e) = r["error"].as_str() {
app.status(e);
}
}
/// A button of the dialog's.
enum Act {
Search(String),
Pick,
Stop,
Add,
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
if d.str("state") == "searching" {
follow(app, d);
ui.ctx().request_repaint_after(Duration::from_millis(100));
}
let state = d.str("state");
let searching = state == "searching";
widgets::dim_label(ui, tl!("These fonts aren't available. Their text shows in another font."));
ui.add_space(8.0);
let fonts = d.fields.get("fonts").and_then(Value::as_array).cloned().unwrap_or_default();
let found = d.fields.get("found").and_then(Value::as_array).cloned().unwrap_or_default();
let mut chosen = d.fields.get("chosen").and_then(Value::as_array).cloned().unwrap_or_default();
widgets::list_box(ui, |ui| {
egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| {
ui.set_width(ui.available_width());
for f in &fonts {
ui.horizontal(|ui| {
ui.add_space(6.0);
ui.vertical(|ui| {
ui.add_space(3.0);
let (note, color) = crate::find_font::font_note(f);
let name = format!("{} {}{note}", f["family"].as_str().unwrap_or_default(), f["style"].as_str().unwrap_or_default());
ui.label(egui::RichText::new(name).font(theme::semibold(12.0)).color(color.unwrap_or(t.text_strong)));
let files = files_for(&found, f);
for file in files {
let path = file.as_str().unwrap_or_default();
let name = std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().into_owned());
let on = chosen.contains(file);
if widgets::check(ui, &name, on, true) {
if on {
chosen.retain(|c| c != file);
} else {
chosen.push(file.clone());
}
}
ui.add(egui::Label::new(egui::RichText::new(path).size(11.0).color(t.text_dim)).truncate()).on_hover_text(path);
}
if files.is_empty() && !state.is_empty() {
widgets::dim_label(ui, if searching { tl!("Searching…") } else { tl!("Not found") });
}
ui.add_space(3.0);
});
});
}
});
});
d.fields.insert("chosen".into(), json!(chosen));
ui.add_space(10.0);
let mut act = None;
let can_pick = crate::picks::can(app, &PickRequest::Folder);
ui.horizontal(|ui| {
let next = d.str("fontsNextToDocument");
if !next.is_empty() && ui.add_enabled(!searching, egui::Button::new(tl!("Search Fonts Folder"))).on_hover_text(&next).clicked() {
act = Some(Act::Search(next));
}
if can_pick && ui.add_enabled(!searching, egui::Button::new(tl!("Find in Folder…"))).clicked() {
act = Some(Act::Pick);
}
if searching {
if ui.button(tl!("Stop")).clicked() {
act = Some(Act::Stop);
}
ui.add(egui::Spinner::new().size(12.0).color(t.accent));
}
});
if searching {
widgets::dim_name(ui, &d.str("folder"));
}
if let Some(s) = d.fields.get("searched") {
let (folders, files) = (s["folders"].to_string(), s["files"].to_string());
widgets::dim_name(
ui,
&crate::i18n::fmt(tl!("{folders} folder(s) and {files} file(s) searched"), &[("folders", &folders), ("files", &files)]),
);
}
let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0).map(|n| n.to_string());
if let Some(n) = count("skipped") {
let text = tl!("{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones");
widgets::dim_name(ui, &crate::i18n::fmt(text, &[("count", &n)]));
}
if let Some(n) = count("unreadable") {
widgets::dim_name(ui, &crate::i18n::fmt(tl!("{count} folder(s) or file(s) couldn't be read"), &[("count", &n)]));
}
if matches!(d.fields.get("stopped").and_then(Value::as_str), Some("time" | "limit")) {
widgets::dim_label(ui, tl!("The search stopped at its limit: search a smaller folder."));
}
// Once files are found: what copying them means, and Add Fonts.
if found.iter().any(|f| f["files"].as_array().is_some_and(|files| !files.is_empty())) {
ui.add_space(8.0);
widgets::dim_label(ui, tl!("Copy only fonts you own or are licensed to install."));
if let Some(dir) = vectorcraft_text::app_font_dir() {
widgets::dim_name(ui, &crate::i18n::fmt(tl!("VectorCraft copies the fonts to {folder}."), &[("folder", &dir.to_string_lossy())]));
}
ui.add_space(6.0);
if ui.add_enabled(!searching && !chosen.is_empty(), egui::Button::new(tl!("Add Fonts"))).clicked() {
act = Some(Act::Add);
}
}
let r = match act {
Some(Act::Search(folder)) => start_search(app, d, &folder),
Some(Act::Pick) => crate::picks::in_dialog(app, d, |app, d| match crate::picks::folder(app) {
Some(folder) => start_search(app, d, &folder),
None => Ok(()),
}),
Some(Act::Stop) => app.run("text.findFontFiles", json!({ "stop": true })).map(|_| follow(app, d)),
// Added: the dialog closes.
Some(Act::Add) => match add_fonts(app, d) {
Ok(_) => return true,
Err(e) => Err(e),
},
None => Ok(()),
};
if let Err(e) = r {
app.status(e);
}
false
}
/// Find Fonts (`discard`): Type › Find Font on the first font the document misses, to replace it;
/// this Missing Fonts dialog doesn't come back. Otherwise (agents), with `searchFolder`: search that
/// folder, and stay open; else Add Fonts.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if d.bool("discard") {
app.ui.fonts_dialog = None;
// Find Font works on the active document; the dialog's may be another tab.
let uid = d.fields.get("document").and_then(Value::as_u64);
let index = app.session.documents().iter().position(|doc| Some(doc.uid) == uid).ok_or("that document is no longer open")?;
app.run("document.activate", json!({ "index": index }))?;
crate::find_font::open_on_missing(app);
return Ok(Value::Null);
}
let folder = d.str("searchFolder");
if !folder.is_empty() {
let mut d = d.clone();
d.fields.remove("searchFolder");
// The folder is searched once: a search that doesn't start leaves the dialog without it.
if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) {
open.fields.remove("searchFolder");
}
start_search(app, &mut d, &folder)?;
let state = d.fields.get("state").cloned().unwrap_or(Value::Null);
app.ui.dialog = Some(d);
return Ok(json!({ "state": state }));
}
add_fonts(app, d)
}
/// Add Fonts: copy the chosen files into VectorCraft's Fonts folder and close.
fn add_fonts(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let chosen = d.fields.get("chosen").and_then(Value::as_array).cloned().unwrap_or_default();
if chosen.is_empty() {
return Err("choose the font files to add".into());
}
let r = app.run("text.addFontFiles", json!({ "files": chosen }))?;
app.ui.dialog = None;
let len = |k: &str| r[k].as_array().map_or(0, Vec::len);
let n = len("copied") + len("kept");
let folder = r["folder"].as_str().unwrap_or_default();
match r["skipped"].as_array().and_then(|s| s.first()) {
None => app.status(format!("{n} font file(s) are now in {folder}")),
Some(first) => {
let failed = len("skipped");
let file =
first["file"].as_str().map(std::path::Path::new).and_then(std::path::Path::file_name).map(|f| f.to_string_lossy().into_owned());
let reason = format!("{}: {}", file.unwrap_or_default(), first["reason"].as_str().unwrap_or_default());
app.status(format!("{n} font file(s) are now in {folder}; {failed} couldn't be added: {reason}"));
}
}
Ok(r)
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::time::Instant;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::findfiles::Rules;
use super::*;
fn frame(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
/// A fresh temporary folder (canonical, as a search reports it).
fn folder(tag: &str) -> PathBuf {
let dir = vectorcraft_testkit::temp_dir(&format!("missing-fonts-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
vectorcraft_engine::cmd::findfiles::plain(std::fs::canonicalize(&dir).unwrap())
}
/// An app that reads files and whose searches may go anywhere in `root`, on two threads.
fn app_for(root: &Path) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
app.session.search_rules = Some(Rules { user_content: vec![root.to_path_buf()], ..Rules::default() });
app.session.search_threads = Some(2);
app
}
fn png() -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::from_pixel(40, 30, image::Rgba([200, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.unwrap();
out
}
/// Save a new document with type in `font` at `path`, with a linked image that is then deleted
/// when `link`.
fn save_doc(app: &mut VectorcraftApp, path: &Path, font: &str, link: bool) {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let pic = path.with_extension("png");
if link {
std::fs::write(&pic, png()).unwrap();
app.run("file.place", json!({"path": pic.to_string_lossy()})).unwrap();
}
app.run("text.create", json!({"x": 10, "y": 40, "text": "Type", "font": font})).unwrap();
app.run("document.save", json!({"path": path.to_string_lossy()})).unwrap();
if link {
std::fs::remove_file(&pic).unwrap();
}
}
fn open(app: &mut VectorcraftApp, path: &Path) {
crate::io::open_path(app, &path.to_string_lossy()).unwrap();
}
fn kind(app: &VectorcraftApp) -> Option<&str> {
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
}
#[test]
fn missing_fonts_are_asked_about_after_the_missing_links() {
let root = folder("after-links");
let mut app = app_for(&root);
let doc = root.join("doc.vectorcraft");
save_doc(&mut app, &doc, "No Such Font Family", true);
open(&mut app, &doc);
assert_eq!(kind(&app), Some(super::super::missing_links::KIND));
super::super::cancel(&mut app);
let d = app.ui.dialog.as_ref().expect("Missing Fonts after the linked files");
assert_eq!((d.kind.as_str(), d.fields["fonts"][0]["family"].as_str()), (KIND, Some("No Such Font Family")));
let text = frame(&mut app);
for label in
["Missing Fonts", "No Such Font Family Regular", "These fonts aren't available. Their text shows in another font.", "Find Fonts", "Close"]
{
assert!(text.contains(label), "{label} in {text}");
}
assert!(!text.contains("Search Fonts Folder"), "no Fonts folder next to the document");
assert!(!text.contains("Add Fonts") && !text.contains("Copy only fonts"), "no file found yet: {text}");
assert_eq!(super::super::confirm(&mut app).err().as_deref(), Some("choose the font files to add"));
assert_eq!(kind(&app), Some(KIND), "nothing to add: the dialog stays open");
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none());
}
#[test]
fn the_documents_fonts_folder_is_offered_and_searched_off_the_ui_thread() {
let root = folder("package");
let font = root.join("pkg").join("Fonts").join("sub").join("Findme.otf");
std::fs::create_dir_all(font.parent().unwrap()).unwrap();
std::fs::write(&font, vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
let mut app = app_for(&root);
let doc = root.join("pkg/doc.vectorcraft");
save_doc(&mut app, &doc, "Findme Sans 3", false);
open(&mut app, &doc);
let next = app.ui.dialog.as_ref().filter(|d| d.kind == KIND).expect("Missing Fonts at once: no links missing").str("fontsNextToDocument");
assert_eq!(next, root.join("pkg").join("Fonts").to_string_lossy());
assert!(frame(&mut app).contains("Search Fonts Folder"));
app.ui.dialog.as_mut().unwrap().fields.insert("searchFolder".into(), json!(next));
let r = super::super::confirm(&mut app).unwrap();
assert!(matches!(r["state"].as_str(), Some("searching" | "done")), "{r}");
assert_eq!(kind(&app), Some(KIND), "the dialog stays open while it searches");
let until = Instant::now() + Duration::from_secs(10);
while app.ui.dialog.as_ref().is_some_and(|d| d.str("state") == "searching") && Instant::now() < until {
frame(&mut app);
std::thread::sleep(Duration::from_millis(5));
}
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.str("state"), &d.fields["found"][0]["files"]), ("done".to_string(), &json!([font])));
assert_eq!(d.fields["chosen"], json!([font]), "the font's file is chosen");
let text = frame(&mut app);
for label in ["Findme.otf", "Copy only fonts you own or are licensed to install.", "Add Fonts"] {
assert!(text.contains(label), "{label} in {text}");
}
// Adding needs VectorCraft's Fonts folder, which only the apps set.
let e = super::super::confirm(&mut app).unwrap_err();
assert!(e.contains("isn't set here"), "{e}");
assert_eq!(kind(&app), Some(KIND));
}
/// Find Fonts opens Type › Find Font on the first missing font, to replace it, and the Missing
/// Fonts dialog doesn't come back for that open.
#[test]
fn find_fonts_opens_find_font_on_the_missing_font() {
let root = folder("find-fonts");
let mut app = app_for(&root);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Here", "font": "Source Sans 3"})).unwrap();
app.run("text.create", json!({"x": 10, "y": 80, "text": "Gone", "font": "Zz Missing Family"})).unwrap();
let doc = root.join("doc.vectorcraft");
app.run("document.save", json!({"path": doc.to_string_lossy()})).unwrap();
open(&mut app, &doc);
assert_eq!(kind(&app), Some(KIND));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
super::super::confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().expect("Find Font");
assert_eq!(d.kind, "findFont");
let fonts = app.session.execute("text.fonts", &json!({})).unwrap();
let selected = d.fields["selected"].as_u64().unwrap() as usize;
assert!(selected > 0 && fonts[selected]["family"] == "Zz Missing Family", "{selected} in {fonts}");
// Find Font closed: no Missing Fonts dialog follows.
app.ui.dialog = None;
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
}
/// The dialog of a document in another tab: Find Fonts makes that document the active one, so
/// Find Font lists and replaces its fonts.
#[test]
fn find_fonts_works_on_the_dialog_s_own_document() {
let root = folder("find-fonts-tab");
let mut app = app_for(&root);
let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft"));
save_doc(&mut app, &a, "Alpha Missing Family", false);
save_doc(&mut app, &b, "Beta Missing Family", true);
open(&mut app, &a);
open(&mut app, &b);
// B's linked files are asked about first; then A's fonts, with B the active tab.
super::super::cancel(&mut app);
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(d.fields["fonts"][0]["family"], "Alpha Missing Family");
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(&*b.to_string_lossy()));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(&*a.to_string_lossy()));
let fonts = app.session.execute("text.fonts", &json!({})).unwrap();
let selected = app.ui.dialog.as_ref().unwrap().fields["selected"].as_u64().unwrap() as usize;
assert_eq!(fonts[selected]["family"], "Alpha Missing Family", "{fonts}");
}
#[test]
fn closing_the_dialog_stops_its_search() {
let root = folder("stop");
// Enough folders that the search usually still runs when the dialog closes.
for a in 0..40 {
for b in 0..40 {
std::fs::create_dir_all(root.join(format!("f{a}/g{b}"))).unwrap();
}
}
let mut app = app_for(&root);
app.session.search_threads = Some(1);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap();
app.run("ui.missingFontsDialog", json!({"folder": root})).unwrap();
let id = app.ui.dialog_search.expect("the dialog's search");
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.dialog_search.is_none());
// Stopped by the close, unless the walker finished the folders first.
let r = app.session.execute("text.findFontFiles", &json!({})).unwrap();
assert_eq!(r["id"].as_u64(), Some(id), "{r}");
match r["state"].as_str() {
Some("stopped") => assert_eq!(r["stopped"], "stop", "{r}"),
state => assert_eq!(state, Some("done"), "{r}"),
}
// Without missing fonts there is nothing to open.
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
assert_eq!(app.run("ui.missingFontsDialog", json!({})).err().as_deref(), Some("No fonts are missing in this document"));
}
#[test]
fn one_dialog_at_a_time_document_by_document() {
let root = folder("queue");
let mut app = app_for(&root);
let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft"));
save_doc(&mut app, &a, "Alpha Missing Family", false);
save_doc(&mut app, &b, "Beta Missing Family", true);
open(&mut app, &a);
let family = |app: &VectorcraftApp| app.ui.dialog.as_ref().and_then(|d| d.fields["fonts"][0]["family"].as_str().map(str::to_string));
assert_eq!(family(&app).as_deref(), Some("Alpha Missing Family"));
// The second document's linked files are asked about first; then each document's fonts.
open(&mut app, &b);
assert_eq!(kind(&app), Some(super::super::missing_links::KIND));
super::super::cancel(&mut app);
assert_eq!(family(&app).as_deref(), Some("Alpha Missing Family"));
super::super::cancel(&mut app);
assert_eq!(family(&app).as_deref(), Some("Beta Missing Family"));
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none());
// A document closed before its turn is passed over.
open(&mut app, &a);
open(&mut app, &b);
let index = app.session.documents().iter().rposition(|d| d.path.as_deref() == Some(&*a.to_string_lossy())).unwrap();
app.session.execute("file.close", &json!({"index": index})).unwrap();
super::super::cancel(&mut app);
assert_eq!(family(&app).as_deref(), Some("Beta Missing Family"));
}
/// Another dialog that takes the Missing Fonts dialog's place (Import PDF for a PDF dropped
/// with the document) hands the question back once it closes.
#[test]
fn the_question_comes_back_after_a_dialog_that_took_its_place() {
let root = folder("replaced");
let mut app = app_for(&root);
let doc = root.join("a.vectorcraft");
save_doc(&mut app, &doc, "Alpha Missing Family", false);
let pdf = || {
let page = || vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f");
vectorcraft_testkit::pdf::pdf(&[page(), page()], None)
};
let opened = |name: &str, path: Option<String>, bytes: Vec<u8>| (crate::place::DropTarget::Open, (name.to_string(), path, bytes));
let files =
vec![opened("a.vectorcraft", Some(doc.to_string_lossy().into_owned()), std::fs::read(&doc).unwrap()), opened("b.pdf", None, pdf())];
crate::place::drop_files(&mut app, files);
assert_eq!(kind(&app), Some(super::super::import_pdf::KIND));
super::super::cancel(&mut app);
let family = |app: &VectorcraftApp| app.ui.dialog.as_ref().filter(|d| d.kind == KIND).map(|d| d.fields["fonts"][0]["family"].clone());
assert_eq!(family(&app), Some(json!("Alpha Missing Family")));
// The same when a frame drew the other dialog before it closed.
crate::io::open_bytes(&mut app, "c.pdf", &pdf(), None).unwrap();
assert_eq!(kind(&app), Some(super::super::import_pdf::KIND));
frame(&mut app);
super::super::cancel(&mut app);
assert_eq!(family(&app), Some(json!("Alpha Missing Family")));
// Closed by Cancel, or by Escape (which empties the dialog slot), it stays closed.
super::super::cancel(&mut app);
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
app.run("ui.missingFontsDialog", json!({})).unwrap();
app.ui.dialog = None;
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
}
/// Type in a CSS generic family (`sans-serif`, the default font of SVG files from some editors)
/// opens without the question.
#[test]
fn generic_families_are_not_asked_about() {
let mut app = app_for(&folder("generic"));
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><text x="10" y="40" font-family="sans-serif">A</text></svg>"#;
crate::io::open_bytes(&mut app, "generic.svg", svg.as_bytes(), None).unwrap();
let listed = app.session.execute("text.fonts", &json!({})).unwrap();
assert!(listed.as_array().unwrap().iter().any(|f| f["family"] == "sans-serif"), "{listed}");
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
}
/// A `searchFolder` whose search doesn't start is dropped from the dialog: OK doesn't try it
/// again.
#[test]
fn a_search_folder_that_fails_is_not_tried_again() {
let root = folder("retry");
let mut app = app_for(&root);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap();
app.run("ui.missingFontsDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("searchFolder".into(), json!("relative/folder"));
let e = super::super::confirm(&mut app).unwrap_err();
assert!(e.contains("absolute"), "{e}");
assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("searchFolder"));
assert_eq!(super::super::confirm(&mut app).err().as_deref(), Some("choose the font files to add"));
}
/// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does.
#[test]
fn edit_original_asks_about_the_placed_documents_fonts() {
let root = folder("edit-original");
let mut app = app_for(&root);
let badge = root.join("badge.vectorcraft");
save_doc(&mut app, &badge, "Badge Missing Family", false);
app.session.execute("file.close", &json!({})).unwrap();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": badge.to_string_lossy(), "link": true})).unwrap();
let tabs = app.session.documents().len();
app.run("links.editOriginal", json!({})).unwrap();
assert_eq!(app.session.documents().len(), tabs + 1);
let d = app.ui.dialog.as_ref().expect("Missing Fonts for the document opened");
assert_eq!((d.kind.as_str(), d.fields["fonts"][0]["family"].as_str()), (KIND, Some("Badge Missing Family")));
}
/// A search leaves out the fonts that became available: the files it found go with their fonts
/// by name, and a file the user unchecked stays unchecked as the search goes on.
#[test]
fn files_go_with_their_fonts_by_name() {
let (a, b) = (json!({"family": "A Sans", "style": "Regular"}), json!({"family": "B Sans", "style": "Bold"}));
let mut d = Dialog::new(KIND, json!({"fonts": [a, b], "chosen": []}));
update(&mut d, &json!({"state": "searching", "fonts": [{"family": "B Sans", "style": "Bold", "files": ["/f/b.otf"]}]}));
let found = d.fields["found"].as_array().unwrap().clone();
assert!(files_for(&found, &a).is_empty());
assert_eq!(files_for(&found, &b), [json!("/f/b.otf")]);
assert_eq!(d.fields["chosen"], json!(["/f/b.otf"]));
d.fields.insert("chosen".into(), json!([]));
update(&mut d, &json!({"state": "done", "fonts": [{"family": "B Sans", "style": "Bold", "files": ["/f/b.otf", "/g/b.otf"]}]}));
assert_eq!((d.str("state"), &d.fields["chosen"]), ("done".to_string(), &json!([])));
}
/// The status lines are translated with the reasons in them, and so are the reasons a search
/// failed and a file wasn't copied, which the code holds as constants.
#[test]
fn the_status_lines_read_in_the_interface_language() {
let fr = crate::i18n::Lang::from_code("fr").unwrap();
let shown = crate::i18n::message(fr, "2 font file(s) are now in /Fonts; 1 couldn't be added: a.otf: larger than 256 MB");
assert!(shown.contains("se trouvent maintenant dans /Fonts") && shown.contains("a.otf") && shown.contains("plus de 256 Mo"), "{shown}");
for code in ["es", "fr", "it", "ru"] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for s in [
"every search thread stopped on an internal error (please report this bug)",
"not a file",
"not a font file",
"the files come to more than 1 GB: add fewer at a time",
"every numbered name for it is taken in the Fonts folder",
] {
assert_ne!(crate::i18n::message(lang, s), s, "{code}");
}
}
}
#[test]
fn the_web_says_how_many_fonts_are_missing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap();
after_open_for(&mut app, &json!({}), true);
assert_eq!(app.ui.status, "1 font(s) aren't available here: their text shows in another font");
assert!(app.ui.pending_fonts.is_empty());
// The open's notes stay on show.
app.ui.status = "Opened with 1 note(s): fonts".into();
after_open_for(&mut app, &json!({"warnings": ["fonts"]}), true);
assert_eq!(app.ui.status, "Opened with 1 note(s): fonts");
}
}
+8 -3
View File
@@ -35,18 +35,23 @@ fn ids(rows: &[Value]) -> Vec<Value> {
}
/// After a document opened (`document.open`'s result `r`): ask about its missing linked files,
/// then about its modified ones. The web reads no linked files, so missing ones just show their
/// then about its modified ones, then about the fonts it opened without
/// ([`super::missing_fonts`]). The web reads no linked files, so missing ones just show their
/// previews there.
pub fn after_open(app: &mut VectorcraftApp, r: &Value) {
// The fonts' dialog waits for these questions (one dialog at a time).
super::missing_fonts::after_open(app, r);
let rows = |k: &str| r[k].as_array().cloned().unwrap_or_default();
let (missing, modified) = (rows("missingLinks"), ids(&rows("modifiedLinks")));
if missing.is_empty() || cfg!(target_arch = "wasm32") {
if !missing.is_empty() {
app.status(format!("{} linked file(s) can't be read here: their previews show", missing.len()));
}
return ask_update(app, modified);
ask_update(app, modified);
} else {
open(app, missing, modified);
}
open(app, missing, modified);
super::settle(app);
}
fn open(app: &mut VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>) {
+19 -1
View File
@@ -39,6 +39,7 @@ pub mod import_pdf;
pub mod layer_options;
pub mod layers_panel_options;
pub mod liquify;
pub mod missing_fonts;
pub mod missing_links;
pub(crate) mod modal;
pub mod new_color_group;
@@ -215,6 +216,7 @@ registry! {
FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)),
SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC,
Confirm: [confirm::KIND] => confirm::SPEC,
Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC,
NewSwatch: [new_swatch::KIND] => new_swatch::SPEC,
NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC,
GradientStop: ["gradientStop"] => gradient_stop::SPEC,
@@ -246,6 +248,7 @@ registry! {
FileInfo: [file_info::KIND] => file_info::SPEC,
RasterEffectsSettings: [raster_effects::KIND] => raster_effects::SPEC,
MissingLinks: [missing_links::KIND] => missing_links::SPEC,
MissingFonts: [missing_fonts::KIND] => missing_fonts::SPEC,
TextImport: [text_import::KIND] => text_import::SPEC,
PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC,
PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC,
@@ -310,20 +313,35 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes
/// Close the open dialog as Cancel does, rolling back a live preview (`ui.dialog.cancel`).
pub fn cancel(app: &mut VectorcraftApp) {
missing_fonts::requeue_replaced(app);
if app.ui.dialog.take().is_some_and(|d| spec(&d.kind).preview) {
let _ = app.session.cancel_interaction();
}
settle(app);
}
/// Apply the open dialog (OK).
pub fn confirm(app: &mut VectorcraftApp) -> DialogResult {
missing_fonts::requeue_replaced(app);
let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) };
// A file dialog it shows off the UI thread confirms the dialog as it is again.
crate::picks::as_entry(app, || crate::picks::Entry::Confirm(Box::new(d.clone())), |app| (spec(&d.kind).confirm)(app, &d))
let r = crate::picks::as_entry(app, || crate::picks::Entry::Confirm(Box::new(d.clone())), |app| (spec(&d.kind).confirm)(app, &d));
settle(app);
r
}
/// After a dialog closes, and each frame: a Missing Fonts dialog that another dialog replaced waits
/// for its turn again, the search a Missing Fonts dialog started stops once that dialog is gone,
/// and with no dialog open the next document's Missing Fonts dialog opens (one dialog at a time).
pub(crate) fn settle(app: &mut VectorcraftApp) {
missing_fonts::requeue_replaced(app);
missing_fonts::stop_when_closed(app);
missing_fonts::open_next(app);
}
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
about::show(app, ctx);
settle(app);
// The kind of dialog shown last frame: a different one (or none) means this one just opened, and
// its first field is to take the keyboard focus (`focus_id`, until a field takes it).
let (shown_id, focus_id) = (egui::Id::new("dialog-shown"), egui::Id::new("dialog-focus-pending"));
+56 -3
View File
@@ -1,5 +1,6 @@
//! Type → Find Font…: the fonts the document uses (missing ones marked), Find (select the text
//! using a font), and Change / Change All to another installed font.
//! using a font), Change / Change All to another installed font, and Find in Folder… (the missing
//! fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`).
use egui::Ui;
use serde_json::{Value, json};
@@ -11,7 +12,19 @@ use crate::{VectorcraftApp, font_menu};
/// Open the dialog.
pub fn open(app: &mut VectorcraftApp) {
app.ui.dialog = Some(Dialog::new("findFont", json!({ "selected": 0, "family": "Source Sans 3", "style": "", "selectionOnly": false })));
open_at(app, 0);
}
/// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find
/// Fonts).
pub fn open_on_missing(app: &mut VectorcraftApp) {
let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
open_at(app, first.unwrap_or(0));
}
/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen.
fn open_at(app: &mut VectorcraftApp, selected: usize) {
app.ui.dialog = Some(Dialog::new("findFont", json!({ "selected": selected, "family": "Source Sans 3", "style": "", "selectionOnly": false })));
}
fn fonts(app: &mut VectorcraftApp) -> Vec<Value> {
@@ -35,7 +48,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let t = Tokens::get(ctx);
let list = fonts(app);
let sample = font_menu::sample_text(app);
// Find in Folder… shows when the document misses fonts, fonts used only in its symbols included.
let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder)
&& app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
let mut close = false;
let mut find_in_folder = false;
let mut act: Option<&str> = None;
crate::dialogs::modal::show(ctx, tl!("Find Font"), egui::Id::new("dialog-find-font"), -40.0, 22, |ui: &mut Ui| {
ui.set_width(380.0);
@@ -57,6 +74,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
});
});
// The missing fonts' files, looked for in a folder (the Missing Fonts dialog).
if offer_folder {
ui.add_space(6.0);
find_in_folder = ui.button(tl!("Find in Folder…")).clicked();
}
ui.add_space(10.0);
widgets::subheader(ui, tl!("Replace With Font"));
let fam = d.str("family");
@@ -113,11 +135,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
} else if app.ui.dialog.is_some() {
app.ui.dialog = Some(d);
}
// Missing Fonts takes the dialog's place, searching the folder picked.
if find_in_folder && let Err(e) = app.run("ui.findFontsInFolder", json!({})) {
app.ui.status = e;
}
}
/// What a Find Font row says after the font's name (`text.fonts` row): a missing family, a style
/// standing in for another, characters the font lacks; and the colour to flag it with.
fn font_note(f: &Value) -> (String, Option<egui::Color32>) {
pub(crate) fn font_note(f: &Value) -> (String, Option<egui::Color32>) {
let lacking = f["missingGlyphs"].as_u64().unwrap_or(0);
let glyphs =
if lacking > 0 { crate::i18n::fmt(tl!(" — {n} characters from another font"), &[("n", &lacking.to_string())]) } else { String::new() };
@@ -156,6 +182,33 @@ mod tests {
assert_eq!(fonts(&mut app)[0]["family"], "Source Sans 3");
}
#[test]
fn find_in_folder_puts_the_missing_fonts_dialog_in_find_fonts_place() {
let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder")).unwrap();
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { user_content: vec![dir.clone()], ..Default::default() });
app.session.search_threads = Some(1);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(!crate::menus::enabled(&app, "ui.findFontsInFolder"), "no folder picker (the web)");
let picked = dir.to_string_lossy().into_owned();
app.services.pick_folder = Some(Box::new(move || Some(picked.clone())));
assert!(crate::menus::enabled(&app, "ui.findFontsInFolder"));
// Nothing missing: no button, and no folder is asked for.
open(&mut app);
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
assert!(text.contains("Fonts in Document") && !text.contains("Find in Folder…"), "{text}");
assert_eq!(app.run("ui.findFontsInFolder", json!({})).err().as_deref(), Some("No fonts are missing in this document"));
app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
assert!(text.contains("Find in Folder…"), "{text}");
app.run("ui.findFontsInFolder", json!({})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), d.str("folder")), (crate::dialogs::missing_fonts::KIND, dir.to_string_lossy().into_owned()));
assert_eq!(d.fields["fonts"][0]["family"], "Missing Family");
assert!(app.ui.dialog_search.is_some());
crate::dialogs::cancel(&mut app);
}
#[test]
fn rows_flag_missing_fonts_substituted_styles_and_lacking_characters() {
let row = |status: &str, glyphs: u64| json!({"status": status, "resolved": {"style": "W4"}, "missingGlyphs": glyphs});
+1
View File
@@ -9,6 +9,7 @@
# back to English. Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name,
# language names, OpenType, the built-in workspace names and the bracketed perspective grid preset
# names.
Glowing Edges… Zářící okraje…
About VectorCraft O aplikaci VectorCraft
Align to Path Zarovnat k cestě
Cut Path at Selected Anchor Points Rozdělit cestu ve vybraných kotevních bodech
Can't render this file because it contains an unexpected character in line 2 and column 73.
+54
View File
@@ -12,6 +12,11 @@
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
# Photoshop-style raster effects (Effect menu, their dialogs).
Glowing Edges… Bordes resplandecientes…
Glowing Edges Bordes resplandecientes
Edge Width Ancho del borde
Edge Brightness Brillo del borde
Smoothness Suavizado
Radial Blur… Desenfoque radial…
Smart Blur… Desenfoque inteligente…
Sharpen Enfocar
@@ -681,6 +686,7 @@
Divide Vertically Into Dividir verticalmente en
Do Not Move No mover
Do you want to save the changes you made to “{name}”? ¿Quieres guardar los cambios hechos en “{name}”?
Can't open “{name}”. No se puede abrir «{name}».
Document Documento
Document Color Mode Modo de color del documento
Document Info Información del documento
@@ -1492,6 +1498,8 @@
Monospaced Monoespaciada
More Más
More Pathfinder options Más opciones de Buscatrazos
More Align options Más opciones de alineación
More Paragraph options Más opciones de párrafo
More Settings Más ajustes
Move Mover
Move All Objects Mover todos los objetos
@@ -2062,6 +2070,25 @@
Reflect… Reflejar…
Refresh Actualizar
Refresh Font List Actualizar lista de fuentes
Missing Fonts Fuentes que faltan
Missing Fonts Dialog Cuadro de diálogo Fuentes que faltan
These fonts aren't available. Their text shows in another font. Estas fuentes no están disponibles. Su texto se muestra con otra fuente.
Search Fonts Folder Buscar en la carpeta Fonts
Find in Folder… Buscar en una carpeta…
Find Fonts in Folder… Buscar fuentes en una carpeta…
Find Font Files Buscar archivos de fuentes
Add Font Files Agregar archivos de fuentes
Add Fonts Agregar fuentes
Find Fonts Buscar fuentes
Stop Detener
Searching… Buscando…
Not found No se encontró
{folders} folder(s) and {files} file(s) searched Se buscó en {folders} carpeta(s) y {files} archivo(s)
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Se omitieron {count} carpeta(s), como las de otras aplicaciones y del sistema y las ocultas
{count} folder(s) or file(s) couldn't be read No se pudieron leer {count} carpeta(s) o archivo(s)
The search stopped at its limit: search a smaller folder. La búsqueda se detuvo en su límite: busca en una carpeta más pequeña.
Copy only fonts you own or are licensed to install. Copia solo fuentes que te pertenezcan o cuya licencia te permita instalarlas.
VectorCraft copies the fonts to {folder}. VectorCraft copia las fuentes en {folder}.
Registered Trademark Symbol Símbolo de marca registrada
Registration marks Marcas de registro
Registry name: Nombre del registro:
@@ -2540,6 +2567,9 @@
Smart Guides (⌘U) Guías inteligentes (⌘U)
Smart Punctuation… Puntuación inteligente…
Smooth Suavizar
Corner Vértice
Relative Relativo
Absolute Absoluto
Smooth Color Color suavizado
Smooth Tool Herramienta Suavizar
Snap Curves To Lines Ajustar curvas a líneas
@@ -3325,6 +3355,7 @@ axis Both Ambos
@msg cannot distort a zero-size bounding box no se puede distorsionar un cuadro delimitador de tamaño cero
@msg cannot read PDF: {0} no se puede leer el PDF: {0}
@msg cannot split an open path at its end point no se puede dividir un trazado abierto en su punto final
@msg closing needs three anchors cerrar necesita tres puntos de ancla
@msg check an asset to export marca un recurso para exportar
@msg choice must be "merge" or "add", not `{choice}` choice debe ser "merge" o "add", no `{choice}`
@msg choose a direction to divide in elige una dirección en la que dividir
@@ -3714,6 +3745,24 @@ axis Both Ambos
@msg an image whose data is cut short was left out se omitió una imagen con datos incompletos
@msg its editing data doesn't say where its art is sus datos de edición no dicen dónde está su ilustración
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) este archivo se guardó sin compatibilidad con PDF y sus datos de edición no se pueden leer ({why})
@msg No fonts are missing in this document No faltan fuentes en este documento
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no busca en carpetas de otras aplicaciones ni del sistema: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft no busca en las carpetas Shared ni Public de Users: {path}
@msg {path} is not a folder {path} no es una carpeta
@msg the search couldn't start: try again in a moment no se pudo iniciar la búsqueda: inténtalo de nuevo en un momento
@msg searching a folder isn't available on the web en la web no se puede buscar en una carpeta
@msg every search thread stopped on an internal error (please report this bug) todos los hilos de búsqueda se detuvieron por un error interno (informa de este error)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it La carpeta Fonts de VectorCraft no está configurada aquí: la configuran la aplicación de escritorio y vectorcraft-cli
@msg choose the font files to add elige los archivos de fuentes que quieres agregar
@msg {n} font file(s) are now in {folder} {n} archivo(s) de fuentes ahora están en {folder}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} archivo(s) de fuentes ahora están en {folder}; no se pudieron agregar {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font aquí no están disponibles {n} fuente(s): su texto se muestra con otra fuente
@msg not a file no es un archivo
@msg not a font file no es un archivo de fuente
@msg that document is no longer open ese documento ya no está abierto
@msg larger than 256 MB mayor de 256 MB
@msg the files come to more than 1 GB: add fewer at a time los archivos suman más de 1 GB: agrega menos a la vez
@msg every numbered name for it is taken in the Fonts folder todos los nombres numerados para él ya existen en la carpeta Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Servicios
@@ -3734,3 +3783,8 @@ axis Both Ambos
Constrain Restringir
Free Transform Transformación libre
Perspective Distort Distorsión de perspectiva
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` es la referencia a un paso {r}, que solo `run` y `command_batch` resuelven
@msg `ids` must be an array of object ids, not {v} `ids` debe ser una lista de identificadores de objeto, no {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: el resultado del paso {i} no tiene ese valor (escriba $$ para un $ literal)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: no hay ningún paso {i} antes de este (los pasos se cuentan desde 0; escriba $$ para un $ literal)
@msg object ids are non-negative integers, not {v} los identificadores de objeto son enteros no negativos, no {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+54
View File
@@ -13,6 +13,11 @@
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
# Photoshop-style raster effects (Effect menu, their dialogs).
Glowing Edges… Bords lumineux…
Glowing Edges Bords lumineux
Edge Width Largeur du bord
Edge Brightness Luminosité du bord
Smoothness Lissage
Radial Blur… Flou radial…
Smart Blur… Flou intelligent…
Sharpen Netteté
@@ -683,6 +688,7 @@
Divide Vertically Into Diviser verticalement en
Do Not Move Ne pas déplacer
Do you want to save the changes you made to “{name}”? Voulez-vous enregistrer les modifications apportées à « {name} » ?
Can't open “{name}”. Impossible d’ouvrir « {name} ».
Document Document
Document Color Mode Mode colorimétrique du document
Document Info Informations sur le document
@@ -1491,6 +1497,8 @@
Monospaced À chasse fixe
More Plus
More Pathfinder options Plus d’options Pathfinder
More Align options Plus d’options d’alignement
More Paragraph options Plus d’options de paragraphe
More Settings Plus de réglages
Move Déplacer
Move All Objects Déplacer tous les objets
@@ -2059,6 +2067,25 @@
Reflect… Miroir…
Refresh Actualiser
Refresh Font List Actualiser la liste des polices
Missing Fonts Polices manquantes
Missing Fonts Dialog Boîte de dialogue Polices manquantes
These fonts aren't available. Their text shows in another font. Ces polices ne sont pas disponibles. Leur texte s’affiche dans une autre police.
Search Fonts Folder Rechercher dans le dossier Fonts
Find in Folder… Rechercher dans un dossier…
Find Fonts in Folder… Rechercher des polices dans un dossier…
Find Font Files Rechercher des fichiers de polices
Add Font Files Ajouter des fichiers de polices
Add Fonts Ajouter les polices
Find Fonts Rechercher les polices
Stop Arrêter
Searching… Recherche…
Not found Introuvable
{folders} folder(s) and {files} file(s) searched {folders} dossier(s) et {files} fichier(s) parcourus
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} dossier(s) ignoré(s), comme ceux d’autres apps et du système et les dossiers masqués
{count} folder(s) or file(s) couldn't be read {count} dossier(s) ou fichier(s) illisible(s)
The search stopped at its limit: search a smaller folder. La recherche s’est arrêtée à sa limite : recherchez dans un dossier plus petit.
Copy only fonts you own or are licensed to install. Ne copiez que des polices qui vous appartiennent ou dont la licence vous autorise l’installation.
VectorCraft copies the fonts to {folder}. VectorCraft copie les polices dans {folder}.
Registered Trademark Symbol Symbole de marque déposée
Registration marks Repères de montage
Registry name: Nom du registre :
@@ -2537,6 +2564,9 @@
Smart Guides (⌘U) Repères commandés (⌘U)
Smart Punctuation… Ponctuation typographique…
Smooth Lisser
Corner Angle
Relative Relatif
Absolute Absolu
Smooth Color Couleur lissée
Smooth Tool Outil Arrondi
Snap Curves To Lines Aimanter les courbes aux lignes
@@ -3322,6 +3352,7 @@ axis Both Les deux
@msg cannot distort a zero-size bounding box impossible de déformer un cadre de sélection de taille nulle
@msg cannot read PDF: {0} impossible de lire le PDF : {0}
@msg cannot split an open path at its end point impossible de scinder un tracé ouvert à son extrémité
@msg closing needs three anchors la fermeture nécessite trois points d’ancrage
@msg check an asset to export cochez une ressource à exporter
@msg choice must be "merge" or "add", not `{choice}` choice doit valoir "merge" ou "add", pas `{choice}`
@msg choose a direction to divide in choisissez une direction de division
@@ -3711,6 +3742,24 @@ axis Both Les deux
@msg an image whose data is cut short was left out une image aux données tronquées a été ignorée
@msg its editing data doesn't say where its art is ses données d’édition ne disent pas où se trouve son illustration
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ce fichier a été enregistré sans compatibilité PDF et ses données d’édition sont illisibles ({why})
@msg No fonts are missing in this document Aucune police ne manque dans ce document
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft ne recherche pas dans les dossiers d’autres apps ni du système : {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft ne recherche pas dans les dossiers Shared et Public de Users : {path}
@msg {path} is not a folder {path} n’est pas un dossier
@msg the search couldn't start: try again in a moment la recherche n’a pas pu démarrer : réessayez dans un instant
@msg searching a folder isn't available on the web la recherche dans un dossier n’est pas disponible sur le web
@msg every search thread stopped on an internal error (please report this bug) tous les fils de recherche se sont arrêtés sur une erreur interne (veuillez signaler ce bogue)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Le dossier Fonts de VectorCraft n’est pas défini ici : l’application de bureau et vectorcraft-cli le définissent
@msg choose the font files to add choisissez les fichiers de polices à ajouter
@msg {n} font file(s) are now in {folder} {n} fichier(s) de polices se trouvent maintenant dans {folder}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} fichier(s) de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}
@msg {n} font(s) aren't available here: their text shows in another font {n} police(s) indisponible(s) ici : leur texte s’affiche dans une autre police
@msg not a file n’est pas un fichier
@msg not a font file n’est pas un fichier de police
@msg that document is no longer open ce document n’est plus ouvert
@msg larger than 256 MB plus de 256 Mo
@msg the files come to more than 1 GB: add fewer at a time les fichiers dépassent 1 Go : ajoutez-en moins à la fois
@msg every numbered name for it is taken in the Fonts folder tous les noms numérotés pour ce fichier sont déjà pris dans le dossier Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Services
@@ -3745,3 +3794,8 @@ axis Both Les deux
Insert Inline Symbol Insérer un symbole dans le texte
ICF Top/Right ICF haut/droite
ICF Bottom/Left ICF bas/gauche
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` est la référence d’étape {r}, que seuls `run` et `command_batch` résolvent
@msg `ids` must be an array of object ids, not {v} `ids` doit être une liste d’identifiants d’objet, pas {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}` : le résultat de l’étape {i} n’a pas cette valeur (écrivez $$ pour un $ littéral)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}` : il n’y a pas d’étape {i} avant celle-ci (les étapes sont comptées à partir de 0 ; écrivez $$ pour un $ littéral)
@msg object ids are non-negative integers, not {v} les identifiants d’objet sont des entiers positifs ou nuls, pas {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+54
View File
@@ -12,6 +12,11 @@
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
# Photoshop-style raster effects (Effect menu, their dialogs).
Glowing Edges… Bordi luminosi…
Glowing Edges Bordi luminosi
Edge Width Larghezza bordo
Edge Brightness Luminosità bordo
Smoothness Uniformità
Radial Blur… Sfocatura radiale…
Smart Blur… Sfocatura intelligente…
Sharpen Nitidezza
@@ -681,6 +686,7 @@
Divide Vertically Into Dividi verticalmente in
Do Not Move Non spostare
Do you want to save the changes you made to “{name}”? Vuoi salvare le modifiche apportate a “{name}”?
Can't open “{name}”. Impossibile aprire «{name}».
Document Documento
Document Color Mode Metodo colore documento
Document Info Informazioni documento
@@ -1492,6 +1498,8 @@
Monospaced Monospaziato
More Altro
More Pathfinder options Altre opzioni di Elaborazione tracciati
More Align options Altre opzioni di allineamento
More Paragraph options Altre opzioni di paragrafo
More Settings Altre impostazioni
Move Sposta
Move All Objects Sposta tutti gli oggetti
@@ -2062,6 +2070,25 @@
Reflect… Rifletti…
Refresh Aggiorna
Refresh Font List Aggiorna elenco font
Missing Fonts Font mancanti
Missing Fonts Dialog Finestra di dialogo Font mancanti
These fonts aren't available. Their text shows in another font. Questi font non sono disponibili. Il loro testo viene mostrato con un altro font.
Search Fonts Folder Cerca nella cartella Fonts
Find in Folder… Trova in una cartella…
Find Fonts in Folder… Trova font in una cartella…
Find Font Files Trova file dei font
Add Font Files Aggiungi file dei font
Add Fonts Aggiungi font
Find Fonts Trova font
Stop Interrompi
Searching… Ricerca in corso…
Not found Non trovato
{folders} folder(s) and {files} file(s) searched Cartelle cercate: {folders}, file: {files}
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Cartelle saltate: {count}, ad esempio quelle di altre app e di sistema e quelle nascoste
{count} folder(s) or file(s) couldn't be read Cartelle o file non leggibili: {count}
The search stopped at its limit: search a smaller folder. La ricerca si è fermata al suo limite: cerca in una cartella più piccola.
Copy only fonts you own or are licensed to install. Copia solo font di tua proprietà o con una licenza che ti consente di installarli.
VectorCraft copies the fonts to {folder}. VectorCraft copia i font in {folder}.
Registered Trademark Symbol Simbolo di marchio registrato
Registration marks Segni di registro
Registry name: Nome registro:
@@ -2540,6 +2567,9 @@
Smart Guides (⌘U) Guide sensibili (⌘U)
Smart Punctuation… Punteggiatura intelligente…
Smooth Smussa
Corner Angolo
Relative Relativo
Absolute Assoluto
Smooth Color Colore graduale
Smooth Tool Strumento Smussa
Snap Curves To Lines Aggancia curve a linee
@@ -3325,6 +3355,7 @@ axis Both Entrambi
@msg cannot distort a zero-size bounding box impossibile distorcere un riquadro di delimitazione di dimensione zero
@msg cannot read PDF: {0} impossibile leggere il PDF: {0}
@msg cannot split an open path at its end point impossibile dividere un tracciato aperto nel suo punto finale
@msg closing needs three anchors per chiudere servono tre punti di ancoraggio
@msg check an asset to export spunta una risorsa da esportare
@msg choice must be "merge" or "add", not `{choice}` choice deve essere "merge" o "add", non `{choice}`
@msg choose a direction to divide in scegli una direzione in cui dividere
@@ -3714,6 +3745,24 @@ axis Both Entrambi
@msg an image whose data is cut short was left out un'immagine con dati incompleti è stata omessa
@msg its editing data doesn't say where its art is i suoi dati di modifica non dicono dove si trova la grafica
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) questo file è stato salvato senza compatibilità PDF e i suoi dati di modifica non si possono leggere ({why})
@msg No fonts are missing in this document In questo documento non mancano font
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft non cerca nelle cartelle di altre app né di sistema: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft non cerca nelle cartelle Shared e Public di Users: {path}
@msg {path} is not a folder {path} non è una cartella
@msg the search couldn't start: try again in a moment impossibile avviare la ricerca: riprova tra un momento
@msg searching a folder isn't available on the web la ricerca in una cartella non è disponibile sul web
@msg every search thread stopped on an internal error (please report this bug) tutti i thread di ricerca si sono fermati per un errore interno (segnala questo bug)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it La cartella Fonts di VectorCraft non è impostata qui: la impostano l'app desktop e vectorcraft-cli
@msg choose the font files to add scegli i file dei font da aggiungere
@msg {n} font file(s) are now in {folder} File di font ora in {folder}: {n}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} File di font ora in {folder}: {n}; impossibile aggiungerne {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font font non disponibili qui: {n}; il loro testo viene mostrato con un altro font
@msg not a file non è un file
@msg not a font file non è un file di font
@msg that document is no longer open quel documento non è più aperto
@msg larger than 256 MB più grande di 256 MB
@msg the files come to more than 1 GB: add fewer at a time i file superano 1 GB: aggiungine meno alla volta
@msg every numbered name for it is taken in the Fonts folder tutti i nomi numerati per il file sono già usati nella cartella Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Servizi
@@ -3734,3 +3783,8 @@ axis Both Entrambi
Constrain Vincola
Free Transform Trasformazione libera
Perspective Distort Distorsione prospettica
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` è il riferimento al passaggio {r}, che solo `run` e `command_batch` risolvono
@msg `ids` must be an array of object ids, not {v} `ids` deve essere un elenco di ID oggetto, non {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: il risultato del passaggio {i} non ha questo valore (scrivi $$ per un $ letterale)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: non c’è un passaggio {i} prima di questo (i passaggi si contano da 0; scrivi $$ per un $ letterale)
@msg object ids are non-negative integers, not {v} gli ID oggetto sono interi non negativi, non {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+54
View File
@@ -4,6 +4,11 @@
# Clean-room: menu and feature names follow the names Japanese users of vector illustration
# software know, written from the meaning of VectorCraft's English labels; no other application's
# Japanese localisation was copied. Toggles read as their action (「…を表示」「…を隠す」).
Glowing Edges… エッジの光彩…
Glowing Edges エッジの光彩
Edge Width エッジの幅
Edge Brightness エッジの明るさ
Smoothness 滑らかさ
#
# Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`,
# tested) — and the status and error messages (`@msg` rows at the end, `COMPLETE_MESSAGES`, tested).
@@ -1117,6 +1122,7 @@
Divide Slices スライスを分割
Divide Vertically Into 垂直方向に分割
Do you want to save the changes you made to “{name}”? 「{name}」への変更を保存しますか?
Can't open “{name}”. 「{name}」を開けません。
Document ドキュメント
Document Ink Options ドキュメントのインキオプション
Document JSON ドキュメント JSON
@@ -1634,6 +1640,8 @@
Monochrome images モノクロイメージ
More 多く
More Pathfinder options その他のパスファインダーオプション
More Align options その他の整列オプション
More Paragraph options その他の段落オプション
More Settings その他の設定
Move 移動
Move Anchors アンカーポイントを移動
@@ -2064,6 +2072,25 @@
Reflect Y Y 軸でリフレクト
Refresh 更新
Refresh Font List フォントリストを更新
Missing Fonts 見つからないフォント
Missing Fonts Dialog 見つからないフォントダイアログ
These fonts aren't available. Their text shows in another font. これらのフォントは使用できません。テキストは別のフォントで表示されます。
Search Fonts Folder 「Fonts」フォルダーを検索
Find in Folder… フォルダー内を検索…
Find Fonts in Folder… フォルダー内のフォントを検索…
Find Font Files フォントファイルを検索
Add Font Files フォントファイルを追加
Add Fonts フォントを追加
Find Fonts フォントを検索
Stop 停止
Searching… 検索中…
Not found 見つかりません
{folders} folder(s) and {files} file(s) searched {folders} 個のフォルダーと {files} 個のファイルを検索しました
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} 個のフォルダーをスキップしました(他のアプリやシステムのフォルダー、隠しフォルダーなど)
{count} folder(s) or file(s) couldn't be read {count} 個のフォルダーまたはファイルを読み込めませんでした
The search stopped at its limit: search a smaller folder. 検索は上限で停止しました。より小さなフォルダーを検索してください。
Copy only fonts you own or are licensed to install. 所有しているフォント、またはインストールするライセンスがあるフォントだけをコピーしてください。
VectorCraft copies the fonts to {folder}. VectorCraft はフォントを {folder} にコピーします。
Registry name: レジストリ名:
Release Compound Shape 複合シェイプを解除
Release Opacity Mask 不透明マスクを解除
@@ -2355,6 +2382,9 @@
Smart Guides (View → Smart Guides) スマートガイド (表示 → スマートガイド)
Smart Guides (⌘U) スマートガイド (⌘U)
Smooth スムーズ
Corner コーナー
Relative 相対
Absolute 絶対
Smooth Tool スムーズツール
Snap Curves To Lines 曲線を直線にスナップ
View: 表示:
@@ -3249,6 +3279,7 @@ theme Appearance 外観
@msg no saved selections 保存した選択範囲はありません
@msg no such artboard 指定されたアートボードが見つかりません
@msg cannot split an open path at its end point オープンパスは端点で分割できません
@msg closing needs three anchors 閉じるには 3 つのアンカーポイントが必要です
@msg empty brush stroke ブラシストロークが空です
@msg no such anchor 指定されたアンカーポイントが見つかりません
@msg no such segment 指定されたセグメントが見つかりません
@@ -3726,3 +3757,26 @@ theme Appearance 外観
@msg no user workspace `{from}` ユーザーワークスペース `{from}` が見つかりません
@msg unknown workspace (one of {_1}) 不明なワークスペースです ({_1} のいずれかを指定してください)
@msg workspace name can't be empty ワークスペース名を入力してください
@msg No fonts are missing in this document このドキュメントには見つからないフォントはありません
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft は他のアプリやシステムのフォルダーを検索しません: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft は Users 内の Shared フォルダーと Public フォルダーを検索しません: {path}
@msg {path} is not a folder {path} はフォルダーではありません
@msg the search couldn't start: try again in a moment 検索を開始できませんでした: しばらくしてからもう一度お試しください
@msg searching a folder isn't available on the web Web 版ではフォルダーを検索できません
@msg every search thread stopped on an internal error (please report this bug) すべての検索スレッドが内部エラーで停止しました (このバグを報告してください)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it この環境では VectorCraft の Fonts フォルダーが設定されていません: デスクトップアプリと vectorcraft-cli が設定します
@msg choose the font files to add 追加するフォントファイルを選択してください
@msg {n} font file(s) are now in {folder} {n} 個のフォントファイルが {folder} に入りました
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} 個のフォントファイルが {folder} に入りましたが、{failed} 個は追加できませんでした: {reason}
@msg {n} font(s) aren't available here: their text shows in another font {n} 個のフォントはこの環境では使用できません: テキストは別のフォントで表示されます
@msg not a file ファイルではありません
@msg not a font file フォントファイルではありません
@msg that document is no longer open そのドキュメントはもう開かれていません
@msg larger than 256 MB 256 MB を超えています
@msg the files come to more than 1 GB: add fewer at a time ファイルの合計が 1 GB を超えています: 一度に追加するファイルを減らしてください
@msg every numbered name for it is taken in the Fonts folder Fonts フォルダーでは、このファイルの番号付きの名前がすべて使われています
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` はステップ参照 {r} です。ステップ参照を解決できるのは `run` と `command_batch` だけです
@msg `ids` must be an array of object ids, not {v} `ids` はオブジェクト ID の配列にしてください ({v} は使えません)
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: ステップ {i} の結果にその値はありません ($ そのものを書くには $$ と入力してください)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: この前にステップ {i} はありません (ステップは 0 から数えます。$ そのものを書くには $$ と入力してください)
@msg object ids are non-negative integers, not {v} オブジェクト ID は 0 以上の整数です ({v} は使えません)
Can't render this file because it contains an unexpected character in line 2 and column 73.
+23
View File
@@ -14,6 +14,7 @@
# Brazilian Portuguese computing vocabulary (arquivo, camada, caminho, preenchimento, traçado,
# pincel, amostra, mesa de trabalho ...), following common desktop-software conventions (commands
# in the infinitive, menus as nouns); no proprietary localisation resource, string table or product
Glowing Edges… Bordas brilhantes…
# UI was consulted or copied; add entries the same way. Product and technology names (VectorCraft,
# ArtCraft, SVG, OpenType, CMYK, Lab ...) stay in Latin letters; the trailing "…" of dialog
# commands is kept.
@@ -635,6 +636,7 @@
Divide Slices… Dividir Fatias…
Divide Vertically Into Dividir Verticalmente Em
Do you want to save the changes you made to “{name}”? Deseja salvar as alterações feitas em “{name}”?
Can't open “{name}”. Não é possível abrir “{name}”.
Document Documento
Document Color Mode Modo de Cor do Documento
Document Info Informações do Documento
@@ -1312,6 +1314,8 @@
Monochrome images Imagens monocromáticas
More Mais
More Pathfinder options Mais opções de Localizador de Caminhos
More Align options Mais opções de alinhamento
More Paragraph options Mais opções de parágrafo
More Settings Mais Configurações
Move Mover
Move Anchors Mover Âncoras
@@ -1819,6 +1823,25 @@
Reflect… Espelhar…
Refresh Atualizar
Refresh Font List Atualizar Lista de Fontes
Missing Fonts Fontes Ausentes
Missing Fonts Dialog Diálogo de Fontes Ausentes
These fonts aren't available. Their text shows in another font. Estas fontes não estão disponíveis. O texto delas aparece em outra fonte.
Search Fonts Folder Pesquisar na Pasta Fonts
Find in Folder… Localizar em uma Pasta…
Find Fonts in Folder… Localizar Fontes em uma Pasta…
Find Font Files Localizar Arquivos de Fontes
Add Font Files Adicionar Arquivos de Fontes
Add Fonts Adicionar Fontes
Find Fonts Localizar Fontes
Stop Parar
Searching… Pesquisando…
Not found Não encontrado
{folders} folder(s) and {files} file(s) searched {folders} pasta(s) e {files} arquivo(s) pesquisados
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} pasta(s) ignorada(s), como as de outros aplicativos e do sistema e as ocultas
{count} folder(s) or file(s) couldn't be read {count} pasta(s) ou arquivo(s) não puderam ser lidos
The search stopped at its limit: search a smaller folder. A pesquisa parou no limite: pesquise uma pasta menor.
Copy only fonts you own or are licensed to install. Copie apenas fontes que sejam suas ou que você tenha licença para instalar.
VectorCraft copies the fonts to {folder}. O VectorCraft copia as fontes para {folder}.
Registered Trademark Symbol Símbolo de Marca Registrada
Registry name: Nome do registro:
Release Liberar
Can't render this file because it contains an unexpected character in line 6 and column 47.
+54
View File
@@ -10,6 +10,11 @@
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
# Photoshop-style raster effects (Effect menu, their dialogs).
Glowing Edges… Светящиеся края…
Glowing Edges Светящиеся края
Edge Width Ширина края
Edge Brightness Яркость края
Smoothness Сглаживание
Radial Blur… Радиальное размытие…
Smart Blur… Умное размытие…
Sharpen Резкость
@@ -679,6 +684,7 @@
Divide Vertically Into Разделить по вертикали на
Do Not Move Не перемещать
Do you want to save the changes you made to “{name}”? Сохранить изменения, внесённые в «{name}»?
Can't open “{name}”. Не удаётся открыть «{name}».
Document Документ
Document Color Mode Цветовой режим документа
Document Info Сведения о документе
@@ -1490,6 +1496,8 @@
Monospaced Моноширинный
More Больше
More Pathfinder options Дополнительные параметры обработки контуров
More Align options Дополнительные параметры выравнивания
More Paragraph options Дополнительные параметры абзаца
More Settings Дополнительные настройки
Move Переместить
Move All Objects Переместить все объекты
@@ -2058,6 +2066,25 @@
Reflect… Отразить…
Refresh Обновить
Refresh Font List Обновить список шрифтов
Missing Fonts Отсутствующие шрифты
Missing Fonts Dialog Диалоговое окно «Отсутствующие шрифты»
These fonts aren't available. Their text shows in another font. Эти шрифты недоступны. Их текст отображается другим шрифтом.
Search Fonts Folder Искать в папке Fonts
Find in Folder… Найти в папке…
Find Fonts in Folder… Найти шрифты в папке…
Find Font Files Найти файлы шрифтов
Add Font Files Добавить файлы шрифтов
Add Fonts Добавить шрифты
Find Fonts Найти шрифты
Stop Остановить
Searching… Поиск…
Not found Не найдено
{folders} folder(s) and {files} file(s) searched Просмотрено папок: {folders}, файлов: {files}
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, например папки других приложений и системы и скрытые папки
{count} folder(s) or file(s) couldn't be read Не удалось прочитать папок или файлов: {count}
The search stopped at its limit: search a smaller folder. Поиск остановился на пределе: выберите папку поменьше.
Copy only fonts you own or are licensed to install. Копируйте только шрифты, которые принадлежат вам или которые вы вправе устанавливать по лицензии.
VectorCraft copies the fonts to {folder}. VectorCraft копирует шрифты в {folder}.
Registered Trademark Symbol Символ зарегистрированного товарного знака
Registration marks Метки совмещения
Registry name: Имя в реестре:
@@ -2536,6 +2563,9 @@
Smart Guides (⌘U) Умные направляющие (⌘U)
Smart Punctuation… Умная пунктуация…
Smooth Сгладить
Corner Угол
Relative Относительно
Absolute Абсолютно
Smooth Color Сглаженный цвет
Smooth Tool Инструмент «Сглаживание»
Snap Curves To Lines Привязывать кривые к линиям
@@ -3321,6 +3351,7 @@ axis Both Оба
@msg cannot distort a zero-size bounding box нельзя исказить ограничительную рамку нулевого размера
@msg cannot read PDF: {0} не удалось прочитать PDF: {0}
@msg cannot split an open path at its end point нельзя разделить открытый контур в его конечной точке
@msg closing needs three anchors для замыкания нужны три опорные точки
@msg check an asset to export отметьте ресурс для экспорта
@msg choice must be "merge" or "add", not `{choice}` choice должно быть "merge" или "add", а не `{choice}`
@msg choose a direction to divide in выберите направление для разделения
@@ -3710,6 +3741,24 @@ axis Both Оба
@msg an image whose data is cut short was left out изображение с обрезанными данными пропущено
@msg its editing data doesn't say where its art is в его данных редактирования не указано, где находится графика
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) этот файл сохранён без совместимости с PDF, и его данные редактирования не удаётся прочитать ({why})
@msg No fonts are missing in this document В этом документе нет отсутствующих шрифтов
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft не ищет в папках других приложений и системы: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft не ищет в папках Shared и Public внутри Users: {path}
@msg {path} is not a folder {path} не является папкой
@msg the search couldn't start: try again in a moment не удалось начать поиск: повторите попытку чуть позже
@msg searching a folder isn't available on the web поиск в папке недоступен в веб-версии
@msg every search thread stopped on an internal error (please report this bug) все потоки поиска остановились из-за внутренней ошибки (сообщите об этой ошибке)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папка Fonts VectorCraft здесь не задана: её задают настольное приложение и vectorcraft-cli
@msg choose the font files to add выберите файлы шрифтов для добавления
@msg {n} font file(s) are now in {folder} Файлов шрифтов теперь в {folder}: {n}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Файлов шрифтов теперь в {folder}: {n}; не удалось добавить {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font здесь недоступно шрифтов: {n}; их текст отображается другим шрифтом
@msg not a file не файл
@msg not a font file не файл шрифта
@msg that document is no longer open этот документ больше не открыт
@msg larger than 256 MB больше 256 МБ
@msg the files come to more than 1 GB: add fewer at a time файлы занимают больше 1 ГБ: добавляйте меньше за раз
@msg every numbered name for it is taken in the Fonts folder все нумерованные имена для него уже заняты в папке Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Службы
@@ -3732,3 +3781,8 @@ axis Both Оба
Perspective Distort Искажение перспективы
Artboard Монтажная область
Exit Выйти
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` — это ссылка на шаг {r}, которую разрешают только `run` и `command_batch`
@msg `ids` must be an array of object ids, not {v} `ids` должен быть массивом идентификаторов объектов, а не {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: в результате шага {i} нет такого значения (чтобы написать сам $, введите $$)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: перед этим шагом нет шага {i} (шаги считаются с 0; чтобы написать сам $, введите $$)
@msg object ids are non-negative integers, not {v} идентификаторы объектов — неотрицательные целые числа, а не {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+54
View File
@@ -10,6 +10,11 @@
# Coverage: every menu string, tl! literal, plural, status and error message (enforced in tests).
# Product, language, built-in workspace and perspective preset names follow MENU_KEEP_AS_IS.
# Keep placeholders, ellipses and leading/trailing spaces of fragments when editing.
Glowing Edges… Сяйливі краї…
Glowing Edges Сяйливі краї
Edge Width Ширина краю
Edge Brightness Яскравість краю
Smoothness Згладжування
Radial Blur… Радіальне розмиття…
Smart Blur… Розумне розмиття…
@@ -675,6 +680,7 @@
Divide Vertically Into Розділити по вертикалі на
Do Not Move Не переміщати
Do you want to save the changes you made to “{name}”? Зберегти зміни, внесені до «{name}»?
Can't open “{name}”. Не вдається відкрити «{name}».
Document Документ
Document Color Mode Колірний режим документа
Document Info Відомості про документ
@@ -1486,6 +1492,8 @@
Monospaced Моноширинний
More Більше
More Pathfinder options Додаткові параметри обробки контурів
More Align options Додаткові параметри вирівнювання
More Paragraph options Додаткові параметри абзацу
More Settings Додаткові налаштування
Move Перемістити
Move All Objects Перемістити всі об’єкти
@@ -2054,6 +2062,25 @@
Reflect… Відобразити…
Refresh Оновити
Refresh Font List Оновити список шрифтів
Missing Fonts Відсутні шрифти
Missing Fonts Dialog Діалогове вікно «Відсутні шрифти»
These fonts aren't available. Their text shows in another font. Ці шрифти недоступні. Їхній текст показано іншим шрифтом.
Search Fonts Folder Шукати в папці Fonts
Find in Folder… Знайти в папці…
Find Fonts in Folder… Знайти шрифти в папці…
Find Font Files Знайти файли шрифтів
Add Font Files Додати файли шрифтів
Add Fonts Додати шрифти
Find Fonts Знайти шрифти
Stop Зупинити
Searching… Пошук…
Not found Не знайдено
{folders} folder(s) and {files} file(s) searched Переглянуто папок: {folders}, файлів: {files}
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, зокрема папки інших програм і системи та приховані папки
{count} folder(s) or file(s) couldn't be read Не вдалося прочитати папок або файлів: {count}
The search stopped at its limit: search a smaller folder. Пошук зупинився на межі: виберіть меншу папку.
Copy only fonts you own or are licensed to install. Копіюйте лише шрифти, які належать вам або які ви маєте право встановлювати за ліцензією.
VectorCraft copies the fonts to {folder}. VectorCraft копіює шрифти в {folder}.
Registered Trademark Symbol Символ зареєстрованого товарного знаку
Registration marks Мітки поєднання
Registry name: Ім’я у реєстрі:
@@ -2532,6 +2559,9 @@
Smart Guides (⌘U) Розумні напрямні (⌘U)
Smart Punctuation… Розумна пунктуація…
Smooth Згладити
Corner Кут
Relative Відносно
Absolute Абсолютно
Smooth Color Згладжений колір
Smooth Tool Інструмент «Згладжування»
Snap Curves To Lines Прив’язувати криві до ліній
@@ -3308,6 +3338,7 @@ axis Both Обидві
@msg cannot distort a zero-size bounding box не можна спотворити обмежувальну рамку нульового розміру
@msg cannot read PDF: {0} не вдалося прочитати PDF: {0}
@msg cannot split an open path at its end point не можна розділити відкритий контур у його кінцевій точці
@msg closing needs three anchors для замикання потрібні три опорні точки
@msg check an asset to export позначте ресурс для експорту
@msg choice must be "merge" or "add", not `{choice}` choice має бути "merge" або "add", а не `{choice}`
@msg choose a direction to divide in виберіть напрямок для поділу
@@ -3697,6 +3728,24 @@ axis Both Обидві
@msg an image whose data is cut short was left out зображення з обрізаними даними пропущено
@msg its editing data doesn't say where its art is у даних редагування не зазначено, де знаходиться графіка
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) цей файл збережений без сумісності з PDF, і його дані редагування не вдається прочитати ({why})
@msg No fonts are missing in this document У цьому документі немає відсутніх шрифтів
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft не шукає в папках інших програм і системи: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft не шукає в папках Shared і Public у Users: {path}
@msg {path} is not a folder {path} не є папкою
@msg the search couldn't start: try again in a moment не вдалося почати пошук: спробуйте ще раз за мить
@msg searching a folder isn't available on the web пошук у папці недоступний у веб-версії
@msg every search thread stopped on an internal error (please report this bug) усі потоки пошуку зупинилися через внутрішню помилку (повідомте про цю помилку)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папку Fonts VectorCraft тут не задано: її задають настільна програма та vectorcraft-cli
@msg choose the font files to add виберіть файли шрифтів для додавання
@msg {n} font file(s) are now in {folder} Файлів шрифтів тепер у {folder}: {n}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Файлів шрифтів тепер у {folder}: {n}; не вдалося додати {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font тут недоступно шрифтів: {n}; їхній текст показано іншим шрифтом
@msg not a file не файл
@msg not a font file не файл шрифту
@msg that document is no longer open цей документ більше не відкрито
@msg larger than 256 MB більше 256 МБ
@msg the files come to more than 1 GB: add fewer at a time файли займають понад 1 ГБ: додавайте менше за раз
@msg every numbered name for it is taken in the Fonts folder усі нумеровані імена для нього вже зайняті в папці Fonts
Services Служби
Hide VectorCraft Приховати VectorCraft
Zoom Масштаб
@@ -3717,3 +3766,8 @@ axis Both Обидві
Perspective Distort Спотворення перспективи
Artboard Монтажна область
Exit Вийти
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` — це посилання на крок {r}, яке розв’язують лише `run` і `command_batch`
@msg `ids` must be an array of object ids, not {v} `ids` має бути масивом ідентифікаторів об’єктів, а не {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: у результаті кроку {i} немає такого значення (щоб написати сам $, введіть $$)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: перед цим кроком немає кроку {i} (кроки рахуються з 0; щоб написати сам $, введіть $$)
@msg object ids are non-negative integers, not {v} ідентифікатори об’єктів — невід’ємні цілі числа, а не {v}
Can't render this file because it contains an unexpected character in line 632 and column 40.
+30
View File
@@ -9,6 +9,11 @@
# proprietary localisation resource, string table or product UI may be copied. Product and
# technology names stay in Latin letters. Full-width punctuation (,。:“”) in sentences, half-width
# parentheses.
Glowing Edges… 发光边缘…
Glowing Edges 发光边缘
Edge Width 边缘宽度
Edge Brightness 边缘亮度
Smoothness 平滑度
— missing — 缺失
to search every command 以搜索所有命令
@@ -661,6 +666,7 @@
Divide Vertically Into 垂直分割为
Do Not Move 不移动
Do you want to save the changes you made to “{name}”? 要存储对“{name}”所做的更改吗?
Can't open “{name}”. 无法打开“{name}”。
Document 文档
Document Color Mode 文档颜色模式
Document Info 文档信息
@@ -1450,6 +1456,8 @@
Monochrome images 单色图像
More 较多
More Pathfinder options 更多路径查找器选项
More Align options 更多对齐选项
More Paragraph options 更多段落选项
More Settings 更多设置
Move 移动
Move All Objects 移动所有对象
@@ -2016,6 +2024,25 @@
Reflect… 镜像…
Refresh 刷新
Refresh Font List 刷新字体列表
Missing Fonts 缺失的字体
Missing Fonts Dialog 缺失的字体对话框
These fonts aren't available. Their text shows in another font. 这些字体不可用。其文字以其他字体显示。
Search Fonts Folder 搜索 Fonts 文件夹
Find in Folder… 在文件夹中查找…
Find Fonts in Folder… 在文件夹中查找字体…
Find Font Files 查找字体文件
Add Font Files 添加字体文件
Add Fonts 添加字体
Find Fonts 查找字体
Stop 停止
Searching… 正在搜索…
Not found 未找到
{folders} folder(s) and {files} file(s) searched 已搜索 {folders} 个文件夹、{files} 个文件
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已跳过 {count} 个文件夹,例如其他应用程序和系统的文件夹,以及隐藏的文件夹
{count} folder(s) or file(s) couldn't be read 有 {count} 个文件夹或文件无法读取
The search stopped at its limit: search a smaller folder. 搜索已达上限而停止:请搜索较小的文件夹。
Copy only fonts you own or are licensed to install. 只复制您拥有或已获得安装许可的字体。
VectorCraft copies the fonts to {folder}. VectorCraft 会将字体复制到 {folder}。
Registered Trademark Symbol 注册商标符号
Registration marks 对位标记
Registry name: 登录名称:
@@ -2457,6 +2484,9 @@
Smart Guides (⌘U) 智能参考线 (⌘U)
Smart Punctuation… 智能标点…
Smooth 平滑
Corner 尖角
Relative 相对
Absolute 绝对
Smooth Color 平滑颜色
Smooth Tool 平滑工具
Snap Curves To Lines 将曲线对齐到直线
Can't render this file because it contains an unexpected character in line 2 and column 73.
+30
View File
@@ -17,6 +17,11 @@
# commands is kept. Full-width punctuation (,。:) inside sentences; half-width parentheses and
# the " · " separators as in the English. Terms shared with PhotoCraft use the same words as its
# zh-hant catalog (圖層, 選取, 偏好設定, 混合模式 ...), so the two apps read alike.
Glowing Edges… 發光邊緣…
Glowing Edges 發光邊緣
Edge Width 邊緣寬度
Edge Brightness 邊緣亮度
Smoothness 平滑度
— missing — 遺失
to search every command 以搜尋所有指令
@@ -679,6 +684,7 @@
Divide Vertically Into 垂直分割為
Do Not Move 不移動
Do you want to save the changes you made to “{name}”? 要儲存對「{name}」所做的變更嗎?
Can't open “{name}”. 無法開啟「{name}」。
Document 文件
Document Color Mode 文件色彩模式
Document Info 文件資訊
@@ -1492,6 +1498,8 @@
Monospaced 等寬
More 更多
More Pathfinder options 更多路徑管理員選項
More Align options 更多對齊選項
More Paragraph options 更多段落選項
More Settings 更多設定
Move 移動
Move All Objects 移動所有物件
@@ -2065,6 +2073,25 @@
Reflect… 鏡射…
Refresh 重新整理
Refresh Font List 重新整理字體清單
Missing Fonts 遺失的字體
Missing Fonts Dialog 遺失的字體對話框
These fonts aren't available. Their text shows in another font. 這些字體無法使用。其文字以其他字體顯示。
Search Fonts Folder 搜尋 Fonts 資料夾
Find in Folder… 在資料夾中尋找…
Find Fonts in Folder… 在資料夾中尋找字體…
Find Font Files 尋找字體檔案
Add Font Files 新增字體檔案
Add Fonts 新增字體
Find Fonts 尋找字體
Stop 停止
Searching… 搜尋中…
Not found 找不到
{folders} folder(s) and {files} file(s) searched 已搜尋 {folders} 個資料夾、{files} 個檔案
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已略過 {count} 個資料夾,例如其他應用程式和系統的資料夾,以及隱藏的資料夾
{count} folder(s) or file(s) couldn't be read 有 {count} 個資料夾或檔案無法讀取
The search stopped at its limit: search a smaller folder. 搜尋已達上限而停止:請搜尋較小的資料夾。
Copy only fonts you own or are licensed to install. 只複製您擁有或已取得安裝授權的字體。
VectorCraft copies the fonts to {folder}. VectorCraft 會將字體複製到 {folder}。
Registered Trademark Symbol 註冊商標符號
Registration marks 對位標記
Registry name: 登錄名稱:
@@ -2543,6 +2570,9 @@
Smart Guides (⌘U) 智慧型參考線 (⌘U)
Smart Punctuation… 智慧型標點…
Smooth 平滑
Corner 角點
Relative 相對
Absolute 絕對
Smooth Color 平滑顏色
Smooth Tool 平滑工具
Snap Curves To Lines 將曲線靠齊線條
Can't render this file because it contains an unexpected character in line 6 and column 47.
+36 -1
View File
@@ -97,7 +97,24 @@ pub fn open_dialog(app: &mut VectorcraftApp) -> Result<(), String> {
return Ok(());
}
let path = pick_open(app, &FilePick { filters: fileio::open_filters().collect(), ..Default::default() })?;
open_path(app, &path).map(|_| ())
open_reporting(app, &path).map(|_| ())
}
/// A file the user asked to open (File › Open, Open Recent, the Home screen, a drop, the Finder)
/// couldn't be: say so in a dialog as well as the status bar, which is easily missed (#861).
pub fn report_open_error(app: &mut VectorcraftApp, name: &str, e: &str) {
app.status(format!("Couldn't open {name}: {e}"));
let message = crate::i18n::fmt(tl!("Can't open “{name}”."), &[("name", name)]);
dialogs::confirm::tell(app, &message, &crate::i18n::message(crate::i18n::current(), e));
}
/// [`open_path`] for a file the user asked for, a failure reported ([`report_open_error`]).
pub fn open_reporting(app: &mut VectorcraftApp, path: &str) -> Result<Value, String> {
let r = open_path(app, path);
if let Err(e) = &r {
report_open_error(app, &fileio::file_name(path), e);
}
r
}
fn read(app: &VectorcraftApp, path: &str) -> Result<Vec<u8>, String> {
@@ -699,6 +716,24 @@ mod tests {
(VectorcraftApp::new(Session::new(), services), written)
}
/// #861: a file the user opens that can't be opened is reported in a dialog they close, not
/// only in the status bar; a file an agent opens by path only answers with the error.
#[test]
fn a_file_the_user_cant_open_is_reported_in_a_dialog() {
let (mut app, _) = app();
app.services.read = Some(Box::new(|_: &str| Err("no such file".into())));
assert!(open_reporting(&mut app, "/docs/gone.ai").is_err());
let d = app.ui.dialog.take().expect("a dialog says so");
assert_eq!(
(d.kind.as_str(), d.str("message"), d.str("detail")),
(dialogs::confirm::MESSAGE, "Can't open “gone.ai”.".to_string(), "no such file".to_string())
);
assert!(app.ui.status.contains("gone.ai"));
// An agent's `file.open {path}` gets the error back and no dialog.
assert!(app.run("file.open", json!({"path": "/docs/gone.ai"})).is_err());
assert!(app.ui.dialog.is_none());
}
fn bytes_of(app: &mut VectorcraftApp, cmd: &str, p: Value) -> Vec<u8> {
let v = app.session.execute(cmd, &p).unwrap();
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()
+16 -5
View File
@@ -293,6 +293,8 @@ pub struct CacheKey {
pub pixel: Option<[i64; 4]>,
/// Images sampled smoothly ([`vectorcraft_render::RenderOptions::smooth_images`]).
pub smooth_images: bool,
/// Isolation mode's group or layer ([`vectorcraft_render::RenderOptions::isolated`]).
pub isolated: Option<u64>,
}
#[derive(Clone, Copy, Debug, Default)]
@@ -704,7 +706,7 @@ impl VectorcraftApp {
self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();
for (name, bytes) in arrived {
if let Err(e) = io::open_bytes(self, &name, &bytes, None) {
self.status(format!("Couldn't open {name}: {e}"));
io::report_open_error(self, &name, &e);
}
}
place::drain(self);
@@ -886,11 +888,20 @@ impl VectorcraftApp {
for f in dropped {
let path = Some(f.path().to_string_lossy().to_string()).filter(|s| !s.is_empty());
let name = path.as_deref().map_or_else(|| "dropped".into(), vectorcraft_engine::cmd::fileio::file_name);
let target = self.drop_target(&name, pos, shift);
// A file placed by its path is read by the engine.
let bytes = if path.is_some() && target != place::DropTarget::Open { Ok(vec![]) } else { f.bytes() };
// Native file drops usually carry a path. Use the same file reader as File → Open
// (and File → Place), even if the drop handle can't supply the bytes itself.
let bytes = if path.is_some() && self.services.read.is_some() { Ok(vec![]) } else { f.bytes() };
match bytes {
Ok(b) => files.push((target, (name, path, b))),
Ok(bytes) => {
// A backend may give bytes without a path or extension. Sniff their format
// before deciding: an SVG opens as a document, a raster image is placed.
let target = if path.is_none() && fileio::detect(&name, &bytes).is_none_or(|f| !f.raster) {
place::DropTarget::Open
} else {
self.drop_target(&name, pos, shift)
};
files.push((target, (name, path, bytes)));
}
Err(e) => self.status(format!("Couldn't read {name}: {e}")),
}
}
+18 -2
View File
@@ -137,6 +137,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
("type.recentFont15", "Recent Font 15", "", "{} apply the 15. most recently used font"),
("file.clearRecent", "Clear Recent Files", "", "{}"),
("type.findFont", "Find Font…", "", "{} open the Find Font dialog (engine: text.fonts / text.replaceFont / select.font)"),
(
"ui.missingFontsDialog",
"Missing Fonts Dialog",
"",
"{folder?} open Missing Fonts (dialog `missingFonts`) for the fonts the active document uses that aren't available (text.missingFonts); with folder, it looks for their files there at once (text.findFontFiles). An error when no font is missing. Opening a document whose fonts are missing shows it after the missing linked file questions (dialog `missingLinks`). Disabled on the web",
),
(
"ui.findFontsInFolder",
"Find Fonts in Folder…",
"",
"{folder?} Type › Find Font's Find in Folder…: asks for a folder (or takes folder), then opens Missing Fonts looking there for the files of the fonts the active document misses (text.findFontFiles). Disabled where there is no folder picker (the web)",
),
("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first"),
(
"file.export.svg",
@@ -365,7 +377,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.swatchLibrary.other",
"Other Library…",
"",
"{path?} (default: pick a file) load a .vcswatches, .gpl or .ase library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
"{path?} (default: pick a file) load a .vcswatches, .gpl, .ase or .acb (color book) library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
),
(
"ui.saveSwatchLibrary",
@@ -872,13 +884,15 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
"file.revert" if p.get("confirmed").and_then(Value::as_bool) != Some(true) => io::ask_revert(app),
"file.reveal" => io::reveal(app),
id if id.starts_with("file.openRecent") => match recent_slot(app, id).cloned() {
Some(path) => io::open_path(app, &path),
Some(path) => io::open_reporting(app, &path),
None => Err("no such recent file".into()),
},
"type.findFont" => {
crate::find_font::open(app);
Ok(Value::Null)
}
"ui.missingFontsDialog" => crate::dialogs::missing_fonts::open_command(app, s("folder")),
"ui.findFontsInFolder" => crate::dialogs::missing_fonts::find_in_folder_command(app, s("folder")),
"file.clearRecent" => {
app.ui.recent_files.clear();
Ok(Value::Null)
@@ -1853,6 +1867,8 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
"ui.cropImage" => selected_image(app, |_| true),
"effect.applyLast" | "effect.last" => app.last_effect.is_some() && app.session.active().is_some_and(|d| !d.selection.is_empty()),
"file.export.pdf" | "ui.savePdfDialog" | "ui.fileInfoDialog" | "ui.rasterEffectsSettingsDialog" => app.session.active().is_some(),
"ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(),
"ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(),
"ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(),
"ui.graphicStyleOptions" => app.session.active().is_some(),
"ui.colorBalanceDialog" | "ui.saturateDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
+51
View File
@@ -52,6 +52,26 @@ pub const DISTRIBUTE: [(&str, &str, &str, &str); 6] = [
("dc-dist-right", "Horizontal Distribute Right", "horizontal", "right"),
];
/// The six align buttons of the Control bar and the Properties panel, `size` points square.
/// They align to what the Align panel's Align To says (the key object while there is one), as
/// its own buttons do (#789).
pub fn align_buttons(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) {
let n = selection_len(app);
let to = align_to(app, ui.ctx());
for (icon, tip, axis, v) in [
("align-start-vertical", "Horizontal Align Left", "horizontal", "left"),
("align-center-vertical", "Horizontal Align Center", "horizontal", "center"),
("align-end-vertical", "Horizontal Align Right", "horizontal", "right"),
("align-start-horizontal", "Vertical Align Top", "vertical", "top"),
("align-center-horizontal", "Vertical Align Center", "vertical", "center"),
("align-end-horizontal", "Vertical Align Bottom", "vertical", "bottom"),
] {
if widgets::icon_button(ui, icon, tl!(tip), false, size).clicked() {
app.run("object.align", align_params(json!({axis: v}), to, n)).ok();
}
}
}
/// Whether the selection has a key object.
fn has_key(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.selection.key.is_some())
@@ -183,4 +203,35 @@ mod tests {
app.run("select.key", json!({})).unwrap();
assert_eq!(align_to(&app, &ctx), AlignTo::Selection, "no key: the choice again");
}
/// #789: the Control bar's and the Properties panel's align buttons follow Align To too.
#[test]
fn the_other_align_buttons_align_to_the_align_to_choice() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone();
let b = app.run("shape.rectangle", json!({"x": 80, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let ctx = egui::Context::default();
set_pstate(&ctx, "align-to", AlignTo::Artboard);
// One frame finds the first button (Horizontal Align Right is third); the next clicks it.
let at = std::cell::Cell::new(egui::Pos2::ZERO);
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| {
ui.horizontal(|ui| {
at.set(ui.cursor().min);
align_buttons(app, ui, 24.0);
});
});
out.textures_delta.clear();
};
frame(&mut app, vec![]);
let right = at.get() + egui::vec2(2.0 * (24.0 + ctx.global_style().spacing.item_spacing.x) + 12.0, 12.0);
let press = |pressed| egui::Event::PointerButton { pos: right, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, vec![egui::Event::PointerMoved(right), press(true)]);
frame(&mut app, vec![press(false)]);
let st = app.session.active().unwrap();
let x1 = |id: &serde_json::Value| st.doc.bounds_of(&[vectorcraft_doc::NodeId(id.as_u64().unwrap())], false).unwrap().x1;
assert_eq!((x1(&a), x1(&b)), (200.0, 200.0), "both to the artboard's right edge");
}
}
+38 -2
View File
@@ -496,7 +496,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
(Some(c), _) => components(mode, &c),
(None, _) => vec![0.0; mode.labels().len()],
};
super::recent_colors_row(app, ui);
let recent = super::recent_colors_row(app, ui);
widgets::divider(ui);
// An edit of the active colour with its displayed components (`new`), or a colour clicked with
// Alt held for the inactive proxy (`behind`).
@@ -585,6 +585,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
*new = Some((c, phase, components(mode, &c)));
}
};
// A recent colour, like the chips, recolours the selected gradient stop (or point).
if let Some(c) = recent {
pick(c, Live::Released, &mut new);
}
// None / Black / White chips and the hex field.
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
@@ -691,12 +695,23 @@ mod tests {
/// Run the panel for one frame with `events` and `modifiers`; returns the spectrum's rect (when
/// the options are shown) and the panel's height.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, modifiers: egui::Modifiers) -> (Option<Rect>, f32) {
frame_with(app, ctx, events, modifiers, "color-spectrum")
}
/// [`frame`] returning the rect of the panel's widget `id` instead of the spectrum's.
fn frame_with(
app: &mut VectorcraftApp,
ctx: &egui::Context,
events: Vec<egui::Event>,
modifiers: egui::Modifiers,
id: impl std::hash::Hash + std::fmt::Debug,
) -> (Option<Rect>, f32) {
let mut out = (None, 0.0);
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let input = egui::RawInput { events, ..Default::default() };
let mut full = ctx.run_ui(input, |ui| {
show(app, ui);
out = (ctx.read_response(ui.id().with("color-spectrum")).map(|r| r.rect), ui.min_rect().height());
out = (ctx.read_response(ui.id().with(&id)).map(|r| r.rect), ui.min_rect().height());
});
full.textures_delta.clear();
out
@@ -712,6 +727,27 @@ mod tests {
frame(app, ctx, vec![], egui::Modifiers::NONE);
}
#[test]
fn a_recent_colour_recolours_the_selected_gradient_stop() {
// #835: it replaced the whole gradient with the colour.
let mut app = app();
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]);
app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap();
app.select_tool("gradient");
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let red = app.session.recent_colors.iter().position(|c| c.to_hex() == "#ff0000").expect("red is a recent colour");
let ctx = egui::Context::default();
let none = egui::Modifiers::NONE;
let chip = frame_with(&mut app, &ctx, vec![], none, ("recent", red)).0.expect("the chip is drawn").center();
let button = |pressed| egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Primary, pressed, modifiers: none };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(chip), button(true)], none);
frame(&mut app, &ctx, vec![button(false)], none);
let Paint::Gradient(g) = crate::panels::current_paints(&app).0 else { panic!("still a gradient") };
let hex: Vec<String> = g.gradient.stops.iter().map(|s| s.color.to_hex()).collect();
assert_eq!(hex, ["#ffffff", "#ff0000"]);
}
fn paints_hex(app: &VectorcraftApp) -> (String, String) {
let (f, s) = crate::panels::current_paints(app);
(f.color().map(|c| c.to_hex()).unwrap_or_default(), s.color().map(|c| c.to_hex()).unwrap_or_default())
+4 -1
View File
@@ -185,7 +185,10 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re
}
// A placed document's file opens here, in a new tab: saving it updates this document.
if !reveal && info["document"] == true {
app.run("document.open", json!({ "path": path }))?;
let opened = app.run("document.open", json!({ "path": path }))?;
// Its missing fonts are asked about as for a document opened with File › Open.
crate::dialogs::missing_fonts::after_open(app, &opened);
crate::dialogs::settle(app);
return Ok(json!({ "path": path }));
}
if reveal { crate::io::reveal_path(app, &path) } else { crate::io::open_in_app(app, &path) }?;
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more