Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
584f08ae70 | ||
|
|
db8be89052 | ||
|
|
1ba987ee7a | ||
|
|
3198abe2fd | ||
|
|
1c19c27fef | ||
|
|
b9b880a5de | ||
|
|
60831b87d9 | ||
|
|
800baacbba | ||
|
|
11aaf816d0 | ||
|
|
2d371849df | ||
|
|
d28cbacbf7 | ||
|
|
2762f61e83 | ||
|
|
94f27299d4 | ||
|
|
6fed61b4db | ||
|
|
09a0ff23ad | ||
|
|
1090385507 | ||
|
|
11cf254a07 | ||
|
|
7b7e10e82e | ||
|
|
5709e636a5 | ||
|
|
796accffc0 | ||
|
|
ef574b6319 | ||
|
|
ec32a0b537 | ||
|
|
8b95f79f3b | ||
|
|
b6625f6964 | ||
|
|
8edee45588 | ||
|
|
d38a2fa023 | ||
|
|
c2339fca81 | ||
|
|
1d0305fc2a | ||
|
|
f2ba41d1c1 | ||
|
|
b4784c02ee | ||
|
|
6f260fac3e | ||
|
|
7d75280ab4 | ||
|
|
c8642eeddb | ||
|
|
0b326c48bc | ||
|
|
f9384dfed7 | ||
|
|
71484fd013 | ||
|
|
7c3687af29 | ||
|
|
ba1b7a834f | ||
|
|
bbb465a0d3 | ||
|
|
f549f6ad4d | ||
|
|
a9e3d85b1d | ||
|
|
a4a040653d | ||
|
|
deff7bb757 | ||
|
|
022069d5a5 | ||
|
|
1f668dfaad | ||
|
|
816a0fe762 | ||
|
|
4fe06391d4 | ||
|
|
ae68704dfc | ||
|
|
eacef005b0 | ||
|
|
c461369421 |
No files matched your search
@@ -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)).
|
||||
|
||||
+9
-9
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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 |
|
||||
@@ -228,7 +228,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| 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) |
|
||||
| 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.
|
||||
|
||||
|
||||
@@ -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..]),
|
||||
|
||||
@@ -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;
|
||||
@@ -141,27 +142,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 +384,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");
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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, ©.name);
|
||||
link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.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");
|
||||
}
|
||||
}
|
||||
@@ -861,6 +861,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 +922,9 @@ impl Session {
|
||||
liquify_stroke: None,
|
||||
plane_widget_press: false,
|
||||
ruler_guide: None,
|
||||
font_search: None,
|
||||
search_rules: None,
|
||||
search_threads: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1459,6 +1471,8 @@ mod tests_flatten;
|
||||
#[cfg(test)]
|
||||
mod tests_focal;
|
||||
#[cfg(test)]
|
||||
mod tests_fontfiles;
|
||||
#[cfg(test)]
|
||||
mod tests_fontlist;
|
||||
#[cfg(test)]
|
||||
mod tests_freeform;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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)?;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
@@ -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(¶, 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()
|
||||
}
|
||||
|
||||
@@ -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 }));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
+5
-41
@@ -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);
|
||||
}
|
||||
|
||||
@@ -1760,6 +1760,8 @@ mod tests_fontchange;
|
||||
#[cfg(test)]
|
||||
mod tests_freeform;
|
||||
#[cfg(test)]
|
||||
mod tests_fxzoom;
|
||||
#[cfg(test)]
|
||||
mod tests_isolation;
|
||||
#[cfg(test)]
|
||||
mod tests_knockout;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
@@ -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}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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>) {
|
||||
|
||||
@@ -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;
|
||||
@@ -246,6 +247,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 +312,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"));
|
||||
|
||||
@@ -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});
|
||||
|
||||
@@ -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.
|
@@ -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
|
||||
@@ -2062,6 +2067,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 +2564,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
|
||||
@@ -3714,6 +3741,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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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é
|
||||
@@ -2059,6 +2064,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 +2561,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
|
||||
@@ -3711,6 +3738,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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
@@ -2062,6 +2067,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 +2564,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
|
||||
@@ -3714,6 +3741,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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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).
|
||||
@@ -2064,6 +2069,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 +2379,9 @@
|
||||
Smart Guides (View → Smart Guides) スマートガイド (表示 → スマートガイド)
|
||||
Smart Guides (⌘U) スマートガイド (⌘U)
|
||||
Smooth スムーズ
|
||||
Corner コーナー
|
||||
Relative 相対
|
||||
Absolute 絶対
|
||||
Smooth Tool スムーズツール
|
||||
Snap Curves To Lines 曲線を直線にスナップ
|
||||
View: 表示:
|
||||
@@ -3726,3 +3753,21 @@ 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 フォルダーでは、このファイルの番号付きの名前がすべて使われています
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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.
|
||||
@@ -1819,6 +1820,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.
|
@@ -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 Резкость
|
||||
@@ -2058,6 +2063,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 +2560,9 @@
|
||||
Smart Guides (⌘U) Умные направляющие (⌘U)
|
||||
Smart Punctuation… Умная пунктуация…
|
||||
Smooth Сгладить
|
||||
Corner Угол
|
||||
Relative Относительно
|
||||
Absolute Абсолютно
|
||||
Smooth Color Сглаженный цвет
|
||||
Smooth Tool Инструмент «Сглаживание»
|
||||
Snap Curves To Lines Привязывать кривые к линиям
|
||||
@@ -3710,6 +3737,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 Службы
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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… Розумне розмиття…
|
||||
@@ -2054,6 +2059,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 +2556,9 @@
|
||||
Smart Guides (⌘U) Розумні напрямні (⌘U)
|
||||
Smart Punctuation… Розумна пунктуація…
|
||||
Smooth Згладити
|
||||
Corner Кут
|
||||
Relative Відносно
|
||||
Absolute Абсолютно
|
||||
Smooth Color Згладжений колір
|
||||
Smooth Tool Інструмент «Згладжування»
|
||||
Snap Curves To Lines Прив’язувати криві до ліній
|
||||
@@ -3697,6 +3724,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 Масштаб
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 632 and column 40.
|
@@ -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 以搜索所有命令
|
||||
@@ -2016,6 +2021,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 +2481,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.
|
@@ -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 以搜尋所有指令
|
||||
@@ -2065,6 +2070,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 +2567,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.
|
@@ -886,11 +886,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}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
@@ -879,6 +891,8 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
|
||||
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()),
|
||||
|
||||
@@ -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) }?;
|
||||
|
||||
@@ -348,11 +348,14 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile
|
||||
p["link"] = json!(!embed);
|
||||
run(app, &p).map(|_| ())
|
||||
}
|
||||
DropTarget::Open => io::open_bytes(app, &name, &bytes, path.clone()).map(|_| {
|
||||
if let Some(path) = &path {
|
||||
io::note_recent(app, path);
|
||||
}
|
||||
}),
|
||||
DropTarget::Open => match path.as_deref() {
|
||||
Some(path) if app.services.read.is_some() => io::open_path(app, path).map(|_| ()),
|
||||
_ => io::open_bytes(app, &name, &bytes, path.clone()).map(|_| {
|
||||
if let Some(path) = &path {
|
||||
io::note_recent(app, path);
|
||||
}
|
||||
}),
|
||||
},
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(if target == DropTarget::Open { format!("Couldn't open {name}: {e}") } else { format!("Couldn't place {name}: {e}") });
|
||||
|
||||
@@ -347,6 +347,18 @@ pub struct UiState {
|
||||
/// dialog is open.
|
||||
#[serde(skip)]
|
||||
pub dialog_file: Option<std::sync::Arc<crate::dialogs::import_pdf::DialogFile>>,
|
||||
/// The documents (uids) whose Missing Fonts dialog waits until no dialog is open, the next one to
|
||||
/// show first ([`crate::dialogs::settle`]).
|
||||
#[serde(skip)]
|
||||
pub pending_fonts: Vec<u64>,
|
||||
/// The document (uid) whose Missing Fonts dialog is on show. When another dialog takes its
|
||||
/// place, [`crate::dialogs::settle`] puts the document back at the front of `pending_fonts`.
|
||||
#[serde(skip)]
|
||||
pub fonts_dialog: Option<u64>,
|
||||
/// The search the Missing Fonts dialog started (`text.findFontFiles`'s `id`), stopped once the
|
||||
/// dialog is gone.
|
||||
#[serde(skip)]
|
||||
pub dialog_search: Option<u64>,
|
||||
/// The DXF Options chosen last (`document.exportDxf` options; null: never used).
|
||||
#[serde(default)]
|
||||
pub dxf_options: Value,
|
||||
@@ -519,6 +531,9 @@ impl Default for UiState {
|
||||
svg_options: Value::Null,
|
||||
place_link: true,
|
||||
dialog_file: None,
|
||||
pending_fonts: vec![],
|
||||
fonts_dialog: None,
|
||||
dialog_search: None,
|
||||
dxf_options: Value::Null,
|
||||
eps_options: Value::Null,
|
||||
dxf_import: Value::Null,
|
||||
|
||||
@@ -55,13 +55,33 @@ impl egui::DroppedFile for Dropped {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MockDrop {
|
||||
path: std::path::PathBuf,
|
||||
bytes: Result<Vec<u8>, String>,
|
||||
}
|
||||
|
||||
impl egui::DroppedFile for MockDrop {
|
||||
fn path(&self) -> &std::path::Path {
|
||||
&self.path
|
||||
}
|
||||
fn bytes(&self) -> Result<Vec<u8>, String> {
|
||||
self.bytes.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// One headless frame of the whole window (800×600) with `events` and `dropped` files.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, mut events: Vec<egui::Event>, dropped: &[&str], shift: bool) {
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, dropped: &[&str], shift: bool) {
|
||||
let files = dropped.iter().map(|p| Arc::new(Dropped(p.into())) as egui::DroppedFileHandle).collect();
|
||||
frame_files(app, ctx, events, files, shift);
|
||||
}
|
||||
|
||||
fn frame_files(app: &mut VectorcraftApp, ctx: &egui::Context, mut events: Vec<egui::Event>, dropped: Vec<egui::DroppedFileHandle>, shift: bool) {
|
||||
events.push(egui::Event::ModifiersChanged(egui::Modifiers { shift, ..Default::default() }));
|
||||
let raw = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
|
||||
events,
|
||||
dropped_files: dropped.iter().map(|p| Arc::new(Dropped(p.into())) as egui::DroppedFileHandle).collect(),
|
||||
dropped_files: dropped,
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
@@ -79,7 +99,7 @@ fn selected_image(app: &VectorcraftApp) -> vectorcraft_doc::Node {
|
||||
}
|
||||
|
||||
/// A tiny SVG document.
|
||||
const SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="50" height="40"><rect width="20" height="10"/></svg>"#;
|
||||
const SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="50" height="40"><path d="M5 5 L45 5 L30 30 Z"/></svg>"#;
|
||||
|
||||
/// Two frames: fonts, then the canvas lays out → the canvas.
|
||||
fn laid_out(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::Rect {
|
||||
@@ -157,6 +177,84 @@ fn a_dropped_document_opens_as_a_tab_of_its_own() {
|
||||
assert_eq!(app.ui.recent_files.first(), Some(&svg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_native_svg_drop_uses_file_open_even_with_a_path_only_handle() {
|
||||
let path = temp_file("path-only.svg", SVG.as_bytes());
|
||||
let mut dropped = app();
|
||||
let ctx = egui::Context::default();
|
||||
laid_out(&mut dropped, &ctx);
|
||||
let handle = Arc::new(MockDrop { path: path.clone().into(), bytes: Err("only a path".into()) }) as egui::DroppedFileHandle;
|
||||
frame_files(&mut dropped, &ctx, vec![], vec![handle], false);
|
||||
|
||||
let mut opened = app();
|
||||
opened.run("file.open", json!({ "path": path })).unwrap();
|
||||
let anchors = |app: &VectorcraftApp| {
|
||||
let mut count = 0;
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
count += path.anchors().count();
|
||||
}
|
||||
});
|
||||
count
|
||||
};
|
||||
assert_eq!(anchors(&dropped), anchors(&opened), "same editable SVG anchors as File > Open");
|
||||
assert!(anchors(&dropped) >= 3, "the imported path has editable anchors");
|
||||
assert_eq!(dropped.session.active().unwrap().path, opened.session.active().unwrap().path);
|
||||
assert_eq!(dropped.session.active().unwrap().selection.objects.len(), opened.session.active().unwrap().selection.objects.len());
|
||||
assert_eq!(dropped.ui.recent_files, opened.ui.recent_files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_drop_without_a_path_is_detected_from_its_bytes() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
laid_out(&mut app, &ctx);
|
||||
let svg = Arc::new(MockDrop { path: Default::default(), bytes: Ok(SVG.as_bytes().to_vec()) }) as egui::DroppedFileHandle;
|
||||
frame_files(&mut app, &ctx, vec![], vec![svg], false);
|
||||
assert_eq!(app.session.documents().len(), 2, "SVG bytes open as a document, not placed art");
|
||||
assert!(app.session.active().unwrap().path.is_none(), "no filesystem path was supplied");
|
||||
|
||||
frame(&mut app, &ctx, vec![], &[], false);
|
||||
let image = Arc::new(MockDrop { path: Default::default(), bytes: Ok(png(6, 6, 72.0)) }) as egui::DroppedFileHandle;
|
||||
frame_files(&mut app, &ctx, vec![], vec![image], false);
|
||||
assert_eq!(app.session.documents().len(), 2, "an image is placed, not opened");
|
||||
assert_eq!(images(&app, 1), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_svg_drops_open_individually() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
laid_out(&mut app, &ctx);
|
||||
let a = temp_file("first.svg", SVG.as_bytes());
|
||||
let b = temp_file("second.svg", SVG.as_bytes());
|
||||
frame(&mut app, &ctx, vec![], &[&a, &b], false);
|
||||
assert_eq!(app.session.documents().len(), 3);
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(b.as_str()));
|
||||
assert_eq!(&app.ui.recent_files[..2], &[b, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_and_unreadable_drops_leave_the_document_open() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
laid_out(&mut app, &ctx);
|
||||
let invalid = temp_file("not-art.xyz", b"not an image or document");
|
||||
frame(&mut app, &ctx, vec![], &[&invalid], false);
|
||||
assert!(app.ui.status.contains("Couldn't place not-art.xyz"), "{}", app.ui.status);
|
||||
|
||||
let invalid_svg = temp_file("broken.svg", b"<svg");
|
||||
frame(&mut app, &ctx, vec![], &[&invalid_svg], false);
|
||||
assert!(app.ui.status.contains("Couldn't open broken.svg"), "{}", app.ui.status);
|
||||
|
||||
let missing = temp_file("unreadable.svg", SVG.as_bytes());
|
||||
std::fs::remove_file(&missing).unwrap();
|
||||
frame(&mut app, &ctx, vec![], &[&missing], false);
|
||||
assert!(app.ui.status.contains("Couldn't open unreadable.svg"), "{}", app.ui.status);
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
assert!(app.ui.recent_files.is_empty(), "failed drops don't enter Open Recent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_dropped_with_no_document_open_open_and_are_recent() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -206,4 +206,23 @@ mod tests {
|
||||
app.run("app.quit", json!({})).unwrap();
|
||||
assert_eq!(app.ui.status, "quit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_channels_quit_says_when_it_asks_first() {
|
||||
// #830: it answered null at once, before the question.
|
||||
let (mut app, _) = app();
|
||||
let ctx = egui::Context::default();
|
||||
let quit = |app: &mut VectorcraftApp| {
|
||||
let (req, _rx) = crate::control::ControlRequest::new("app.quit", json!({}));
|
||||
let crate::control::Outcome::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("not done") };
|
||||
r
|
||||
};
|
||||
new_doc(&mut app, true);
|
||||
assert_eq!(quit(&mut app), json!({"ok": true, "result": {"pending": KIND}}));
|
||||
assert_eq!((pending(&app), app.ui.status.as_str()), (Some(0), ""));
|
||||
app.ui.dialog = None;
|
||||
app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap();
|
||||
assert_eq!(quit(&mut app), json!({"ok": true, "result": null}));
|
||||
assert_eq!(app.ui.status, "quit");
|
||||
}
|
||||
}
|
||||
@@ -375,6 +375,27 @@ folder; `ui.dialog.set {field: "discard", value: true}` then confirm ignores it
|
||||
Then, with the preference `updateLinks: "askWhenModified"`, modified linked files are offered for update in a
|
||||
`confirm` dialog whose `ui.dialog.confirm` runs `links.update`.
|
||||
|
||||
Missing fonts: once the missing linked file questions are answered, or at once when there are none, `app.open` of a
|
||||
document whose type uses fonts that aren't available (`text.missingFonts`) opens the `missingFonts` dialog, one document
|
||||
at a time, and so does `links.editOriginal` of a placed document. When another dialog takes its place (Import PDF for a
|
||||
file opened next, for example), the dialog opens again once that one closes. Fields: `document` (the document's uid),
|
||||
`fonts` (`[{family, style, status, resolved}]`), `fontsNextToDocument` (the `Fonts` folder next to the document, 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` and
|
||||
`chosen` (the files to add; a font's first file is chosen when the search finds it). Its buttons are Find Fonts and
|
||||
Close, with Search Fonts Folder, Find in Folder… and, once files are found, Add Fonts in the dialog.
|
||||
`ui.dialog.set {field: "discard", value: true}` then `ui.dialog.confirm` is Find Fonts: the dialog closes and Type ›
|
||||
Find Font opens (dialog `findFont`) with the first missing font selected. `ui.dialog.set {field: "searchFolder",
|
||||
value}` then `ui.dialog.confirm` searches that folder (`text.findFontFiles`), keeps the dialog open and clears
|
||||
`searchFolder`, also when the search doesn't start. The fields change as frames draw the dialog; `text.findFontFiles
|
||||
{}` reports the search directly. `ui.dialog.confirm` without `discard` or `searchFolder` is Add Fonts: it copies the
|
||||
files in `chosen` (`text.addFontFiles`) and closes the dialog. `ui.dialog.cancel` (Close) closes it and stops its
|
||||
search. After Find Fonts or Close, the dialog doesn't open again for that open.
|
||||
`ui.missingFontsDialog {folder?}` opens the dialog for the active document, searching `folder` when given.
|
||||
`ui.findFontsInFolder {folder?}` (Find in Folder… in Type › Find Font…, shown when the document misses fonts) asks for a
|
||||
folder, then opens the dialog searching it. The web shows a status line instead of the dialog, and both commands are
|
||||
disabled there.
|
||||
|
||||
Text Import Options: placing a `.txt` file through the app (`file.place` with a file and no `text` options, the Place
|
||||
dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: `unicode`/`ansi`,
|
||||
`removeLineReturns`, `removeParagraphReturns`, `replaceSpaces`, `spaces`). `ui.dialog.confirm` places the file as area
|
||||
|
||||
+62
-6
@@ -412,8 +412,11 @@ An Illustrator EPS (version 9 on) or `.ai` file opens from the editing data it c
|
||||
colour), groups as they were nested, compound paths, clipping groups, object names, hidden and locked objects, fills and
|
||||
strokes (spot colours as spot swatches), 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 is the page's, in its
|
||||
text object's place; hidden point type is made from the file's text document. A file whose editing data has symbols,
|
||||
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: point type, area type (a story in several frames as threaded type) and type on a path,
|
||||
with its fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment,
|
||||
indents and paragraph spacing. Where the text document can't say, type that shows is the page's, in its text object's
|
||||
place. A file whose editing data has symbols,
|
||||
pattern fills, placed files or anything else the reader doesn't read on a layer that shows, or whose layers look
|
||||
different from its page, opens as before: an EPS as its printed page, a `.ai` file from its PDF content (where plain
|
||||
groups open ungrouped), with a warning saying why. Layers look different when they draw an object the page doesn't (or
|
||||
@@ -449,8 +452,10 @@ CMYK too.
|
||||
|
||||
PostScript files (`.eps`, and `.ai` files saved in older formats or without PDF compatibility) open through the EPS
|
||||
reader (see EPS and PostScript import). An `.ai` saved without PDF compatibility (its PDF part is only a placeholder
|
||||
page) opens from its editing data alone: its type is made from the file's text document where it can be (point type), and
|
||||
what can't be is left out with a warning; without editing data it says it can't be opened.
|
||||
page) opens from its editing data alone: its type is made from the file's text document where it can be (point type,
|
||||
area type and type on a path), and what can't be is left out with a warning; so is non-native art (the content of a
|
||||
placed PDF, which Illustrator shows but doesn't edit and keeps as a PDF inside the editing data); without editing data
|
||||
it says it can't be opened.
|
||||
|
||||
What a PDF holds comes in as editable art: soft masks become opacity masks (an alpha mask as a white copy of its art;
|
||||
the backdrop colour gives Clip, an inverting transfer function Invert), transparency groups keep isolation and knockout,
|
||||
@@ -1843,7 +1848,9 @@ bounds; `clip` puts it in a clip group of the old bounds when it is larger). The
|
||||
unsaved one is an error) into `folder/name` (default name `<document> Folder`): `<document>.vectorcraft`, its linked
|
||||
files in `Links/` (relinked: the packaged document points at the copies; the open one doesn't change), the fonts its
|
||||
type uses in `Fonts/` (fonts whose licence doesn't allow embedding are listed in `skippedFonts` instead) and
|
||||
`<document> Report.txt`. Every option defaults to true. Without `folder` (the web, or an agent that wants the bytes) the
|
||||
`<document> Report.txt`. A placed `.vectorcraft` document is packaged with its own linked files and fonts, relinked to
|
||||
the copies (each file copied once); one that can't be read is copied as it is, and a cycle of placed documents or one
|
||||
past the nesting limit stops there, each with a line in `warnings` and the report. Every option defaults to true. Without `folder` (the web, or an agent that wants the bytes) the
|
||||
result carries the same files as a zip (`{name: "<name>.zip", dataBase64}`, entries under `<name>/`).
|
||||
|
||||
`document.info {selectionOnly?, category?, format?: "text"}` adds `sections` (`[{id, title, rows: [[label, value]]}]`:
|
||||
@@ -2561,7 +2568,11 @@ the fonts CoreText's font manager lists outside them, such as those apps and fon
|
||||
folders; Linux and BSD: `/usr/share/fonts`,
|
||||
`/usr/local/share/fonts`, `~/.fonts` and the XDG data folders' `fonts`, `~/.local/share/fonts` among them, and in a
|
||||
Flatpak sandbox the host's fonts). Faces without outlines VectorCraft draws (no `glyf`, `CFF`, `CFF2` or `VARC` table, such
|
||||
as bitmap-only fonts) are left out. The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
|
||||
as bitmap-only fonts) are left out. The scan also reads the folder the `fontsFolder` preference names (Preferences › Type ›
|
||||
Additional Fonts Folder) with its subfolders and, in the desktop app and `vectorcraft-cli`, VectorCraft's own `Fonts` folder
|
||||
next to the preferences: `~/Library/Application Support/VectorCraft/Fonts` on macOS, `%APPDATA%\VectorCraft\Fonts` on
|
||||
Windows, and `$XDG_CONFIG_HOME/vectorcraft/Fonts` or `~/.config/vectorcraft/Fonts` on Linux and BSD. `text.addFontFiles`
|
||||
copies fonts into that folder. The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
|
||||
by family name), so opening, placing, pasting and importing files find them whatever ran before. `text.fontList`
|
||||
lists every family available, the installed ones included, as the font menus do: without the system's hidden
|
||||
families, whose names start with "." (macOS's ".SF NS", ".LastResort"), which still resolve when a document names
|
||||
@@ -2577,6 +2588,51 @@ comes to the front and a font folder changed meanwhile.
|
||||
{"name":"run_command","arguments":{"command":"text.rescanFonts","params":{}}}
|
||||
```
|
||||
|
||||
`text.missingFonts` lists the fonts that the active document's type uses, in its layers and its symbols, and that aren't
|
||||
available as named: `{fonts: [{family, style, status, resolved}], count, fontsNextToDocument?}`. `status` is `missing` or
|
||||
`substitute`, as in `text.fonts`. CSS generic families such as `sans-serif`, which no font file provides, and names
|
||||
longer than 256 bytes are left out. `fontsNextToDocument` is the `Fonts` folder next to the saved document
|
||||
(File › Package writes it), when there is one and a search may start there. `text.findFontFiles {folder}` looks for
|
||||
the fonts' files in an absolute folder and its subfolders on separate threads and returns at once with
|
||||
`state: "searching"` and an `id`; `fonts: [{family, style?}]` names other fonts to look for. `text.findFontFiles {}`
|
||||
returns the last search's state with the files found so far for each font: `searching`, `done`, `stopped` (with
|
||||
`stopped`: `stop`, `time` or `limit`) or `failed` (with `error`); before the first search it returns
|
||||
`{state: "idle", fonts: []}`, without an `id`. `{stop: true}` stops the search. A search reads the table directories
|
||||
and the `name`, `fvar` and `OS/2` tables of `.ttf`, `.otf`, `.ttc` and `.otc` files and, on macOS, of suitcase fonts
|
||||
(extensionless or `.suit` files whose fonts are in their resource fork), and it lists a file for a font only when adding
|
||||
the file makes the font resolve exactly as `text.fonts` resolves it. It ends after `maxSeconds` (60 by default, 1 to
|
||||
600), at its limits on the entries listed (10,000,000), the folders waiting to be listed (1,000,000), the font files
|
||||
read (10,000) and the files kept (1,000), or once every font has a file. Folders more than 64 levels below the picked
|
||||
one are skipped and counted in `skipped`. A search does not read a font file larger than 256 MB, which
|
||||
`text.addFontFiles` does not copy, or a suitcase font whose resource fork is larger than 8 MB.
|
||||
|
||||
A search does not enter app and media library packages (`.app`, `.bundle`, `.framework`, `.photoslibrary` and the like),
|
||||
folders named `Program Files` (also `Program Files (x86)` and `Program Files (Arm)`), `ProgramData`, `$Recycle.Bin` or
|
||||
`System Volume Information`, the system's folders at the root of a volume (a macOS, Linux, BSD or Windows root, told by
|
||||
the folders it holds), the `Shared` and `Public` folders in `Users`, a home folder's `Library`, `AppData`,
|
||||
`Applications` and `snap` folders and the folders in it whose names start with a dot, the app data folders in a
|
||||
`Library` folder (`Application Support`, `Containers`, `Group Containers`, `Caches`, `Preferences`), or the folders the
|
||||
environment names for apps and the system (such as `APPDATA`, `LOCALAPPDATA`, `ProgramFiles`, `SystemRoot` and
|
||||
`XDG_CONFIG_HOME`), and a search of a folder inside one of them fails. The walk also skips other hidden folders and
|
||||
folders whose contents are in the cloud, and it follows no links; a picked folder may be one of those, and a picked path
|
||||
that goes through a link is searched at its target. Programs installed in other folders, such as a folder on another
|
||||
drive, are searched as any other folder is.
|
||||
|
||||
`text.addFontFiles {files}` copies files that the session's last search found into VectorCraft's `Fonts` folder, then
|
||||
scans the fonts again, and type set in them redraws. 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, and lists any
|
||||
other file in `skipped`. It never replaces a file: a file with the same contents is kept (`kept`), and when another
|
||||
file has the name, the copy gets a number (`Name 2.otf`). Copy only fonts you own or are licensed to install. `command.batch` returns before a search ends; later requests over MCP or the control channel poll
|
||||
`text.findFontFiles {}`. `vectorcraft-cli run` stops the search when its last step ends. The web build has no Fonts
|
||||
folder and no folder search.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"text.missingFonts","params":{}}}
|
||||
{"name":"run_command","arguments":{"command":"text.findFontFiles","params":{"folder":"/Users/me/Downloads"}}}
|
||||
{"name":"run_command","arguments":{"command":"text.findFontFiles","params":{}}}
|
||||
{"name":"run_command","arguments":{"command":"text.addFontFiles","params":{"files":["/Users/me/Downloads/Example/Example-Regular.otf"]}}}
|
||||
```
|
||||
|
||||
## Tool options
|
||||
|
||||
`tool.setOption` reads and sets a tool's options, headless too: `{key, value}` or `{values: {…}}` sets them on the
|
||||
|
||||
Reference in new issue
Block a user