Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 4767ec7113 Fix #398: Linux/Wayland bitmap paste, copied files paste as art
Under Wayland the window is native but arboard was built without its
data-control backend, so it read the X11 clipboard through XWayland,
which only holds what X11 apps copied: Paste found nothing and reported
an empty clipboard (egui's text paste into fields uses smithay-clipboard,
which is why that worked). arboard now has `wayland-data-control`, the
same as PhotoCraft; it falls back to X11 where the compositor lacks the
protocol (GNOME's Mutter).

The reporter's clipboard also held text/uri-list: with a file copied in a
file manager, Paste would have taken the path as text before the bitmap.
Copied files now paste first, as the first one that is art (SVG, PDF,
EMF/WMF or a bitmap), told from its first 4 KiB by the engine's format
detection (`clipboard::file_flavour`): text/uri-list through arboard on
Linux and macOS (a trailing CR from CRLF lists trimmed), CF_HDROP on
Windows, read with the clipboard closed again.

Dropping files on the window can't work under Wayland yet: winit 0.30,
which eframe 0.36 runs on, has no Wayland drag and drop (winit#1881,
added in 0.31), so no dropped_files arrive. docs/development.md documents
it and the workarounds (copy and paste the files, File > Place, or run
under XWayland with `WAYLAND_DISPLAY=`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:44:23 +07:00
bflatasticandClaude Opus 5.5 526fc2e157 MCP: reject document.node slices without summary, document and sweep them (review of #405)
`depth` / `childLimit` without `summary: true` used to return the whole
full-JSON subtree silently; it is now an invalid-params error. docs/mcp.md
describes the slice parameters and childCount, the engine test covers
fractional values, unsliced reads and limits past the tree, and the CLI
stdio sweep reads a sliced group through run_command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:43:07 +07:00
Fahri Meral 81ab5cb3b0 MCP: slice summary reads with document.node depth and childLimit 2026-10-08 07:43:07 +07:00
BFlat 8221b73729 Merge pull request #397 from DWAA1660/fix/font-menu-find-font-glyphs
#358: Find Font's Replace With and the Glyphs panel use the font menu
2026-10-08 07:42:27 +07:00
BFlat c8155e9d69 Merge pull request #389 from imachus/pr/ja-charalign
Type: Character Alignment — where smaller characters line up with a line's largest
2026-10-08 07:42:07 +07:00
BFlat 52f4fb38f2 Merge pull request #390 from theironchef/fix/freehand-tool-options
Pencil, Paintbrush, Smooth, Blob Brush and Eraser: Tool Options on double-click
2026-10-08 07:41:25 +07:00
bflatasticandClaude Opus 5.5 d324138bc1 Fonts: drop the plain font dropdown now that no picker uses it (review of #397)
Find Font and the Glyphs panel were widgets::font_dropdown's last
callers; the font menu's own tests cover searching and Enter. ROADMAP:
the Glyphs panel and Find Font's Replace With use the font menu, without
its live preview.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:32:12 +07:00
bflatasticandClaude Opus 5.5 18cbe007b8 Character Alignment: on a character range too, with the East Asian options (review of #389)
text.setRangeStyle takes charAlign, so the panel menu works on the
characters selected with the Type tool (it routes there while text is
edited, and charAlign alone was answered with "nothing to change").
One char_align_param parses it for both commands. The menu shows with
Preferences › Type › Show East Asian Options, like Mojikumi Set and
Top-to-Top Leading. Rows in the Simplified Chinese, Spanish and
Brazilian Portuguese catalogs; the Japanese Em Box Center names the em
box. ROADMAP: the gating, the range command, and ICF top/bottom still
missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:32:11 +07:00
DWAA1660andClaude Opus 5.5 1d5e9cb239 Find Font and Glyphs: pick fonts from the font menu (#358 follow-up)
Both switch from widgets::font_dropdown to font_menu::font_menu, so they
get the same samples, favourites and filters as the Character and
Properties panels. They only pick a font: the new font_menu::picked
returns the choice and toggles stars, and never previews on the document.

Follow-up to #339 as suggested in #364.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRE8ZD3p8QgYctENhnJDz3
2026-10-08 07:32:11 +07:00
imachusandClaude Opus 5.5 178ca03eba Type: Character Alignment — where smaller characters line up with a line's largest
Characters of different sizes on one line all sat on the Roman baseline.
Japanese layout usually lines them up by their ideographic em boxes
instead (a 16 pt 第一回 next to 32 pt 雅楽 centred on it, not sitting on
its baseline). The Character panel menu now has Character Alignment:

- `CharStyle.char_align`: Roman Baseline (as before, the default), or the
  em box Top/Right, Center or Bottom/Left: a character smaller than the
  line's largest moves so that its em box top, centre or bottom lines up
  with the largest's (the em box from the font's vertical metrics, else
  0.12 em below the baseline to 0.88 em above it). Vertical type the
  same across the column (top → right). Written only when not Roman
  Baseline.
- `text.setFormat {charAlign: "romanBaseline"|"emBoxTop"|"emBoxCenter"|
  "emBoxBottom"}`; the menu shows the selection's setting; catalog rows
  in ja and zh-hant.
- Not yet: aligning on the ICF (average character face) top and bottom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:32:10 +07:00
bflatasticandClaude Opus 5.5 505f3bd7ae Freehand Tool Options: Accurate/Smooth ends on the Fidelity slider, Spanish rows (review of #390)
The Fidelity slider names its ends, Accurate and Smooth, through a
shared form::slider_ends that the Color Guide Options' Less/More now use
too. The dialog's strings get Spanish rows (complete catalog), and
Accurate rows in every catalog. ROADMAP: the Drawing tools row lists
what the freehand Tool Options still lack (Keep selected, Alt to the
Smooth tool, Blob Brush Merge Only with Selection, brush angle and
roundness).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:32:09 +07:00
theironchefandClaude Sonnet 5.5 02582f318d Fix #388: Pencil, Paintbrush, Smooth, Blob Brush and Eraser Tool Options on double-click
The five freehand tools keep options (Fidelity, fill, the two
tolerances, the brush size) that last across tool switches and are
saved with the preferences, but nothing in the window showed or changed
them: a double-click on the tool's button answered "the pencil tool has
no options", which the toolbar drops. It now opens a Tool Options dialog
with the options the tool has, and OK sets them with tool.setOption. The
dialog's strings are in the Japanese, Chinese (both scripts) and
Brazilian Portuguese catalogs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-08 07:32:09 +07:00
BFlat a80d9b8195 Merge pull request #409 from storytold/fix/issue-392
Fix #392: Cmd+A selects a focused field's text or the type being edited
2026-10-08 07:31:45 +07:00
BFlat 2a434190f2 Merge pull request #408 from storytold/fix/issue-396
Fix #396: SVG type opens at the size it draws at
2026-10-08 07:31:29 +07:00
BFlat d036a6d613 Merge pull request #403 from storytold/fix/issue-369
Fix #369: restart the web build's graphics after a lost device or context
2026-10-08 07:31:13 +07:00
41 changed files with 884 additions and 173 deletions

No files matched your search

Generated
+66
View File
@@ -217,6 +217,7 @@ dependencies = [
"parking_lot",
"percent-encoding",
"windows-sys 0.60.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -1242,6 +1243,12 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
name = "fixedbitset"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
[[package]]
name = "flate2"
version = "1.1.10"
@@ -2367,6 +2374,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2754,6 +2770,16 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "os_pipe"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.52.0",
]
[[package]]
name = "parking"
version = "2.2.1"
@@ -2814,6 +2840,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4067,6 +4104,17 @@ dependencies = [
"once_cell",
]
[[package]]
name = "tree_magic_mini"
version = "3.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
dependencies = [
"memchr",
"nom",
"petgraph",
]
[[package]]
name = "ttf-parser"
version = "0.25.1"
@@ -5640,6 +5688,24 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "wl-clipboard-rs"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"
dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-protocols-wlr",
]
[[package]]
name = "write-fonts"
version = "0.48.1"
+9 -9
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381) and SVG type opening at the size it draws at (#396); see [Honest assessment](#honest-assessment-2026-10-05))._
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396) and the Wayland clipboard with copied-file paste (#398); see [Honest assessment](#honest-assessment-2026-10-05))._
## Where we are
@@ -42,7 +42,7 @@ since 2026-10-01.
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); hybrid-graphics laptops render on the power-saving GPU by default (#306); web drops land in the document they were dropped on (#359); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); hybrid-graphics laptops render on the power-saving GPU by default (#306); web drops land in the document they were dropped on (#359); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel |
### Where we're lacking (in priority order)
@@ -90,7 +90,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command.
- JSON-lines control channel with real egui pointer and keyboard injection.
- MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings.
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`).
- Actions panel that records and plays back commands.
- **UI:** Illustrator 2026 layout restyled to measured values:
@@ -121,7 +121,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked.
- **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool.
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options.
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies, the trash deletes), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.
- **Drawing aids:** Smart Guides and snapping (moving, and resizing by the bounding-box handles: the dragged edges align with the other objects; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H), guides dragged out of the rulers, and Draw Normal / Behind / Inside modes.
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it.
@@ -129,7 +129,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected.
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text.
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese and Spanish (neutral international Spanish, for every `es-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech and Spanish ones from the bundled UI fonts. The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese and Spanish (neutral international Spanish, for every `es-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech and Spanish ones from the bundled UI fonts. The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline; Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; Alt deletes their pieces; filled open paths count as closed), Live Paint (every path an edge, open lines included), Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Paint and appearance (M3):**
@@ -148,7 +148,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export.
- 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); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers; strokes kept live, a fill and a stroke of one outline as one object; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs Illustrator's AGM/CoolType prologs (resource categories, `resourceforall`, `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters, `cshow`, metadata skipped with `flushfile`), so Illustrator 30 EPS files open as vectors, and falls back to its palette TIFF preview. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours.
- 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).
- **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 the desktop app asks for the power-saving GPU by default (the integrated one on hybrid-graphics laptops, where presenting from the discrete GPU made the window flicker, #306). Preferences › Performance › Graphics Processor (`gpuPreference`) or `WGPU_POWER_PREF` picks the discrete one; Help › About and `ui.inspect` 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).
- **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`).
@@ -164,7 +164,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info. Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, polish | 3–6 |
| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 |
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open) | 3–6 |
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects, tab stops + Tabs panel, Hebrew/Arabic bidirectional text and Paragraph Direction done; tab leaders, spell check, vertical type pending | 45–60 |
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects, tab stops + Tabs panel, Hebrew/Arabic bidirectional text and Paragraph Direction done; tab leaders, spell check, vertical type pending | 45–60 |
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 |
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 |
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; brushes/symbols in progress | 23–37 |
@@ -191,7 +191,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Area | Weight | Done | Missing (main items) | One agent (h) |
|---|---:|---:|---|---:|
| Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Start Global Edit, transform nuances (the rotated persistent bounding box is done) | 4–6 |
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pencil and the remaining pen modifier nuances, Touch Type, Live Corners on plain paths and polygons (and Relative rounding) | 10–15 |
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners on plain paths and polygons (and Relative rounding) | 10–15 |
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection and options | 3–6 |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4 |
| 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 |
@@ -200,7 +200,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 20% | ~55 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery; Document Raster Effects Settings and raster effects in PDF are done | 28–42 |
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
| Type core | 9 | 79% | 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); composer/hyphenation options, Optical Margin Alignment, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 15–20 |
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — hanging punctuation, line-start brackets, kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support | 20–28 |
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — hanging punctuation, line-start brackets, kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko, Character Alignment on the ICF top and bottom), 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 | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 |
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (Vector Halftone is done) | 6–10 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard presets/rearrange polish (Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
+21
View File
@@ -160,6 +160,27 @@ fn mcp_protocol_over_stdio() {
send(&mut stdin, json!({"jsonrpc":"2.0","id":10,"method":"resources/read","params":{"uri":"vectorcraft://object/"}}));
assert_eq!(recv(&mut lines, &mut notes, 10)["error"]["code"], -32602);
// Large containers slice through run_command document.node: a truncated level reports
// childCount, and a bad limit is a tool error, not a crash or a full read.
send(
&mut stdin,
json!({"jsonrpc":"2.0","id":20,"method":"tools/call","params":{"name":"draw_shape","arguments":{"shape":"ellipse","x":90,"y":10,"width":30,"height":30}}}),
);
assert_eq!(recv(&mut lines, &mut notes, 20)["result"]["isError"], false);
let run = |id: u64, command: &str, params: Value| json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"run_command","arguments":{"command":command,"params":params}}});
send(&mut stdin, run(21, "select.all", json!({})));
recv(&mut lines, &mut notes, 21);
send(&mut stdin, run(22, "object.group", json!({})));
let r = recv(&mut lines, &mut notes, 22);
let group = serde_json::from_str::<Value>(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap()["id"].clone();
send(&mut stdin, run(23, "document.node", json!({"id": group, "summary": true, "childLimit": 1})));
let r = recv(&mut lines, &mut notes, 23);
let sliced: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
assert_eq!(sliced["children"].as_array().map(Vec::len), Some(1), "{sliced}");
assert_eq!(sliced["childCount"], 2, "{sliced}");
send(&mut stdin, run(24, "document.node", json!({"id": group, "summary": true, "depth": -1})));
assert_eq!(recv(&mut lines, &mut notes, 24)["result"]["isError"], true);
// The binary installed its logger: records arrive as notifications/message, and only
// after the client asked for them.
send(&mut stdin, json!({"jsonrpc":"2.0","id":11,"method":"logging/setLevel","params":{"level":"debug"}}));
+2 -1
View File
@@ -26,7 +26,8 @@ log = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
# wayland-data-control: native Wayland clipboard (Linux; X11 through XWayland only sees what X11 apps copied).
arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
image = { workspace = true }
webbrowser = { workspace = true }
# The window's monitors, size and position (the same winit eframe runs on).
+90 -10
View File
@@ -4,11 +4,16 @@
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
//! Paste reads each of them.
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
//! else the PNG as a bitmap; Paste reads text and bitmaps.
//! else the PNG as a bitmap; Paste reads text and bitmaps. On Wayland, arboard's data-control
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
//! copied), falling back to X11 where the compositor lacks the protocol.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, a
//! metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
use std::io::Cursor;
use std::io::{Cursor, Read};
use std::path::PathBuf;
use vectorcraft_engine::cmd::clipboard::{BITMAP, Flavour, PNG, TEXT};
use vectorcraft_engine::cmd::clipboard::{BITMAP, FILE_HEAD, Flavour, PNG, TEXT, file_flavour};
use vectorcraft_ui_egui::SystemClipboard;
/// This platform's system clipboard.
@@ -29,6 +34,23 @@ fn decode_png(png: &[u8]) -> Option<image::RgbaImage> {
Some(image::load_from_memory_with_format(png, image::ImageFormat::Png).ok()?.to_rgba8())
}
/// The first of `paths` (files copied in a file manager) that pastes as one of `mimes`, read
/// whole. Only its first bytes are read to tell, so other files cost little.
fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
Some(p) if p.ends_with('\r') => PathBuf::from(p.trim_end_matches('\r')),
_ => path,
};
let mut head = Vec::with_capacity(FILE_HEAD);
std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?;
let data = std::fs::read(&path).ok()?;
(!data.is_empty()).then_some(Flavour { mime, data })
})
}
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
@@ -123,16 +145,26 @@ mod win {
}
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
mimes.iter().find_map(|m| read_one(m))
let mut files = vec![];
{
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
// None copied when the clipboard holds no file list.
let _ = raw::get_file_list_path(&mut files);
}
// The files are read with the clipboard closed again, not keeping other apps waiting.
copied_file(files, mimes).or_else(|| {
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
mimes.iter().find_map(|m| read_one(m))
})
}
fn has(&mut self, mimes: &[&'static str]) -> bool {
mimes.iter().any(|m| match *m {
TEXT => raw::is_format_avail(formats::CF_UNICODETEXT),
BITMAP => raw::is_format_avail(formats::CF_BITMAP) || formats_of(PNG).any(raw::is_format_avail),
m => formats_of(m).any(raw::is_format_avail),
})
raw::is_format_avail(formats::CF_HDROP)
|| mimes.iter().any(|m| match *m {
TEXT => raw::is_format_avail(formats::CF_UNICODETEXT),
BITMAP => raw::is_format_avail(formats::CF_BITMAP) || formats_of(PNG).any(raw::is_format_avail),
m => formats_of(m).any(raw::is_format_avail),
})
}
}
@@ -245,6 +277,9 @@ mod portable {
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
let cb = self.cb().ok()?;
if let Some(f) = cb.get().file_list().ok().and_then(|paths| copied_file(paths, mimes)) {
return Some(f);
}
mimes.iter().find_map(|m| match *m {
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Flavour { mime: TEXT, data: t.into_bytes() }),
BITMAP => {
@@ -262,3 +297,48 @@ mod portable {
}
}
}
#[cfg(test)]
mod tests {
use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG};
use super::*;
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
d
}
fn png(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::new(w, h).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
#[test]
fn the_first_copied_file_that_is_art_pastes() {
let d = dir("art");
let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg"));
std::fs::write(&notes, "not art").unwrap();
std::fs::write(&red, png(3, 2)).unwrap();
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
// Missing files, folders and text are skipped.
let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// Only what Paste asks for.
assert_eq!(copied_file(vec![art, red.clone()], &[BITMAP]).map(|f| f.mime), Some(PNG));
assert!(copied_file(vec![red], &[TEXT]).is_none());
assert!(copied_file(vec![notes], &PASTE_ORDER).is_none());
assert!(copied_file(vec![], &PASTE_ORDER).is_none());
}
#[test]
fn a_crlf_left_by_the_uri_list_is_ignored() {
let red = dir("crlf").join("red.png");
std::fs::write(&red, png(2, 2)).unwrap();
let with_cr = PathBuf::from(format!("{}\r", red.display()));
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
}
}
+2 -2
View File
@@ -78,8 +78,8 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
pub use style_libs::StyleLibrary;
pub use text::{
AreaOptions, CharPosition, CharStyle, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathEffect, ScriptMetrics,
TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape,
AreaOptions, CharAlign, CharPosition, CharStyle, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathEffect,
ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape,
};
pub use vectorcraft_color as color;
pub use vectorcraft_geom as geom;
+18
View File
@@ -86,6 +86,23 @@ pub struct CharStyle {
/// size (Document Setup → Type → Small Caps); None = off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub small_caps: Option<f64>,
/// Character Alignment (Character panel menu): where characters smaller than the largest on
/// their line line up with it.
#[serde(default, rename = "charAlign", skip_serializing_if = "crate::skip::is_default")]
pub char_align: CharAlign,
}
/// Where a character smaller than the largest on its line lines up with it: on the Roman
/// baseline, or at the top (right, in vertical type), centre or bottom (left) of the ideographic
/// em boxes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CharAlign {
#[default]
RomanBaseline,
EmBoxTop,
EmBoxCenter,
EmBoxBottom,
}
/// Superscript or subscript proportions in percent of the font size (Document Setup → Type).
@@ -178,6 +195,7 @@ impl Default for CharStyle {
stroke_miter_limit: 10.0,
stroke_dash: None,
position: CharPosition::Normal,
char_align: CharAlign::RomanBaseline,
small_caps: None,
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
use vectorcraft_geom::Rect;
pub use flavours::{BITMAP, EMF, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT};
pub use flavours::{BITMAP, EMF, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour};
pub(crate) use resources::SwatchChoices;
use super::*;
@@ -30,6 +30,23 @@ pub const EMF: &str = "image/emf";
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
/// (word processors offer a picture of copied text too).
pub const PASTE_ORDER: [&str; 5] = [SVG, PDF, EMF, TEXT, BITMAP];
/// How much of a copied file [`file_flavour`] needs to tell what it is.
pub const FILE_HEAD: usize = 4096;
/// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap):
/// SVG, PDF, a Windows metafile or a bitmap (its own `image/…` type), told from its first
/// [`FILE_HEAD`] bytes and its name. The file's bytes are that flavour's data.
pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> {
let f = fileio::detect(name, head)?;
let (asked, mime) = match f.id {
"svg" => (SVG, SVG),
"pdf" => (PDF, PDF),
"emf" | "wmf" => (EMF, EMF),
_ if f.raster => (BITMAP, f.mime),
_ => return None,
};
mimes.contains(&asked).then_some(mime)
}
/// One representation of the clipboard's contents.
#[derive(Clone, Debug, PartialEq, Eq)]
+20 -2
View File
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close),
cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate),
cmd!(query "document.inspect", "Inspect Document", [], None, "{} → layer tree, artboards, selection, history", has_doc, |s, _| Ok(inspect::document(s))),
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: the compact document.inspect-style summary instead of the full object JSON} → one object", has_doc, doc_node),
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))),
cmd!(
"document.setUnits",
@@ -105,8 +105,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?;
let opts = slice_opts(p)?;
let summary = bool_or(p, "summary", false);
if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) {
// The full object JSON is never truncated: a slice without `summary` would
// otherwise silently return the whole subtree.
return Err(bad("document.node", "`depth` and `childLimit` slice the summary: pass `summary: true`"));
}
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
if bool_or(p, "summary", false) { Ok(inspect::node_summary(n)) } else { Ok(serde_json::to_value(n).unwrap_or(Value::Null)) }
if summary { Ok(inspect::node_summary_opts(n, opts)) } else { Ok(serde_json::to_value(n).unwrap_or(Value::Null)) }
}
/// `depth` / `childLimit` for a summary read: absent (or null) means no limit.
/// A present value that is not a non-negative integer is rejected rather than
/// silently reinterpreted.
fn slice_opts(p: &Value) -> Result<inspect::SummaryOpts> {
let opt = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("document.node", format!("`{key}` must be a non-negative integer"))),
};
Ok(inspect::SummaryOpts { depth: opt("depth")?, child_limit: opt("childLimit")? })
}
/// Document Setup's units (also `document.setup {units}`).
+6 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top)}",
"{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it)}",
has_doc,
set_format
),
@@ -114,11 +114,13 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"mojikumi",
"direction",
"leadingModel",
"charAlign",
];
if !keys.iter().any(|k| p.get(*k).is_some()) {
return Err(bad(C, "nothing to change"));
}
let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?;
let char_align = super::textedit::char_align_param(p, C)?;
let mojikumi = match p.get("mojikumi") {
None => None,
Some(v) => Some(match v.as_str() {
@@ -179,6 +181,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = small_caps {
st.small_caps = v;
}
if let Some(v) = char_align {
st.char_align = v;
}
}
let para = &mut t.para;
if let Some(v) = num("leftIndent") {
+20 -1
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id, start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …]} style a character range (runs are split at the range ends) → {id, runs}",
"{id, start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
has_doc,
set_range_style
),
@@ -151,6 +151,7 @@ pub(crate) struct CharChange {
features: Option<Vec<String>>,
position: Option<vectorcraft_doc::CharPosition>,
small_caps: Option<Option<f64>>,
char_align: Option<vectorcraft_doc::CharAlign>,
}
/// `features: ["dlig", "-liga", …]` → the canonical tag list (differences from the defaults).
@@ -163,6 +164,19 @@ pub(crate) fn features_param(p: &Value, cmd: &str) -> Result<Option<Vec<String>>
Ok(Some(vectorcraft_text::OtFeatures::default().with_tags(tags).to_tags()))
}
/// `charAlign: "romanBaseline"|"emBoxTop"|"emBoxCenter"|"emBoxBottom"` (Character Alignment).
pub(crate) fn char_align_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::CharAlign>> {
use vectorcraft_doc::CharAlign;
let Some(v) = p.get("charAlign").filter(|v| !v.is_null()) else { return Ok(None) };
Ok(Some(match v.as_str() {
Some("romanBaseline") => CharAlign::RomanBaseline,
Some("emBoxTop") => CharAlign::EmBoxTop,
Some("emBoxCenter") => CharAlign::EmBoxCenter,
Some("emBoxBottom") => CharAlign::EmBoxBottom,
_ => return Err(bad(cmd, "`charAlign` must be \"romanBaseline\", \"emBoxTop\", \"emBoxCenter\" or \"emBoxBottom\"")),
}))
}
fn paint_param(p: &Value, k: &str, cmd: &str) -> Result<Option<Paint>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
@@ -213,6 +227,7 @@ impl CharChange {
features: features_param(p, cmd)?,
position,
small_caps,
char_align: char_align_param(p, cmd)?,
};
if c.size.is_some_and(|v| v <= 0.0) {
return Err(bad(cmd, "size must be positive"));
@@ -240,6 +255,7 @@ impl CharChange {
&& self.features.is_none()
&& self.position.is_none()
&& self.small_caps.is_none()
&& self.char_align.is_none()
}
pub(crate) fn apply(&self, st: &mut CharStyle) {
@@ -310,6 +326,9 @@ impl CharChange {
if let Some(v) = self.small_caps {
st.small_caps = v;
}
if let Some(v) = self.char_align {
st.char_align = v;
}
}
}
+26
View File
@@ -433,6 +433,32 @@ mod area_tests {
assert!(serde_json::to_value(&text(&s).para).unwrap().get("leading_model").is_none());
}
#[test]
fn character_alignment_is_a_character_attribute_saved_only_when_set() {
use vectorcraft_doc::CharAlign;
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "雅楽"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
assert_eq!(runs(&s)[0].style.char_align, CharAlign::RomanBaseline);
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("charAlign").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
assert!(s.execute("text.setFormat", &json!({"charAlign": "middle"})).is_err());
s.execute("text.setFormat", &json!({"charAlign": "emBoxCenter"})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.char_align == CharAlign::EmBoxCenter));
assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["charAlign"], "emBoxCenter");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(runs(&s)[0].style.char_align, CharAlign::RomanBaseline);
// Characters selected with the Type tool: only the range takes it (雅 is 3 bytes).
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "charAlign": "top"})).is_err());
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "charAlign": "emBoxTop"})).unwrap();
let aligns: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.char_align)).collect();
assert_eq!(aligns, [("雅".to_string(), CharAlign::RomanBaseline), ("楽".to_string(), CharAlign::EmBoxTop)]);
}
#[test]
fn new_type_is_composed_with_line_end_half_width_punctuation() {
use vectorcraft_doc::Mojikumi;
+25 -2
View File
@@ -12,8 +12,23 @@ fn rect_json(r: Option<vectorcraft_geom::Rect>) -> Value {
}
}
/// Compact tree summary of a node (for `document.inspect`).
/// How much of the subtree a node summary carries.
#[derive(Clone, Copy, Default)]
pub struct SummaryOpts {
/// Child levels to include (`None`: the whole subtree). `0` is the node alone.
pub depth: Option<u64>,
/// Children shown per node (`None`: all, top of the stack first). A level that shows
/// fewer children than it has reports `childCount`, so truncation is never silent.
pub child_limit: Option<u64>,
}
/// Compact tree summary of a node (for `document.inspect`): the whole subtree.
pub fn node_summary(n: &Node) -> Value {
node_summary_opts(n, SummaryOpts::default())
}
/// The same summary with [`SummaryOpts`] applied.
pub fn node_summary_opts(n: &Node, opts: SummaryOpts) -> Value {
let mut v = json!({
"id": n.id.0,
"name": n.display_name(),
@@ -69,7 +84,15 @@ pub fn node_summary(n: &Node) -> Value {
_ => {}
}
if let Some(ch) = n.children() {
v["children"] = Value::Array(ch.iter().rev().map(|c| node_summary(c)).collect());
let total = ch.len();
let take_n = opts.child_limit.map_or(total, |l| l.min(total as u64) as usize);
if opts.depth.is_none_or(|d| d > 0) {
let next = SummaryOpts { depth: opts.depth.map(|d| d.saturating_sub(1)), child_limit: opts.child_limit };
v["children"] = Value::Array(ch.iter().rev().take(take_n).map(|c| node_summary_opts(c, next)).collect());
}
if take_n < total || v.get("children").is_none() {
v["childCount"] = json!(total);
}
}
v
}
+50
View File
@@ -364,6 +364,56 @@ fn document_node_summary_matches_inspect() {
assert!(s.execute("document.node", &json!({"id": 999999, "summary": true})).is_err());
}
/// `depth` and `childLimit` slice a summary read; a level that shows fewer children
/// than it has reports `childCount`, and invalid values are rejected, not reinterpreted.
#[test]
fn document_node_summary_slices_with_depth_and_limit() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
s.execute("select.all", &json!({})).unwrap();
let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
rect(&mut s, 40.0, 0.0, 10.0, 10.0);
s.execute("select.all", &json!({})).unwrap();
let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let mut read = |p: Value| s.execute("document.node", &p).unwrap();
let g = read(json!({"id": outer, "summary": true}));
assert_eq!(g["children"].as_array().map(Vec::len), Some(2));
assert!(g.get("childCount").is_none(), "nothing truncated: {g}");
// Limits beyond the tree are the whole tree, byte for byte.
assert_eq!(read(json!({"id": outer, "summary": true, "depth": u64::MAX, "childLimit": u64::MAX})), g);
let one = read(json!({"id": outer, "summary": true, "childLimit": 1}));
assert_eq!(one["children"].as_array().map(Vec::len), Some(1));
assert_eq!(one["childCount"], 2);
let flat = read(json!({"id": outer, "summary": true, "depth": 0}));
assert!(flat.get("children").is_none(), "{flat}");
assert_eq!(flat["childCount"], 2);
// Limits compose per level: the outer children show; the inner group's own
// children don't, and it says so.
let shallow = read(json!({"id": outer, "summary": true, "depth": 1}));
let kids = shallow["children"].as_array().unwrap();
assert_eq!(kids.len(), 2);
assert!(shallow.get("childCount").is_none(), "{shallow}");
let nested = kids.iter().find(|n| n["id"] == inner).unwrap();
assert!(nested.get("children").is_none(), "{nested}");
assert_eq!(nested["childCount"], 2);
for bad in [
json!({"id": outer, "summary": true, "depth": -1}),
json!({"id": outer, "summary": true, "depth": 1.5}),
json!({"id": outer, "summary": true, "childLimit": "many"}),
// A slice of the full object JSON would silently be the whole subtree.
json!({"id": outer, "depth": 0}),
json!({"id": outer, "summary": false, "childLimit": 1}),
] {
assert!(s.execute("document.node", &bad).is_err(), "{bad}");
}
}
/// Type reports the paint its characters show, and its own object-level paint apart from it.
#[test]
fn inspect_reports_the_paint_of_types_characters() {
+24 -1
View File
@@ -7,7 +7,7 @@ use vectorcraft_geom::Point;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use super::*;
use crate::cmd::clipboard::{PDF, PNG, SVG, TEXT};
use crate::cmd::clipboard::{BITMAP, FILE_HEAD, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour};
fn session() -> Session {
let mut s = Session::new();
@@ -118,6 +118,29 @@ fn import_image_then_paste_gives_an_image() {
assert!(s.execute("clipboard.importImage", &json!({"dataBase64": "!!"})).is_err());
}
#[test]
fn copied_files_paste_by_their_content() {
let mut s = session();
copy_red_square(&mut s);
let png = decode(&run(&mut s, "clipboard.exportPng", json!({})));
let pdf = decode(&run(&mut s, "clipboard.exportPdf", json!({})));
let mut jpeg = vec![];
image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"4\" height=\"4\"/></svg>";
let of = |name: &str, bytes: &[u8]| file_flavour(name, &bytes[..bytes.len().min(FILE_HEAD)], &PASTE_ORDER);
assert_eq!(of("red.png", &png), Some(PNG));
// The content tells, whatever the name says; bitmaps keep their own type.
assert_eq!(of("photo.txt", &jpeg), Some("image/jpeg"));
assert_eq!(of("art.svg", svg), Some(SVG));
assert_eq!(of("doc.pdf", &pdf), Some(PDF));
// Files that aren't art paste as nothing (not as their path).
assert_eq!(of("notes.txt", b"hello"), None);
assert_eq!(of("archive.zip", b"PK\x03\x04"), None);
// Only what was asked for.
assert_eq!(file_flavour("red.png", &png, &[TEXT, SVG]), None);
assert_eq!(file_flavour("art.svg", svg, &[BITMAP]), None);
}
#[test]
fn import_text_then_paste_gives_point_text() {
let mut s = session();
+1 -1
View File
@@ -44,7 +44,7 @@ pub static TEMPLATES: &[Template] = &[
uri: "vectorcraft://object/{id}",
name: "object",
title: "One layer or object",
description: "The layer or object with this id, with its children, bounds and paint (document.node {summary: true})",
description: "The layer or object with this id, with its children, bounds and paint (document.node {summary: true}). Large containers can be sliced with run_command document.node {id, summary, depth, childLimit}: truncated levels report childCount",
mime: "application/json",
live: Live::Objects,
},
+24 -1
View File
@@ -320,6 +320,26 @@ fn space_japanese_and_latin(sg: &mut [SGlyph]) -> Vec<f64> {
added
}
/// The size of `g`'s em, in points.
fn glyph_em(g: &SGlyph) -> f64 {
g.face.units_per_em() * g.sy
}
/// How far up (line space) Character Alignment `a` moves glyph `g` on a line whose largest em is
/// `line_em`: the glyph's em box top, centre or bottom onto the line's (the em box running from
/// its centre less half an em to its centre plus half an em above the baseline). Nothing on the
/// Roman baseline, or for the line's largest characters.
fn align_shift(g: &SGlyph, a: vectorcraft_doc::CharAlign, line_em: f64) -> f64 {
use vectorcraft_doc::CharAlign;
let k = match a {
CharAlign::RomanBaseline => return 0.0,
CharAlign::EmBoxTop => 0.5,
CharAlign::EmBoxCenter => 0.0,
CharAlign::EmBoxBottom => -0.5,
};
(g.face.ideographic_centre() + k) * (line_em - glyph_em(g)).max(0.0)
}
/// The length an upright glyph takes down the column before tracking and justification: its
/// vertical advance (the font's vertical metrics), else its advance, at least one em.
fn upright_cell(g: &SGlyph) -> f64 {
@@ -1056,6 +1076,8 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
};
let li = cx.out.lines.len();
let glyph_start = cx.out.glyphs.len();
// Character Alignment lines smaller characters up with the line's largest em box.
let line_em = sg.get(i..end).map_or(0.0, |line| line.iter().map(glyph_em).fold(0.0, f64::max));
let mut x_end = start_x;
// Tab stops are measured from the frame's left edge (point type: the origin).
let tab_origin = if regions.is_some() { x0 } else { 0.0 };
@@ -1088,7 +1110,8 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
adv += per_gap;
}
}
cx.emit(g, Affine::translate((x, baseline)), Point::new(x, baseline), 0.0, adv, li);
let y = baseline - align_shift(g, cx.style_at(g.byte).char_align, line_em);
cx.emit(g, Affine::translate((x, y)), Point::new(x, y), 0.0, adv, li);
x += adv;
if j < trimmed {
x_end = x;
+28
View File
@@ -557,3 +557,31 @@ fn em_box_top_leading_hangs_lines_from_the_line_above() {
em.lines[1].baseline - em.lines[0].baseline
);
}
/// Character Alignment: a 20 pt character next to a 40 pt one lines its em box top, centre or
/// bottom up with the big one's (the em box from 0.12 em below the baseline to 0.88 em above it,
/// in fonts without vertical metrics), or stays on the baseline; in vertical type the same across
/// the column (top → right).
#[test]
fn character_alignment_lines_small_characters_up_with_the_largest_em_box() {
use vectorcraft_doc::{CharAlign, TextRun};
for vertical_type in [false, true] {
let place = |a: CharAlign| {
let mut t = point("", style(40.0));
t.vertical = vertical_type;
t.runs = vec![
TextRun { text: "大".into(), style: style(40.0) },
TextRun { text: "小".into(), style: CharStyle { char_align: a, ..style(20.0) } },
];
let l = layout(db(), &t);
// How far the small character's origin sits above the big one's (to the right, vertical).
let (big, small) = (l.glyphs[0].origin, l.glyphs[1].origin);
if vertical_type { small.x - big.x } else { big.y - small.y }
};
let near = |a: f64, b: f64| (a - b).abs() < 0.01;
assert!(near(place(CharAlign::RomanBaseline), 0.0), "vertical {vertical_type}");
assert!(near(place(CharAlign::EmBoxTop), 0.88 * 20.0), "top: {}", place(CharAlign::EmBoxTop));
assert!(near(place(CharAlign::EmBoxCenter), 0.38 * 20.0), "centre: {}", place(CharAlign::EmBoxCenter));
assert!(near(place(CharAlign::EmBoxBottom), -0.12 * 20.0), "bottom: {}", place(CharAlign::EmBoxBottom));
}
}
@@ -41,13 +41,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
};
form::slider(ui, d, "steps", tl!("Steps:"), 1.0..=max, "", &ramp);
form::slider(ui, d, "amount", tl!("Variation:"), 0.0..=100.0, "%", &ramp);
ui.horizontal(|ui| {
ui.add_space(form::SLIDER_LABEL + ui.spacing().item_spacing.x);
let (r, _) = ui.allocate_exact_size(vec2(form::SLIDER_WIDTH, 14.0), Sense::hover());
let font = egui::FontId::proportional(11.0);
ui.painter().text(r.left_center(), egui::Align2::LEFT_CENTER, tl!("Less"), font.clone(), t.text_dim);
ui.painter().text(r.right_center(), egui::Align2::RIGHT_CENTER, tl!("More"), font, t.text_dim);
});
form::slider_ends(ui, form::SLIDER_LABEL, (tl!("Less"), tl!("More")));
ui.add_space(10.0);
// Preview: the base colour's row of variations.
let o = options(app, d);
+13
View File
@@ -329,6 +329,19 @@ pub(super) fn slider_w(
}
}
/// The words at the two ends of a slider's rail (Less … More), under a slider whose label column
/// is `label_w` wide.
pub(super) fn slider_ends(ui: &mut egui::Ui, label_w: f32, (left, right): (&str, &str)) {
let t = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.add_space(label_w + ui.spacing().item_spacing.x);
let (r, _) = ui.allocate_exact_size(egui::vec2(SLIDER_WIDTH, 14.0), egui::Sense::hover());
let font = egui::FontId::proportional(11.0);
ui.painter().text(r.left_center(), egui::Align2::LEFT_CENTER, left, font.clone(), t.text_dim);
ui.painter().text(r.right_center(), egui::Align2::RIGHT_CENTER, right, font, t.text_dim);
});
}
/// The field where [`preview`] keeps the parameters it last previewed.
pub(super) const PREVIEWED: &str = "__previewed";
+217
View File
@@ -0,0 +1,217 @@
//! Tool Options of the freehand tools (double-click Pencil, Paintbrush, Smooth, Blob Brush or
//! Eraser): the options each tool keeps, which last across tool switches and are saved with the
//! preferences. OK sets them with `tool.setOption {tool, values}`.
//!
//! Fields: `tool`; `fidelity` (points; Pencil, Paintbrush and Smooth), `fill` (Pencil and
//! Paintbrush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and
//! Paintbrush) and `size` (points; Blob Brush and Eraser).
use serde_json::{Map, Value, json};
use super::document_setup::check;
use super::{DialogSpec, form, run_and_close};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of the freehand tools' Tool Options.
pub const KIND: &str = "freehandOptions";
pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 420.0, ..DialogSpec::FORM };
/// The tools the dialog serves.
pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"];
/// The options the dialog edits, in the order it shows them (a tool has those it reports).
const KEYS: [&str; 5] = ["fidelity", "size", "fill", "closeWithin", "editWithin"];
/// Width of the label column: wide enough for the tolerances' labels when there are any.
fn label_w(d: &Dialog) -> f32 {
if d.fields.contains_key("closeWithin") { 230.0 } else { 90.0 }
}
/// The range of the Fidelity slider (points); the field takes what the tool allows.
const FIDELITY: (f64, f64) = (0.5, 20.0);
fn heading(d: &Dialog) -> String {
let label = vectorcraft_tools::tool_info(&d.str("tool")).map_or("", |t| t.label);
crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))])
}
/// Open the options of freehand tool `tool` with their current values.
pub fn open(app: &mut VectorcraftApp, tool: &str) -> Result<Value, String> {
if !TOOLS.contains(&tool) {
return Err(format!("`{tool}` isn't a freehand tool"));
}
let o = app.session.tool_options_of(tool);
let mut fields: Map<String, Value> = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect();
fields.insert("tool".into(), json!(tool));
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
Ok(json!({ "dialog": KIND }))
}
/// A row with a number field for `d.fields[key]` (`suffix` is its unit), kept within `range`.
fn number(ui: &mut egui::Ui, d: &mut Dialog, (key, label): (&str, &str), suffix: &str, decimals: usize, range: (f64, f64)) {
let label_w = label_w(d);
let v = d.f64(key, 0.0);
widgets::label_row(ui, label, label_w, |ui| {
if let Some(x) = widgets::plain_field(ui, ("freehand-field", key), v, suffix, decimals, 72.0) {
d.fields.insert(key.into(), json!(x.clamp(range.0, range.1)));
}
});
}
/// The Fidelity row: a slider over [`FIDELITY`] in tenths, and a field.
fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) {
let label_w = label_w(d);
let t = Tokens::get(ui.ctx());
let v = d.f64("fidelity", 1.5);
let (min, max) = FIDELITY;
let mut new = None;
widgets::label_row(ui, tl!("Fidelity:"), label_w, |ui| {
let at = ((v.clamp(min, max) - min) / (max - min)) as f32;
if let (Some(x), _) = widgets::color_slider(ui, "freehand-fidelity", at, form::SLIDER_WIDTH, &|_| t.input_border) {
new = Some(((min + x as f64 * (max - min)) * 10.0).round() / 10.0);
}
if let Some(x) = widgets::plain_field(ui, "freehand-fidelity-field", v, "pt", 1, 64.0) {
new = Some(x.clamp(0.05, 100.0));
}
});
if let Some(n) = new.filter(|n| *n != v) {
d.fields.insert("fidelity".into(), json!(n));
}
form::slider_ends(ui, label_w, (tl!("Accurate"), tl!("Smooth")));
ui.label(
egui::RichText::new(tl!("A lower value follows the stroke closely; a higher one gives fewer points and smoother curves."))
.size(11.5)
.color(t.text_dim),
);
}
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
if d.fields.contains_key("fidelity") {
fidelity(ui, d);
ui.add_space(10.0);
}
if d.fields.contains_key("size") {
number(ui, d, ("size", tl!("Size:")), "pt", 1, (0.1, 1000.0));
}
if d.fields.contains_key("fill") {
check(ui, d, "fill", tl!("Fill new strokes"));
ui.add_space(6.0);
}
if d.fields.contains_key("closeWithin") {
number(ui, d, ("closeWithin", tl!("Close paths when ends are within:")), "px", 0, (0.0, 100.0));
}
if d.fields.contains_key("editWithin") {
number(ui, d, ("editWithin", tl!("Edit selected paths within:")), "px", 0, (0.0, 100.0));
}
false
}
/// OK: set the tool's options.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values }))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app
}
/// The labels the open dialog paints.
fn painted(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
#[test]
fn each_tool_shows_its_options_and_ok_sets_them() {
let mut app = app();
// Pencil: Fidelity, fill, the two tolerances; no Size.
app.run("tool.options", json!({"tool": "pencil"})).unwrap();
let text = painted(&mut app);
for label in [
"Pencil Tool Options",
"Fidelity:",
"Accurate",
"Smooth",
"Fill new strokes",
"Close paths when ends are within:",
"Edit selected paths within:",
] {
assert!(text.contains(label), "{label} in {text}");
}
assert!(!text.contains("Size:"), "{text}");
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!((d.f64("fidelity", 0.0), d.bool("fill"), d.f64("closeWithin", 0.0), d.f64("editWithin", 0.0)), (1.5, false, 15.0, 12.0));
for (k, v) in [("fidelity", json!(6.5)), ("fill", json!(true)), ("closeWithin", json!(0)), ("editWithin", json!(20))] {
d.fields.insert(k.into(), v);
}
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let o = app.session.tool_options_of("pencil");
assert_eq!(
(o["fidelity"].as_f64(), o["fill"].as_bool(), o["closeWithin"].as_f64(), o["editWithin"].as_f64()),
(Some(6.5), Some(true), Some(0.0), Some(20.0))
);
// The Paintbrush keeps its own: the Pencil's change left it alone.
app.run("tool.options", json!({"tool": "paintbrush"})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.f64("fidelity", 0.0), d.bool("fill")), (1.5, false));
assert!(painted(&mut app).contains("Paintbrush Tool Options"));
// Smooth has Fidelity only, the Blob Brush and the Eraser Size only.
app.run("tool.options", json!({"tool": "smooth"})).unwrap();
let text = painted(&mut app);
assert!(text.contains("Smooth Tool Options") && text.contains("Fidelity:"), "{text}");
assert!(!text.contains("Fill new strokes") && !text.contains("Size:"), "{text}");
for tool in ["blobBrush", "eraser"] {
app.run("tool.options", json!({"tool": tool})).unwrap();
let text = painted(&mut app);
assert!(text.contains("Size:") && !text.contains("Fidelity:"), "{tool}: {text}");
app.ui.dialog.as_mut().unwrap().fields.insert("size".into(), json!(24));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.session.tool_options_of(tool)["size"].as_f64(), Some(24.0), "{tool}");
}
}
#[test]
fn a_new_fidelity_changes_what_the_pencil_draws() {
let mut app = app();
// The anchors of a wave drawn around height `y0`, with nothing selected (a stroke starting
// at the end of a selected path would continue it).
let anchors = |app: &mut VectorcraftApp, y0: f64| {
app.run("select.set", json!({"ids": []})).unwrap();
app.select_tool("pencil");
let view = app.view_info();
let pts: Vec<_> = (0..=40).map(|i| (20.0 + i as f64 * 8.0, y0 + 30.0 * (i as f64 * 0.25).sin())).collect();
let pointer = |kind, (x, y)| vectorcraft_tools::PointerEvent::new(kind, x, y);
crate::canvas::dispatch(app, &pointer(vectorcraft_tools::PointerKind::Down, pts[0]), view);
for p in &pts[1..] {
crate::canvas::dispatch(app, &pointer(vectorcraft_tools::PointerKind::Drag, *p), view);
}
crate::canvas::dispatch(app, &pointer(vectorcraft_tools::PointerKind::Up, pts[40]), view);
let doc = &app.session.doc().unwrap().doc;
doc.layers[0].children().unwrap().last().unwrap().path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>())
};
let precise = anchors(&mut app, 100.0);
app.run("tool.options", json!({"tool": "pencil"})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(12));
super::super::confirm(&mut app).unwrap();
let smooth = anchors(&mut app, 200.0);
assert!(smooth < precise, "{smooth} anchors at fidelity 12, {precise} at the default");
}
#[test]
fn the_other_tools_have_no_freehand_options() {
let mut app = app();
assert!(open(&mut app, "pen").is_err());
assert!(app.ui.dialog.is_none());
}
}
+2
View File
@@ -31,6 +31,7 @@ pub mod file_info;
pub mod flatten;
pub mod flattener_presets;
mod form;
pub mod freehand;
mod gradient_stop;
pub mod graphic_style_options;
pub mod halftone;
@@ -268,6 +269,7 @@ registry! {
PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC,
Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC,
LiquifyOptions: [liquify::KIND] => liquify::SPEC,
FreehandOptions: [freehand::KIND] => freehand::SPEC,
PerspectiveGridPresets: [perspective_presets::KIND] => perspective_presets::SPEC,
PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC,
BlendOptions: [blend_options::KIND] => blend_options::SPEC,
+6 -3
View File
@@ -4,10 +4,10 @@
use egui::Ui;
use serde_json::{Value, json};
use crate::VectorcraftApp;
use crate::state::Dialog;
use crate::theme::{self, Tokens};
use crate::widgets;
use crate::{VectorcraftApp, font_menu};
/// Open the dialog.
pub fn open(app: &mut VectorcraftApp) {
@@ -34,6 +34,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(mut d) = app.ui.dialog.clone() else { return };
let t = Tokens::get(ctx);
let list = fonts(app);
let sample = font_menu::sample_text(app);
let mut close = false;
let mut act: Option<&str> = None;
egui::Area::new(egui::Id::new("modal-dim")).order(egui::Order::Middle).fixed_pos(egui::pos2(0.0, 0.0)).show(ctx, |ui| {
@@ -71,9 +72,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
widgets::subheader(ui, tl!("Replace With Font"));
let fam = d.str("family");
ui.horizontal(|ui| {
if let Some(f) = widgets::font_dropdown(ui, "ff-family", &fam, 220.0) {
// Picks the font only: nothing is previewed on the document.
let pick = font_menu::font_menu(ui, "ff-family", &fam, 220.0, sample.as_deref(), font_menu::MenuLook::of(app));
if let Some((f, style)) = font_menu::picked(app, pick) {
d.fields.insert("family".into(), json!(f));
d.fields.insert("style".into(), json!(""));
d.fields.insert("style".into(), json!(style.unwrap_or_default()));
}
let styles = vectorcraft_text::FontDb::global().styles(&d.str("family"));
// "(closest)" is ours; the font's style names are shown as they are.
+35 -16
View File
@@ -1,10 +1,12 @@
//! The font family menu of the Character and Properties panels: a search field over every family
//! available, each row the family's name and a sample of the selected text set in it. The row
//! under the pointer or reached with ↑/↓ previews its font on the selected text (one live
//! interaction, nothing in the history); a click or Enter applies it as one step, Escape or
//! closing the menu puts the text back. A star marks a favourite family, and the ★ filter lists
//! only those. Preferences › Type › Enable in-menu font previews and Font Preview Size turn the
//! samples off or size the rows.
//! The font family menu of the Character, Properties and Glyphs panels and Find Font's Replace
//! With: a search field over every family available, each row the family's name and a sample of
//! the selected text set in it. In the Character and Properties panels the row under the pointer
//! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in
//! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text
//! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the
//! document. A star marks a favourite family, and the ★ filter lists only those. Preferences ›
//! Type › Enable in-menu font previews and Font Preview Size turn the samples off or size the
//! rows.
use std::collections::HashMap;
use std::sync::Arc;
@@ -637,15 +639,7 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic
app.sync_views();
}
}
FontPick::Favorite(f) => {
let favs = &mut app.ui.favorite_fonts;
match favs.iter().position(|x| x.eq_ignore_ascii_case(&f)) {
Some(i) => {
favs.remove(i);
}
None => favs.push(f),
}
}
FontPick::Favorite(f) => toggle_favorite(app, f),
FontPick::Chosen(f, style) => {
if previewing {
app.session.cancel_interaction().ok();
@@ -658,6 +652,31 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic
}
}
/// Star `family`, or take its star off (any case).
fn toggle_favorite(app: &mut VectorcraftApp, family: String) {
let favs = &mut app.ui.favorite_fonts;
match favs.iter().position(|x| x.eq_ignore_ascii_case(&family)) {
Some(i) => {
favs.remove(i);
}
None => favs.push(family),
}
}
/// For a font menu that only picks a font and never changes the document (Find Font's Replace
/// With, the Glyphs panel): the family (and style) chosen, if any. A star is toggled here; the
/// highlighted row is not previewed.
pub(crate) fn picked(app: &mut VectorcraftApp, pick: Option<FontPick>) -> Option<(String, Option<String>)> {
match pick? {
FontPick::Chosen(f, style) => Some((f, style)),
FontPick::Favorite(f) => {
toggle_favorite(app, f);
None
}
FontPick::Preview(..) | FontPick::EndPreview => None,
}
}
/// The command that sets font `family` (and `style`, else the closest the family has) on what the
/// menus act on.
fn font_command(app: &VectorcraftApp, family: &str, style: Option<&str>) -> (&'static str, serde_json::Value) {
+10
View File
@@ -36,11 +36,13 @@
[Default] is protected: New… starts an editable copy. [Predeterminado] está protegido: Nuevo… crea una copia editable.
[Unnamed] [Sin nombre]
A File… Un archivo…
A lower value follows the stroke closely; a higher one gives fewer points and smoother curves. Un valor menor sigue el trazo de cerca; uno mayor da menos puntos y curvas más suaves.
A new preset starting from the selected one Un preajuste nuevo a partir del seleccionado
A saved copy of the selected preset Una copia guardada del preajuste seleccionado
About VectorCraft Acerca de VectorCraft
above arriba
Absolute Position Posición absoluta
Accurate Preciso
Abutting Contiguo
Action {n} Acción {n}
Actions Acciones
@@ -297,6 +299,7 @@
Changing these settings changes how raster effects look when exported, flattened or expanded. Cambiar estos ajustes modifica el aspecto de los efectos ráster al exportar, acoplar o expandir.
Channel Canal
Character Carácter
Character Alignment Alineación de caracteres
Character / Paragraph Carácter / Párrafo
Character Rotation Rotación de caracteres
Character Set: Juego de caracteres:
@@ -347,6 +350,7 @@
Close All Cerrar todo
Close Library Cerrar biblioteca
Close Path Cerrar trazado
Close paths when ends are within: Cerrar trazados cuando los extremos estén a menos de:
Cmd Cmd
CMYK CMYK
CMYK Color Color CMYK
@@ -726,6 +730,7 @@
Edit Pattern Editar motivo
Edit PDF Preset Editar preajuste de PDF
Edit Print Preset Editar preajuste de impresión
Edit selected paths within: Editar trazados seleccionados a menos de:
Edit Selection Editar selección
Edit Selection… Editar selección…
Edit Symbol Editar símbolo
@@ -748,6 +753,9 @@
Ellipse Tool Herramienta Elipse
Ellipse… Elipse…
Ellipsis Puntos suspensivos
Em Box Bottom/Left Abajo/izquierda del cuadro eme
Em Box Center Centro del cuadro eme
Em Box Top/Right Arriba/derecha del cuadro eme
Em Dash Raya
Em Space Espacio eme
Embed Incrustar
@@ -892,6 +900,7 @@
Fill & Stroke Relleno y trazo
Fill (X), double-click for the Color Picker Relleno (X), doble clic para el selector de color
Fill and Stroke Relleno y trazo
Fill new strokes Rellenar trazos nuevos
Fill Color Color de relleno
Fill New Type Objects With Placeholder Text Rellenar nuevos objetos de texto con texto de muestra
Fill Rule Regla de relleno
@@ -2076,6 +2085,7 @@
Right-to-Left Paragraph Direction Dirección de párrafo de derecha a izquierda
Right: Derecha:
Rise… Ascenso…
Roman Baseline Línea de base latina
Roman Hanging Punctuation Puntuación colgante romana
Rotate Rotar
Rotate 90° CW Rotar 90° en sentido horario
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -12,7 +12,11 @@
All Scripts すべての文字
Any Kind すべての種類
Bottom-to-Bottom Leading 欧文ベースライン基準の行送り
Character Alignment 文字揃え
Decorative 装飾
Em Box Bottom/Left 仮想ボディの下 / 左
Em Box Center 仮想ボディの中央
Em Box Top/Right 仮想ボディの上 / 右
Favorites お気に入り
Japanese 日本語
Join Our Discord Discord に参加
@@ -20,6 +24,7 @@
Mojikumi Set 文字組み
Latin 欧文
Monospaced 等幅
Roman Baseline 欧文ベースライン
Rounded 丸ゴシック
Sans Serif / Gothic ゴシック・サンセリフ
Script / Brush 筆書体・スクリプト
@@ -660,9 +665,11 @@
< 1 sec 1 秒未満
<Opacity Mask> <不透明マスク>
A File… ファイル…
A lower value follows the stroke closely; a higher one gives fewer points and smoother curves. 値を小さくするとストロークに忠実に、大きくするとポイントが少なく滑らかな曲線になります。
A new preset starting from the selected one 選択したプリセットをもとにした新しいプリセット
A saved copy of the selected preset 選択したプリセットの保存済みの複製
Absolute Position 絶対位置
Accurate 精細
Abutting 隣接
Activate Document ドキュメントをアクティブにする
Active Perspective Plane アクティブな遠近面
@@ -869,6 +876,7 @@
Clipboard as Text クリップボードをテキストとして取得
Close Library ライブラリを閉じる
Close Path パスを閉じる
Close paths when ends are within: 端点が次の距離以内のとき、パスを閉じる:
Collate 部単位で印刷
Collect in New Layer 新規レイヤーに集める
Color Burn 焼き込みカラー
@@ -1123,6 +1131,7 @@
Edit Print Preset プリントプリセットを編集
Edit Symbol シンボルを編集
Edit Theme テーマを編集
Edit selected paths within: 選択したパスを次の距離以内で編集:
Edit or Apply Color Group カラーグループを編集または適用
Edit or Apply Color Group… カラーグループを編集または適用…
Edit or Apply Colors カラーを編集/適用
@@ -1241,6 +1250,7 @@
Fill New Type Objects With Placeholder Text 新規テキストオブジェクトをダミーテキストで埋める
Fill Rule 塗りのルール
Fill and Stroke 塗りと線
Fill new strokes 新しいストロークに塗りを適用
Fill: 塗り:
Find 検索
Find Font フォントを検索
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -99,10 +99,12 @@
< 1 sec < 1 segundo
<Opacity Mask> <máscara de opacidade>
A File… Um arquivo…
A lower value follows the stroke closely; a higher one gives fewer points and smoother curves. Um valor menor segue o traço de perto; um valor maior gera menos pontos e curvas mais suaves.
A new preset starting from the selected one Um novo predefinido a partir do selecionado
A saved copy of the selected preset Uma cópia salva do predefinido selecionado
About VectorCraft Sobre o VectorCraft
Absolute Position Posição Absoluta
Accurate Preciso
Abutting Contíguo
Actions Ações
Activate Document Ativar Documento
@@ -334,6 +336,7 @@
Changing these settings changes how raster effects look when exported, flattened or expanded. Alterar estas configurações muda a aparência dos efeitos de raster ao exportar, achatar ou expandir.
Channel Canal
Character Caractere
Character Alignment Alinhamento de Caracteres
Character / Paragraph Caractere / Parágrafo
Character Rotation Rotação de Caractere
Character Set: Conjunto de Caracteres:
@@ -381,6 +384,7 @@
Close All Fechar Tudo
Close Library Fechar Biblioteca
Close Path Fechar Caminho
Close paths when ends are within: Fechar caminhos quando as extremidades estiverem a menos de:
Collapse Panels to Icons Recolher Painéis em Ícones
Collapse to Icons Recolher em Ícones
Collate Agrupar
@@ -695,6 +699,7 @@
Edit PDF Preset Editar Predefinido de PDF
Edit Pattern Editar Padrão
Edit Print Preset Editar Predefinido de Impressão
Edit selected paths within: Editar caminhos selecionados a menos de:
Edit Selection… Editar Seleção…
Edit Symbol Editar Símbolo
Edit Text Editar Texto
@@ -717,6 +722,9 @@
Ellipse Tool Ferramenta Elipse
Ellipse… Elipse…
Ellipsis Reticências
Em Box Bottom/Left Base/Esquerda da Caixa Eme
Em Box Center Centro da Caixa Eme
Em Box Top/Right Topo/Direita da Caixa Eme
Em Dash Travessão
Em Space Espaço Em
Embed Incorporar
@@ -848,6 +856,7 @@
Fill New Type Objects With Placeholder Text Preencher Novos Objetos de Texto com Texto de Placeholder
Fill Rule Regra de Preenchimento
Fill and Stroke Preenchimento e Traçado
Fill new strokes Preencher novos traçados
Fill with Placeholder Text Preencher com Texto de Placeholder
Fill: Preenchimento:
Find Localizar
@@ -1868,6 +1877,7 @@
Right Plane Plano Direito
Right: Direita:
Rise… Rise…
Roman Baseline Linha de Base Romana
Roman Hanging Punctuation Pontuação Pendurada Romana
Rotate Girar
Rotate Tool Ferramenta Girar
Can't render this file because it contains an unexpected character in line 6 and column 47.
+10
View File
@@ -40,11 +40,13 @@
[Default] is protected: New… starts an editable copy. [默认] 受保护:“新建…”会创建可编辑的副本。
[Unnamed] [未命名]
A File… 文件…
A lower value follows the stroke closely; a higher one gives fewer points and smoother curves. 数值较小时紧贴所绘线条,较大时锚点较少、曲线更平滑。
A new preset starting from the selected one 以所选预设为基础的新预设
A saved copy of the selected preset 所选预设的副本
About VectorCraft 关于 VectorCraft
above 以上
Absolute Position 绝对位置
Accurate 精确
Abutting 相邻
Action {n} 动作 {n}
Actions 动作
@@ -300,6 +302,7 @@
Changing these settings changes how raster effects look when exported, flattened or expanded. 更改这些设置会改变栅格效果在导出、拼合或扩展时的外观。
Channel 色版
Character 字符
Character Alignment 字符对齐
Character / Paragraph 字符/段落
Character Rotation 字符旋转
Character Set: 字符集:
@@ -350,6 +353,7 @@
Close All 全部关闭
Close Library 关闭库
Close Path 闭合路径
Close paths when ends are within: 端点相距在以下范围内时闭合路径:
Cmd Cmd
CMYK CMYK
CMYK Color CMYK 颜色
@@ -722,6 +726,7 @@
Edit Pattern 编辑图案
Edit PDF Preset 编辑 PDF 预设
Edit Print Preset 编辑打印预设
Edit selected paths within: 在以下范围内编辑所选路径:
Edit Selection… 编辑所选对象…
Edit Symbol 编辑符号
Edit Text 编辑文字
@@ -743,6 +748,9 @@
Ellipse Tool 椭圆工具
Ellipse… 椭圆形…
Ellipsis 删节号
Em Box Bottom/Left 全角字框下 / 左
Em Box Center 全角字框居中
Em Box Top/Right 全角字框上 / 右
Em Dash 长破折号
Em Space 全角空格
Embed 嵌入
@@ -886,6 +894,7 @@
Fill & Stroke 填色和描边
Fill (X), double-click for the Color Picker 填色 (X),双击打开拾色器
Fill and Stroke 填色和描边
Fill new strokes 为新描边应用填色
Fill Color 填色
Fill New Type Objects With Placeholder Text 用占位文本填充新文字对象
Fill Rule 填充规则
@@ -2048,6 +2057,7 @@
Right-Justified Tab 右对齐制表位
Right: 右:
Rise… 上升…
Roman Baseline 罗马基线
Roman Hanging Punctuation 西文悬挂标点
Rotate 旋转
Rotate 90° CW 顺时针旋转 90°
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10
View File
@@ -48,11 +48,13 @@
[Default] is protected: New… starts an editable copy. [預設] 受到保護:「新增…」會開始一份可編輯的複本。
[Unnamed] [未命名]
A File… 一個檔案…
A lower value follows the stroke closely; a higher one gives fewer points and smoother curves. 數值較小時會貼近筆畫,較大時則錨點較少、曲線較平滑。
A new preset starting from the selected one 以所選預設集為基礎建立新預設集
A saved copy of the selected preset 所選預設集的已儲存拷貝
About VectorCraft 關於 VectorCraft
above 以上
Absolute Position 絕對位置
Accurate 精確
Abutting 相鄰
Action {n} 動作 {n}
Actions 動作
@@ -312,6 +314,7 @@
Channel 色版
Character 字元
Character / Paragraph 字元/段落
Character Alignment 字元對齊
Character Rotation 字元旋轉
Character Set: 字元集:
Character Style 字元樣式
@@ -361,6 +364,7 @@
Close All 全部關閉
Close Library 關閉資料庫
Close Path 封閉路徑
Close paths when ends are within: 端點相距在以下範圍內時封閉路徑:
Cmd Cmd
CMYK CMYK
CMYK Color CMYK 色彩
@@ -740,6 +744,7 @@
Edit Pattern 編輯圖樣
Edit PDF Preset 編輯 PDF 預設集
Edit Print Preset 編輯列印預設集
Edit selected paths within: 在以下範圍內編輯選取的路徑:
Edit Selection 編輯選取範圍
Edit Selection… 編輯選取範圍…
Edit Symbol 編輯符號
@@ -762,6 +767,9 @@
Ellipse Tool 橢圓工具
Ellipse… 橢圓形…
Ellipsis 刪節號
Em Box Bottom/Left 全形字框下 / 左
Em Box Center 全形字框中央
Em Box Top/Right 全形字框上 / 右
Em Dash 長破折號
Em Space 全形空格
Embed 嵌入
@@ -909,6 +917,7 @@
Fill (X), double-click for the Color Picker 填色 (X),按兩下開啟檢色器
Fill and Stroke 填色與筆畫
Fill Color 填色顏色
Fill new strokes 為新筆畫套用填色
Fill New Type Objects With Placeholder Text 以預留位置文字填滿新文字物件
Fill Rule 填色規則
Fill with Placeholder Text 以預留位置文字填滿
@@ -2095,6 +2104,7 @@
Right-to-Left Paragraph Direction 從右至左段落方向
Right: 右:
Rise… 上升…
Roman Baseline 羅馬基線
Roman Hanging Punctuation 羅馬懸掛標點
Rotate 旋轉
Rotate 90° CW 順時針旋轉 90°
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1 -1
View File
@@ -276,7 +276,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient → the Gradient panel (window.panel), eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values})",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient → the Gradient panel (window.panel), eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, closeWithin and editWithin (px, 0 is off), size (pt); OK runs tool.setOption {tool, values})",
),
(
"ui.colorGuideOptions",
+42
View File
@@ -395,6 +395,28 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
menu_item(ui, tl!(l), false, false);
}
ui.separator();
// Character Alignment: where characters smaller than the largest on their line line up, with
// the East Asian options.
if app.session.prefs.show_east_asian_options {
let align = s.as_ref().map(|s| s.char_align);
ui.add_enabled_ui(has, |ui| {
// Indented like the items beside it (their check column).
ui.menu_button(format!(" {}", tl!("Character Alignment")), |ui| {
use vectorcraft_doc::CharAlign;
for (label, a, key) in [
(tl!("Roman Baseline"), CharAlign::RomanBaseline, "romanBaseline"),
(tl!("Em Box Top/Right"), CharAlign::EmBoxTop, "emBoxTop"),
(tl!("Em Box Center"), CharAlign::EmBoxCenter, "emBoxCenter"),
(tl!("Em Box Bottom/Left"), CharAlign::EmBoxBottom, "emBoxBottom"),
] {
if menu_item(ui, label, true, align == Some(a)) {
format(app, json!({"charAlign": key}));
}
}
});
});
ui.separator();
}
for l in ["Standard Vertical Roman Alignment", "Tate-chu-yoko", "Fractional Widths", "System Layout", "No Break"] {
menu_item(ui, tl!(l), false, l == "Fractional Widths");
}
@@ -414,3 +436,23 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
/// Character Alignment is in the panel menu with the East Asian options only (as Mojikumi Set
/// and Top-to-Top Leading are in the Paragraph panel).
#[test]
fn character_alignment_shows_with_the_east_asian_options() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "雅楽"})).unwrap()["id"].clone();
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let shown = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, menu).contains("Character Alignment");
assert!(!shown(&mut app));
app.session.prefs.show_east_asian_options = true;
assert!(shown(&mut app));
}
}
+6 -2
View File
@@ -198,8 +198,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
.color(t.text_dim),
);
ui.horizontal(|ui| {
if let Some(f) = widgets::font_dropdown(ui, "gl-family", &family, (w * 0.6).max(80.0)) {
let st = db.face(&f, "Regular").map_or_else(|| "Regular".into(), |face| face.style.clone());
// Picks the font the panel browses only: nothing is previewed on the document.
let sample = crate::font_menu::sample_text(app);
let look = crate::font_menu::MenuLook::of(app);
let pick = crate::font_menu::font_menu(ui, "gl-family", &family, (w * 0.6).max(80.0), sample.as_deref(), look);
if let Some((f, style)) = crate::font_menu::picked(app, pick) {
let st = style.unwrap_or_else(|| db.face(&f, "Regular").map_or_else(|| "Regular".into(), |face| face.style.clone()));
set_pstate(ui.ctx(), "gl-font", Some((f, st)));
}
let styles = db.styles(&family);
+5 -4
View File
@@ -1,9 +1,10 @@
//! The system clipboard's formats: Copy and Cut publish every flavour the engine makes
//! ([`Session::clipboard_flavours`](vectorcraft_engine::Session::clipboard_flavours): text, SVG,
//! PDF, PNG), and a Paste first turns what another app copied (SVG, PDF, an EMF, text, a bitmap)
//! into the internal clipboard with the `clipboard.import*` commands. The host installs the
//! platform side as [`Services::system_clipboard`](crate::Services::system_clipboard); without it
//! (the web) Copy publishes SVG text through egui and Paste takes SVG text only.
//! PDF, PNG), and a Paste first turns what another app copied (SVG, PDF, an EMF, text, a bitmap,
//! or a copied file that is one of them) into the internal clipboard with the `clipboard.import*`
//! commands. The host installs the platform side as
//! [`Services::system_clipboard`](crate::Services::system_clipboard); without it (the web) Copy
//! publishes SVG text through egui and Paste takes SVG text only.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::clipboard::{EMF, Flavour, PASTE_ORDER, PDF, SVG, TEXT, looks_like_svg};
+29
View File
@@ -241,3 +241,32 @@ fn stars_mark_favourites_and_the_preferences_size_the_rows() {
let look = MenuLook::of(&app);
assert!(!look.samples && look.row > 24.0, "Font Preview Size and Enable in-menu font previews");
}
/// Find Font's Replace With and the Glyphs panel only pick a font: their menu's highlight never
/// previews on the document, a choice is just returned, and a star is still toggled.
#[test]
fn menus_that_only_pick_a_font_leave_the_document_alone() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let font = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.first_style().font_family,
_ => String::new(),
};
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = steps(&app);
use crate::font_menu::picked;
assert_eq!(picked(&mut app, None), None);
assert_eq!(picked(&mut app, Some(FontPick::Preview("Source Serif 4".into(), None))), None);
assert_eq!(picked(&mut app, Some(FontPick::EndPreview)), None);
assert_eq!(
picked(&mut app, Some(FontPick::Chosen("Source Serif 4".into(), Some("Bold".into())))),
Some(("Source Serif 4".to_string(), Some("Bold".to_string())))
);
assert_eq!((font(&app), steps(&app)), ("Inter".to_string(), before), "nothing previewed or applied on the text");
assert_eq!(picked(&mut app, Some(FontPick::Favorite("Inter".into()))), None);
assert_eq!(app.ui.favorite_fonts, ["Inter"], "a star is still toggled");
assert_eq!(picked(&mut app, Some(FontPick::Favorite("inter".into()))), None);
assert!(app.ui.favorite_fonts.is_empty());
}
+2 -49
View File
@@ -1,12 +1,10 @@
//! The font menus list the installed fonts without asking for them (#36), and the font dropdown
//! searches them.
//! The font menus list the installed fonts without asking for them (#36).
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_text::{FontDb, system_font_dirs};
use crate::tests_labels::shapes_text;
use crate::{VectorcraftApp, menus, widgets};
use crate::{VectorcraftApp, menus};
#[test]
fn type_font_menu_lists_every_available_family() {
@@ -25,51 +23,6 @@ fn type_font_menu_lists_every_available_family() {
assert_eq!(fonts(&app), labels);
}
#[test]
fn the_font_dropdown_searches_the_families_and_enter_picks_the_first_match() {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
// Each frame: what it painted, where the dropdown is and what it picked.
let frame = |events: Vec<egui::Event>| {
let input =
egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), ..Default::default() };
let (mut at, mut picked) = (egui::Pos2::ZERO, None);
let mut out = ctx.run_ui(input, |ui| {
at = ui.next_widget_position();
picked = widgets::font_dropdown(ui, "test-font", "Inter", 220.0);
});
out.textures_delta.clear();
(shapes_text(&out), at, picked)
};
let (closed, at, _) = frame(vec![]);
assert_eq!(closed.trim(), "Inter");
let click = at + egui::vec2(40.0, 10.0);
let button = |pressed| egui::Event::PointerButton { pos: click, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(vec![egui::Event::PointerMoved(click), button(true)]);
frame(vec![button(false)]);
// The popup sizes itself invisibly in its first frame, then the list scrolls (animated).
for _ in 0..30 {
frame(vec![]);
}
// The families painted in the list (the button shows the current one, Inter).
let families = FontDb::global().families();
let listed = |text: &str| -> Vec<String> { text.lines().skip(1).filter(|l| families.iter().any(|f| f == l)).map(str::to_string).collect() };
let (open, ..) = frame(vec![]);
assert!(listed(&open).len() >= families.len().min(5), "{open}");
assert!(listed(&open).iter().any(|f| f == "Inter"), "the current font in view: {open}");
// The search field has the focus: typing filters the list.
frame(vec![egui::Event::Text("source serif".into())]);
let (filtered, ..) = frame(vec![]);
let shown = listed(&filtered);
assert!(shown.iter().any(|f| f == "Source Serif 4"), "{filtered}");
assert!(shown.iter().all(|f| f.to_lowercase().contains("source serif")), "{shown:?}");
let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
let (_, _, picked) = frame(vec![enter(true), enter(false)]);
assert_eq!(picked.as_deref(), Some("Source Serif 4"));
let (closed, ..) = frame(vec![]);
assert_eq!(closed.trim(), "Inter", "the list closes");
}
#[test]
fn the_character_panel_menu_refreshes_the_font_list() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+5 -2
View File
@@ -219,8 +219,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
/// Options dialog, the Blend tool's Blend
/// Options; the Print Tiling tool's resets the print tiling. As in the reference app, the Hand
/// tool's fits the artboard in the window, the Zoom tool's shows it at 100%, the Rotate, Scale,
/// Reflect and Shear tools' are their Object › Transform dialogs, and the selection tools' are the
/// Move dialog.
/// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the
/// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools' are their Tool
/// Options.
pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::Value, String> {
match tool {
"hand" => app.run("view.fitArtboard", json!({})),
@@ -252,6 +253,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::
"printTiling" => app.run("print.tiling.set", json!({ "reset": true })),
// The Liquify tools: their Tool Options (the Global Brush Dimensions and the tool's own).
_ if vectorcraft_tools::settings::LIQUIFY.contains(&tool) => crate::dialogs::liquify::open(app, tool),
// The freehand tools: their Tool Options (Fidelity, fill, the tolerances, the brush size).
_ if crate::dialogs::freehand::TOOLS.contains(&tool) => crate::dialogs::freehand::open(app, tool),
_ if vectorcraft_tools::tool_info(tool).is_none() => Err(format!("unknown tool `{tool}`")),
_ => Err(format!("the {tool} tool has no options")),
}
-55
View File
@@ -530,61 +530,6 @@ pub(crate) fn combo<R>(
.inner
}
/// The font family dropdown: every family available (the installed fonts included), with a search
/// field over the list that filters it as you type (Enter picks the first match). Returns the
/// chosen family.
pub fn font_dropdown(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, current: &str, width: f32) -> Option<String> {
let state = ui.id().with(&id).with("font-search");
combo(ui, id, current, width, true, |ui| {
// Each time the list opens: unfiltered, with the current font in view. Typing goes to the
// search field.
let pass = ui.ctx().cumulative_pass_nr();
// (the last pass the list was drawn in, the pass it opened in)
let (last, opened) = ui.data(|d| d.get_temp::<(u64, u64)>(state)).unwrap_or_default();
let opened = if last + 1 < pass || last == 0 { pass } else { opened };
let field = state.with("query");
ui.data_mut(|d| {
d.insert_temp(state, (pass, opened));
if opened == pass {
d.insert_temp(field, String::new());
}
});
// Its first two passes: a popup sizes itself in the first, invisibly.
let opening = pass <= opened + 1;
if ui.memory(|m| m.focused().is_none()) {
ui.memory_mut(|m| m.request_focus(field.with("edit")));
}
let query = search_field(ui, field, "Search").to_lowercase();
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
let families = vectorcraft_text::FontDb::global().menu_family_list();
let (mut chosen, mut first) = (None, None);
// The search field stays put over the list as it scrolls.
menu_scroll(ui, |ui| {
for f in families.iter().filter(|f| query.is_empty() || f.to_lowercase().contains(&query)) {
first.get_or_insert(f);
let r = ui.add(egui::Button::selectable(f == current, f.as_str()));
if opening && f == current {
r.scroll_to_me(Some(egui::Align::Center));
}
if r.clicked() {
chosen = Some(f.clone());
}
}
});
match first {
None => {
dim_label(ui, "No matching fonts");
}
Some(f) if enter && chosen.is_none() => chosen = Some(f.clone()),
_ => {}
}
if chosen.is_some() {
ui.close();
}
chosen
})
}
/// The body of a menu or popup list: as tall as its items up to the bottom of the window, and
/// scrolling only past that, so long menus (Window, Effect, a panel's menu) stay reachable on
/// small windows.
+6
View File
@@ -523,6 +523,12 @@ then the tool's options `detail`, `simplify` and `simplifyOn` (Warp, Twirl, Puck
`vertical` (Wrinkle, %), and `showBrush`. `ui.dialog.confirm` runs `tool.setOption {tool, values}`. `ui.pointer`
events take `pressure` (0..1, default 1): it is the Liquify intensity while Use Pressure Pen is on.
Freehand Tool Options: double-clicking the Pencil, Paintbrush, Smooth, Blob Brush or Eraser tool
(`tool.options {tool: "pencil"}`) opens a `freehandOptions` dialog. Its fields are `tool` and the options the tool
keeps: `fidelity` (pt; Pencil, Paintbrush, Smooth), `fill` (Pencil, Paintbrush), `closeWithin` and `editWithin` (screen
pixels, 0 turns it off; Pencil, Paintbrush) and `size` (pt; Blob Brush, Eraser). `ui.dialog.confirm` runs
`tool.setOption {tool, values}`.
`ui.pointer` events also take `holdMs` (0..60000): the pointer then holds still that long, button down, before the
next event. Twirl, Pucker and Bloat keep applying while held (a repeat of the last point every 0.1 s), exactly as
for the same time held with the mouse. Liquify leaves type, symbols, images, graphs, meshes, envelopes, repeats and
+8
View File
@@ -42,6 +42,14 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU (
- The `WGPU_POWER_PREF` environment variable (`low`, `high` or `none`) overrides the preference.
- Help › About and the control channel's `ui.inspect` (`graphicsAdapter`) show the adapter in use, and the app logs it at startup.
## Linux: Wayland and X11
The window runs natively on Wayland (eframe's `wayland` feature) and on X11. The system clipboard (`apps/vectorcraft/src/clipboard.rs`) is arboard with its `wayland-data-control` feature:
- **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. egui's own text paste into fields goes through smithay-clipboard and works either way.
- **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EMF/WMF or a bitmap), before the clipboard's other formats (which include the files' paths as text).
- **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.36 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or run the app under XWayland, where drops work (`WAYLAND_DISPLAY= vectorcraft`).
## Fonts: craft-fonts (optional build input)
Font files are never committed to this repository. Fonts shared by the Crafting Apps live in
+6 -2
View File
@@ -75,7 +75,7 @@ is thousands of lines an agent pays for again on every change.
| `uriTemplate` | Reads |
|---|---|
| `vectorcraft://object/{id}` | One layer or object with its children, bounds and paint: `document.node {id, summary: true}`, the node as `document.inspect` lists it |
| `vectorcraft://object/{id}` | One layer or object with its children, bounds and paint: `document.node {id, summary: true}`, the node as `document.inspect` lists it. A large container can be sliced with `run_command document.node {id, summary: true, depth?, childLimit?}` (a level that shows fewer children reports `childCount`) |
| `vectorcraft://command/{id}` | One command: label, menu path, shortcut, parameter description, enablement |
| `vectorcraft://effect/{id}` | One live effect with its parameters and defaults |
| `vectorcraft://swatch/{name}` | One swatch, colour, gradient or pattern swatch (percent-encode spaces) |
@@ -85,7 +85,11 @@ An unknown URI is `-32002`; a template with no value, or a value that names noth
The same reads work as query commands through `run_command`: `document.node {id}` returns the object's full model
JSON (geometry, appearance, every attribute) and `document.node {id, summary: true}` the compact summary
`document.inspect` gives for it (id, name, kind, bounds, paint labels, children), without summarizing the whole
document.
document. A summary read slices a large container: `depth` is how many child levels it includes (`0`: the node
alone) and `childLimit` how many children each node shows, top of the stack first (both default to all). A level
that shows fewer children than it has reports their total as `childCount`, so truncation is never silent; with
nothing truncated the reply is the plain summary. Both must be non-negative integers and need `summary: true`
(the full object JSON is never truncated); anything else is an error.
### Completions