Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 a0d5d72d90 Fix #593: anchors and handle ends are easier to grab than the segments through them
An anchor was picked within the selection tolerance (3 px), the same reach
as its segments: a press a little off the anchor's 5 px square took the
curve instead.

- `ToolContext::point_tol`: anchors and direction handle ends are picked
  within the selection tolerance, but at least 2 px past the drawn point
  (4.5 px at the default Size 3, more with a larger Size). Anchors are
  tested before segments, so where both are within reach the anchor wins.
- Direct Selection (presses, Highlight anchors on mouse over, blend spine
  points and handles), the Anchor Point, Delete Anchor Point and Scissors
  tools, and the Pen (its Alt conversions; its close/continue reach stays
  5 px unless the points are drawn larger) use it. Segments, objects and
  frame edges keep the selection tolerance.
- Of the topmost path with anchors in reach, the nearest anchor is picked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 05:09:31 +07:00
BFlat c3b73f0146 Merge pull request: land #603 (part of #372)
Land #603 (part of #372: .ai layers and sublayers as PDF layers, hidden ones kept)
2026-10-09 04:51:50 +07:00
bflatastic ef99ab8d1c Merge #603: Part of #372: .ai files write layers and sublayers as PDF layers, hidden ones kept
# Conflicts:
#	ROADMAP.md
2026-10-09 04:46:09 +07:00
BFlat a89f914119 Merge pull request: land #600, #601
Land #600 (area type vertical alignment) and #601 (RTL shaping across runs)
2026-10-09 04:45:23 +07:00
bflatasticandClaude Opus 5.5 50bb36ebc2 Part of #372: .ai files write layers and sublayers as PDF layers, hidden ones kept
A `.ai` file's PDF part is what apps that don't read VectorCraft's native
document open. It had no PDF layers: hidden layers and sublayers were left
out of it and everything else was flat page content.

- `.ai` files (Save As, exports, the CLI) write PDF layers unless
  `createLayers` is false (a PDF standard still decides for itself).
- createLayers writes sublayers too, as optional content groups listed
  under their layer's in `/Order`, hidden ones off with their art.
- A layer's form gets a box round the whole page instead of its art's
  bounds, which readers made a clipping group of, gathering a layer's art
  and its sublayers' in one group.
- PDF import: art inside a group, clip or form that dissolves into its
  parent keeps the layer it was drawn in, so sublayers nested in their
  layer's content import as sublayers.
- Save PDF: "Create PDF layers from layers and sublayers" (ja, es, it,
  pt-br, ru, zh-hans, zh-hant).

Hidden objects (not layers) still aren't in the PDF part.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 04:40:30 +07:00
bflatastic 4e774b8b61 Merge #601: Fix RTL shaping across text runs 2026-10-09 04:39:56 +07:00
bflatasticandClaude Opus 5.5 017c846889 Tests: the top-to-top em box check needs the craft-fonts CJK faces
Without craft-fonts the CJK text falls back to a system font with its own
em box (Windows: 34.0 instead of 35.2 at 40 pt); the relative alignment
checks hold either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 04:39:56 +07:00
bflatasticandClaude Opus 5.5 e12ed1608e Tests: the composer round trip counts #600's area type in the rich fixture
#587 and #600 landed together: the fixture's new area type (Every-line,
the default) is a second text object the composer test now sees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 04:36:06 +07:00
Emad Fussi 9e6c115481 Fix RTL shaping across text runs 2026-10-09 00:34:00 +03:00
bflatastic c7b2bba90e Merge #600: M7: area type vertical alignment 2026-10-09 04:31:10 +07:00
haven d2bb95daab M7: area type vertical alignment
Area Type Options > Align: Top / Center / Bottom / Justify (AreaOptions.verticalAlign,
LayoutOptions.vertical_align). Each row/column cell is aligned on its own; rectangular
cells shift their lines, other frames and text wrap reflow until settled without
losing text. Justify shares the leftover space equally between line gaps. Area Type Options
shows Align and First Baseline as dropdowns (the parameter dialog's choices table).
2026-10-08 14:28:02 -07:00
BFlat 8d0cede84a Merge pull request: land #594 (fix #579)
Land #594 (fix #579: fonts from font services such as Adobe Fonts on Windows)
2026-10-09 04:26:21 +07:00
bflatastic 030d407f61 Merge #594: Fix #579: fonts activated by font services such as Adobe Fonts are listed on Windows
# Conflicts:
#	ROADMAP.md
2026-10-09 04:18:54 +07:00
BFlat 465ec07445 Merge pull request: land #591 (fix #578)
Land #591 (fix #578: no flicker dragging the Color spectrum near white)
2026-10-09 04:17:20 +07:00
bflatastic f4b4312cc9 Merge #591: Fix #578: a drag on the Color panel's spectrum no longer flickers near white
# Conflicts:
#	ROADMAP.md
2026-10-09 04:13:07 +07:00
BFlat 0869f51360 Merge pull request #587 from Haven-King/feat/text-engine/text-composer-ragged
M7: Every-line Composer for ragged text
2026-10-09 04:12:08 +07:00
haven d2aad22dac M7: Every-line Composer for ragged text
Illustrator's Every-line Composer balances the breaks of the whole
paragraph for left/centre/right aligned text too, not only justified
text. VectorCraft only composed justified area text; ragged text was
always broken greedily.

- Model: ParaStyle.composer (vectorcraft_doc::Composer, re-exported by
  vectorcraft-text), Every-line by default like Illustrator, saved only
  when Single-line. layout() reads it from the object;
  LayoutOptions.composer is now an Option override for tests.
- Composer: the justified gate is gone. Ragged lines never shrink (a
  line that doesn't fit ends the node), badness is 100*r^3 with r = the
  line's leftover space over a rag zone of 1/6 of the width (finite for
  lines without spaces); the last line is free unless shorter than 1/3
  of the width (measured in zones of 1/3), so a lone short word on the
  last line pulls a word down. Hyphens cost 25 in ragged text (50 in
  justified). Knuth-Plass fitness classes with adjacency demerits
  (justified 10000, ragged 1000). Lines past the last width change
  share one node key, active nodes are capped (4096) and paragraphs
  over 200k glyphs break single-line, so work stays bounded; ragged
  tries a tolerance of one rag zone, then any fitting breaks, then
  falls back to greedy.
- text.setFormat {composer: "singleLine"|"everyLine"}; the Paragraph
  panel menu's composer items work with a check mark (Reset Panel goes
  back to Every-line).
- Tests: ragged Every-line moves "or" down in "Destroy all creatures
  with toughness X or less." where greedy leaves "less." alone; the rag
  of long paragraphs is no worse than greedy (sum of squared leftover
  and of neighbour differences); Single-line is greedy; the 10k-char
  layout budget covers ragged text; command test with undo; native
  format round trip (rich_session's text is now Single-line).
  No existing test needed changing: the justified tests and
  hyphenated_layout_adds_hyphens (ragged, now Every-line) still pass.

Auto alignment (start of the paragraph direction) is ragged; a wrapped
line's Mojikumi flush opening bracket gives its half em back to the
composer, as in the line loop; tests cover Auto in both directions.

Layout of 10k chars, release: justified Every-line 5.6 ms, ragged
Every-line 5.8 ms, ragged Single-line 4.8 ms.
2026-10-08 14:03:33 -07:00
bflatasticandClaude Opus 5.5 2e64786e8c Fix #578: a drag on the Color panel's spectrum no longer flickers near white
The Color panel shows the out-of-gamut and out-of-web warnings under its
proxy only when the colour needs them, so the panel grew and shrank with
the colour. Dragging on the spectrum's pale top edge, a colour out of
gamut added a warning, the spectrum moved down under the pointer, the
pointer then picked white (above the spectrum), the warning went away,
the spectrum moved back up: the colour flipped every frame.

The panel now keeps room for the warnings its mode can show, so its
height no longer depends on the colour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 04:02:44 +07:00
43 changed files with 1547 additions and 197 deletions

No files matched your search

+6 -5
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
## Where we are
@@ -60,7 +60,8 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
renderer in its own crate (layering allows it below L6), with output in SVG/PDF as rasters or projected vectors.
The largest single gap. 50–80 h.
4. **Advanced type:** CJK composition for vertical type (ruby, mojikumi, proportional vertical metrics, manual
tate-chu-yoko), Optical Margin Alignment, the composer/hyphenation options, tab leaders, a
tate-chu-yoko), Optical Margin Alignment, the hyphenation and justification options (the Every-line/Single-line
composer choice is done), tab leaders, a
spell-check dictionary (open licence), Touch Type and Snap to Glyph. Vertical point, area and path type have
initial support. 35–48 h across type core and advanced.
5. **Brushes, symbols and libraries:** brush options depth; original brush, symbol and graphic-style libraries
@@ -138,7 +139,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Geometry and effects:**
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
- 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) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), 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. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline 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; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
@@ -175,7 +176,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 (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; 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 and Options with draggable start/centre/end brackets (slide, flip), 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 and vertical Align), 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 (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; 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 and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) 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 |
@@ -210,7 +211,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 |
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 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 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); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), 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 (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) (Vector Halftone is done) | 6–10 |
+3
View File
@@ -28,3 +28,6 @@ sync_github_name = false
[people.mo0kid]
sync_github_name = true
[people.omd0]
sync_github_name = true
+2 -2
View File
@@ -82,8 +82,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, Burasagari, CharAlign, CharPosition, CharStyle, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign,
PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape,
AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle,
PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
};
pub use vectorcraft_color as color;
pub use vectorcraft_geom as geom;
+65 -1
View File
@@ -285,6 +285,24 @@ fn default_align_on() -> char {
/// Distance between default tab stops when no explicit stop applies (½ inch).
pub const DEFAULT_TAB_INTERVAL: f64 = 36.0;
/// Paragraph composer (Paragraph panel menu): how lines are broken.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Composer {
/// Break each line as soon as it is full.
SingleLine,
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
/// spacing, ragged lines an even rag.
#[default]
EveryLine,
}
impl Composer {
fn is_default(&self) -> bool {
*self == Self::default()
}
}
/// Paragraph attributes (the Paragraph panel).
///
/// Saved through [`ParaStyleFile`], which keeps files with text openable by builds from before
@@ -299,6 +317,8 @@ pub struct ParaStyle {
pub space_before: f64,
pub space_after: f64,
pub hyphenate: bool,
/// Line breaking: Single-line or Every-line Composer.
pub composer: Composer,
/// Tab stops (Tabs panel), sorted by position.
pub tabs: Vec<TabStop>,
/// Paragraph style (Paragraph Styles panel) these attributes come from; None = Normal.
@@ -341,6 +361,8 @@ struct ParaStyleFile {
space_after: f64,
#[serde(default)]
hyphenate: bool,
#[serde(default, skip_serializing_if = "Composer::is_default")]
composer: Composer,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
tabs: Vec<TabStop>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -370,6 +392,7 @@ impl From<ParaStyle> for ParaStyleFile {
space_before,
space_after,
hyphenate,
composer,
tabs,
style_name,
mojikumi,
@@ -387,6 +410,7 @@ impl From<ParaStyle> for ParaStyleFile {
space_before,
space_after,
hyphenate,
composer,
tabs,
style_name,
mojikumi,
@@ -407,6 +431,7 @@ impl From<ParaStyleFile> for ParaStyle {
space_before,
space_after,
hyphenate,
composer,
tabs,
style_name,
mojikumi,
@@ -423,6 +448,7 @@ impl From<ParaStyleFile> for ParaStyle {
space_before,
space_after,
hyphenate,
composer,
tabs,
style_name,
mojikumi,
@@ -506,6 +532,34 @@ pub enum FirstBaseline {
Fixed,
}
/// Area Type Options "Align" (vertical): where the lines of each row/column sit in it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum VerticalAlign {
/// Lines start at the top of the cell (the default).
#[default]
Top,
/// The block of lines is centred in the cell.
Center,
/// The last line's descent touches the cell bottom.
Bottom,
/// The first line stays at the top, the last one moves to the bottom and the space left over
/// is shared equally between the lines (no paragraph spacing limit).
Justify,
}
impl VerticalAlign {
pub const ALL: [VerticalAlign; 4] = [VerticalAlign::Top, VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify];
pub fn id(self) -> &'static str {
match self {
VerticalAlign::Top => "top",
VerticalAlign::Center => "center",
VerticalAlign::Bottom => "bottom",
VerticalAlign::Justify => "justify",
}
}
}
/// Text Wrap Options of a wrap object (Object → Text Wrap).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
@@ -608,11 +662,21 @@ pub struct AreaOptions {
pub first_baseline: FirstBaseline,
/// Minimum first-baseline offset in points.
pub first_baseline_min: f64,
/// Vertical alignment of the lines in each row/column.
pub vertical_align: VerticalAlign,
}
impl Default for AreaOptions {
fn default() -> Self {
Self { rows: 1, columns: 1, gutter: 18.0, inset: 0.0, first_baseline: FirstBaseline::Ascent, first_baseline_min: 0.0 }
Self {
rows: 1,
columns: 1,
gutter: 18.0,
inset: 0.0,
first_baseline: FirstBaseline::Ascent,
first_baseline_min: 0.0,
vertical_align: VerticalAlign::Top,
}
}
}
+2 -2
View File
@@ -86,7 +86,7 @@ pub(super) const OPTIONS: &[FormatOption] = &[
name: "createLayers",
ty: "boolean",
default: "false",
description: "top-level layers as PDF layers (optional content groups with their visibility, print state and lock; PDF 1.5 or later)",
description: "layers and sublayers as PDF layers (optional content groups with their visibility, print state and lock, sublayers listed under their layers; PDF 1.5 or later)",
},
FormatOption {
name: "flattenerPreset",
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each top-level layer but template layers as a PDF layer, an optional content group: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A always), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: true (false: type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet c Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A always), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: true (false: type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options ac Line truncated
has_doc,
export_pdf
),
+7 -2
View File
@@ -306,11 +306,16 @@ fn blank_pages(doc: &Document) -> Document {
const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages";
/// The encoder's params for a `.ai` file, from a save's or an export's: a PDF of every artboard
/// with the PDF options, always carrying the native document; Use Compression compresses the
/// PDF's content.
/// with the PDF options, always carrying the native document, its layers and sublayers PDF layers
/// (hidden ones off) unless asked otherwise; Use Compression compresses the PDF's content.
pub(super) fn ai_params(params: &mut Value) {
let Some(o) = params.as_object_mut() else { return };
o.extend([("preserveEditing".into(), json!(true)), ("range".into(), json!("all"))]);
// Apps that read the PDF part (not the native document) then find the layers, the hidden ones
// with their art (#372); a PDF standard decides for itself.
if o.get("standard").is_none_or(Value::is_null) {
o.entry("createLayers").or_insert(json!(true));
}
if let Some(c) = o.get("compress").and_then(Value::as_bool) {
let compression = o.entry("compression").or_insert_with(|| json!({}));
if let Some(m) = compression.as_object_mut() {
@@ -59,3 +59,35 @@ fn export_pdf_overprint_is_preserved_or_discarded() {
assert_eq!(overprints(&mut s, json!({"compression": {"compressText": false}})), 1);
assert_eq!(overprints(&mut s, json!({"advanced": {"overprint": "discard"}})), 0);
}
/// A `.ai` file's PDF part, which apps that don't read the native document open, has the layers
/// and sublayers as PDF layers, the hidden ones with their art (#372).
#[test]
fn ai_files_write_their_layers_and_sublayers_as_pdf_layers() {
let mut s = session();
let layer1 = s.execute("document.inspect", &json!({})).unwrap()["layers"][1]["id"].as_u64().unwrap();
let sub = s.execute("layer.newSublayer", &json!({"parent": layer1, "name": "Sketch"})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setCurrent", &json!({"id": sub})).unwrap();
s.execute("shape.ellipse", &json!({"x": 10, "y": 40, "width": 20, "height": 20})).unwrap();
s.execute("layer.setProps", &json!({"id": sub, "visible": false})).unwrap();
// Name, shown and what it holds (sublayers by name), top-level layers in paint order.
fn rows(layers: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Vec<(String, bool, Vec<String>)> {
layers
.iter()
.map(|l| {
let held =
l.children().into_iter().flatten().map(|c| c.name.clone().filter(|_| c.is_layer()).unwrap_or_else(|| "art".into())).collect();
(l.name.clone().unwrap_or_default(), l.visible, held)
})
.collect()
}
let v = s.execute("document.export", &json!({"format": "ai"})).unwrap();
let back = vectorcraft_pdf::import(&b64(&v)).unwrap();
let art = || "art".to_string();
assert_eq!(rows(&back.layers), [("Layer 1".to_string(), true, vec![art(), "Sketch".into()]), ("Notes".to_string(), false, vec![art()])]);
let sketch = back.layers.first().and_then(|l| l.children()?.last().cloned()).unwrap();
assert_eq!(rows(&[sketch]), [("Sketch".to_string(), false, vec![art()])]);
// Asked not to, it writes none.
let v = s.execute("document.export", &json!({"format": "ai", "createLayers": false})).unwrap();
assert_eq!(vectorcraft_pdf::import(&b64(&v)).unwrap().layers.len(), 1);
}
+14 -2
View File
@@ -2,7 +2,7 @@
//! Character/Paragraph attributes.
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_doc::{Composer, NodeKind};
use vectorcraft_geom::{Rect, Vec2};
use super::*;
@@ -43,7 +43,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), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\")}",
"{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), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default)}",
has_doc,
set_format
),
@@ -219,10 +219,19 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"leadingModel",
"charAlign",
"burasagari",
"composer",
];
if !keys.iter().any(|k| p.get(*k).is_some()) {
return Err(bad(C, "nothing to change"));
}
let composer = match p.get("composer") {
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
Some("singleLine") => Composer::SingleLine,
Some("everyLine") => Composer::EveryLine,
_ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")),
}),
};
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") {
@@ -329,6 +338,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = burasagari {
para.burasagari = v;
}
if let Some(v) = composer {
para.composer = v;
}
super::typecmd::refresh_bounds(t);
}
Ok(())
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area Type Options…",
["Type"],
None,
"{ids?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (none given: query) → the first object's options",
"{ids?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (none given: query) → the first object's options",
has_selection,
area_options
),
+10
View File
@@ -248,6 +248,16 @@ fn text_set_format() {
let NodeKind::Text(t) = node(&s, id).kind else { panic!() };
assert_eq!(t.first_style().kerning, None);
assert!(s.execute("text.setFormat", &json!({"ids": [id.0]})).is_err());
// Paragraph composer: Every-line by default, undoable.
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine"})).unwrap();
let NodeKind::Text(t) = node(&s, id).kind else { panic!() };
assert_eq!(t.para.composer, vectorcraft_doc::Composer::SingleLine);
assert!(s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "best"})).is_err());
assert!(s.execute("text.setFormat", &json!({"ids": [id.0], "composer": 1})).is_err());
s.execute("edit.undo", &json!({})).unwrap();
let NodeKind::Text(t) = node(&s, id).kind else { panic!() };
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
}
#[test]
+35
View File
@@ -339,3 +339,38 @@ fn the_type_widget_converts_point_and_area_type() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s, id), before);
}
#[test]
fn area_type_options_align_the_lines_vertically() {
use vectorcraft_doc::VerticalAlign;
let mut s = session();
let id = area(&mut s, 40.0, 40.0, 200.0, 300.0, "Short story");
sel(&mut s, &[id]);
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["verticalAlign"], "top");
let top = layout(&s, id).lines[0].baseline;
let before = text(&s, id).cached_bounds;
let n = undo_len(&s);
let r = s.execute("text.areaOptions", &json!({"verticalAlign": "bottom"})).unwrap();
assert_eq!(r["verticalAlign"], "bottom");
assert_eq!(text(&s, id).area.vertical_align, VerticalAlign::Bottom);
let l = layout(&s, id);
let last = l.lines.last().unwrap();
assert!((last.baseline + last.descent - 300.0).abs() < 1e-6);
assert!(l.lines[0].baseline > top + 200.0);
assert_ne!(text(&s, id).cached_bounds, before, "the cached bounds follow the text");
assert_eq!((undo_len(&s), last_step(&s).as_str()), (n + 1, "Area Type Options"));
s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap();
assert_eq!(text(&s, id).area.vertical_align, VerticalAlign::Center);
// Unknown values are refused and change nothing.
for bad in [json!({"verticalAlign": "middle"}), json!({"verticalAlign": 3}), json!({"verticalAlign": null})] {
assert!(s.execute("text.areaOptions", &bad).is_err(), "{bad}");
}
assert_eq!(undo_len(&s), n + 2);
assert_eq!(text(&s, id).area.vertical_align, VerticalAlign::Center);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s, id).area.vertical_align, VerticalAlign::Top);
assert_eq!(layout(&s, id).lines[0].baseline, top);
assert_eq!(text(&s, id).cached_bounds, before);
assert!(cmd::find_command("text.areaOptions").unwrap().params.contains("verticalAlign?: top|center|bottom|justify"));
}
+1
View File
@@ -205,6 +205,7 @@ impl Session {
slices_locked: self.menu.slices_locked,
auto_add_delete: !self.prefs.disable_auto_add_delete,
selection_tolerance: self.prefs.selection_tolerance,
anchor_size: self.prefs.anchor_size,
path_only: self.prefs.object_selection_by_path_only,
type_path_only: self.prefs.type_selection_by_path_only,
double_click_isolate: self.prefs.double_click_to_isolate,
+62 -1
View File
@@ -7,7 +7,7 @@ use std::io::Write as _;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{ColorProfiles, Document, ImageBlob, ImageObject, Node, NodeKind, OpacityMask, Symbol};
use vectorcraft_doc::{ColorProfiles, Composer, Document, ImageBlob, ImageObject, Node, NodeKind, OpacityMask, Symbol};
use vectorcraft_format::{FormatError, SaveOptions, VERSION, is_compressed, load, preview, save, save_with, sniff};
use vectorcraft_geom::Affine;
use vectorcraft_testkit::fixtures;
@@ -43,6 +43,31 @@ fn opts(version: u32, compress: bool) -> SaveOptions {
SaveOptions { version, compress, ..SaveOptions::default() }
}
#[test]
fn area_type_vertical_alignment_round_trips() {
let d = rich_doc();
let text = String::from_utf8(save(&d, false)).unwrap();
assert!(text.contains("\"verticalAlign\":\"center\""), "the fixture's area type is centred");
let back = load(text.as_bytes()).unwrap();
assert_eq!(doc_json(&back), doc_json(&d));
let area = |d: &Document| {
let mut found = None;
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind
&& matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })
{
found = Some(t.area.vertical_align);
}
});
found.unwrap()
};
assert_eq!(area(&back), vectorcraft_doc::VerticalAlign::Center);
// Files from before the option open top-aligned.
let old = text.replacen("\"verticalAlign\":\"center\",", "", 1).replacen(",\"verticalAlign\":\"center\"", "", 1);
assert!(!old.contains("verticalAlign"));
assert_eq!(area(&load(old.as_bytes()).unwrap()), vectorcraft_doc::VerticalAlign::Top);
}
#[test]
fn compressed_files_load() {
let d = rich_doc();
@@ -111,6 +136,42 @@ fn keys_from_newer_versions_round_trip() {
check_native_roundtrip(&d).unwrap();
}
/// The paragraph composer is saved only when it isn't the default (Every-line) and reads back.
#[test]
fn text_composer_round_trips() {
let d = rich_doc();
let composers = |d: &Document| {
let mut v = vec![];
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
v.push(t.para.composer);
}
});
v
};
// The point type set to Single-line, then the area type left at the default.
assert_eq!(composers(&d), [Composer::SingleLine, Composer::EveryLine]);
let bytes = save(&d, false);
assert!(String::from_utf8_lossy(&bytes).contains("\"composer\":\"singleLine\""));
assert_eq!(composers(&load(&bytes).unwrap()), [Composer::SingleLine, Composer::EveryLine]);
// Files without the key (older files, Every-line text) read as Every-line.
fn strip(v: &mut Value) {
match v {
Value::Object(m) => {
m.remove("composer");
m.values_mut().for_each(strip);
}
Value::Array(a) => a.iter_mut().for_each(strip),
_ => {}
}
}
let mut v = json_of(&bytes);
strip(&mut v);
let d2 = load(&serde_json::to_vec(&v).unwrap()).unwrap();
assert_eq!(composers(&d2), [Composer::EveryLine, Composer::EveryLine]);
assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer"));
}
/// A document as the first version wrote it (format name `drawcraft`, anchors as maps).
const V1_FILE: &str = r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{"version":1,"title":"Old","artboards":[{"id":1,"name":"Artboard 1","rect":{"x0":0.0,"y0":0.0,"x1":100.0,"y1":80.0}}],
"layers":[{"id":1,"name":"Layer 1","visible":true,"locked":false,"opacity":1.0,"kind":{"type":"layer","children":[
+18 -10
View File
@@ -453,11 +453,13 @@ pub(crate) struct Exporter<'a> {
/// The fonts real text is written in, by face id, with their units per em; `None` for faces
/// that can't be embedded.
fonts: HashMap<u32, Option<(krilla::text::Font, f64)>>,
/// Top-level layers are drawn as forms marked for their optional content groups
/// Layers and sublayers are drawn as forms marked for their optional content groups
/// ([`crate::forms`]).
pub layers: bool,
/// A top-level layer's form is being drawn.
in_layer: bool,
/// Each layer's index in [`crate::forms::pdf_layers`], by address.
layer_index: HashMap<usize, usize>,
/// The address of the layer whose form is being drawn.
in_layer: usize,
/// Overprinting fills and strokes are drawn as forms marked to overprint.
pub overprint: bool,
/// An overprinting fill or stroke was drawn so.
@@ -485,7 +487,8 @@ impl<'a> Exporter<'a> {
outline_text: set.advanced.outline_text,
fonts: HashMap::new(),
layers: false,
in_layer: false,
layer_index: crate::forms::pdf_layers(doc).iter().enumerate().map(|(i, l)| (address(l.node), i)).collect(),
in_layer: 0,
overprint: false,
overprinted: false,
}
@@ -601,6 +604,11 @@ fn constant_mask(s: &mut Surface, page: Rect, alpha: f32) -> krilla::mask::Mask
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Alpha)
}
/// A node's address, to tell the very node apart from equal ones.
fn address(n: &Node) -> usize {
std::ptr::from_ref(n).addr()
}
fn rects_overlap(a: Rect, b: Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
@@ -885,15 +893,15 @@ impl Exporter<'_> {
fn node(&mut self, s: &mut Surface, n: &Node, page: Rect, force: bool) {
if self.layers
&& !self.in_layer
&& let NodeKind::Layer { template: false, printable, .. } = n.kind
&& self.in_layer != address(n)
&& let NodeKind::Layer { printable, .. } = n.kind
&& (printable || self.non_printing)
&& let Some(i) = self.doc.layers.iter().position(|l| std::ptr::eq(&**l, n))
&& let Some(&i) = self.layer_index.get(&address(n))
{
// A PDF layer: hidden layers are written too (their group is off).
self.in_layer = true;
// A PDF layer: hidden layers and sublayers are written too (their group is off).
let enclosing = std::mem::replace(&mut self.in_layer, address(n));
crate::forms::form(s, Mark::Layer(i), |s| self.node(s, n, page, true));
self.in_layer = false;
self.in_layer = enclosing;
return;
}
if !force && !n.visible {
+78 -11
View File
@@ -11,7 +11,9 @@ use std::io::Read;
use krilla::geom::PathBuilder;
use krilla::graphic::Graphic;
use krilla::surface::Surface;
use vectorcraft_doc::{Document, NodeKind};
use std::sync::Arc;
use vectorcraft_doc::{Document, Node, NodeKind};
use crate::encrypt::{Lexer, Obj, StreamSpans, Tok, int, stream_spans};
use crate::output::{deflate, text_string};
@@ -21,12 +23,36 @@ use crate::{PdfError, PdfSettings, Standard};
/// What a marked form is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mark {
/// The art of top-level layer `i` (`Document::layers`).
/// The art of layer `i` of [`pdf_layers`].
Layer(usize),
/// A fill or stroke that overprints.
Overprint,
}
/// A layer written as a PDF layer (an optional content group).
pub(crate) struct PdfLayer<'a> {
pub node: &'a Node,
/// Its parent layer's index in [`pdf_layers`] (none for a top-level layer).
pub parent: Option<usize>,
}
/// The layers written as PDF layers: the top-level layers and their sublayers, but template layers
/// (and what they hold), each before its sublayers, in paint order (bottom first).
pub(crate) fn pdf_layers(doc: &Document) -> Vec<PdfLayer<'_>> {
fn add<'a>(nodes: &'a [Arc<Node>], parent: Option<usize>, out: &mut Vec<PdfLayer<'a>>) {
for n in nodes {
if let NodeKind::Layer { template: false, children, .. } = &n.kind {
let i = out.len();
out.push(PdfLayer { node: n, parent });
add(children, Some(i), out);
}
}
}
let mut out = vec![];
add(&doc.layers, None, &mut out);
out
}
/// The x coordinate of a layer mark's first point (its y is the layer index).
const LAYER_X: i32 = -32000;
/// The x coordinate of an overprint mark's first point.
@@ -199,7 +225,7 @@ fn mark_layers(content: &[u8], forms: &HashMap<&[u8], usize>) -> Option<(Vec<u8>
}
/// Finish the marked forms of `pdf` (as [`crate::export`] writes `doc` with `set`): with
/// `layers`, each top-level layer (but template layers) becomes an optional content group —
/// `layers`, each layer and sublayer (but template layers) becomes an optional content group —
/// named as the layer, off when it is hidden, not printed (`/PrintState /OFF`) when its Print
/// option is off, locked when it is locked — and the uses of its forms its optional content;
/// with `overprint`, the overprinting forms get a graphics state that overprints (`/OP`, `/op`,
@@ -228,6 +254,11 @@ pub(crate) fn finish(pdf: Vec<u8>, doc: &Document, set: &PdfSettings, layers: bo
}
if layers {
write_layers(&pdf, &xref, &objects, &marks, &mut patch, doc, set)?;
for (n, _) in marks.iter().filter(|(_, m)| matches!(m, Mark::Layer(_))) {
if let Some(o) = objects.get(n) {
unbox(&pdf, o, &mut patch)?;
}
}
}
let pdf = patch.apply(&pdf, &xref)?;
// The file still is what its standard says.
@@ -235,8 +266,9 @@ pub(crate) fn finish(pdf: Vec<u8>, doc: &Document, set: &PdfSettings, layers: bo
Ok(pdf)
}
/// The optional content groups of `doc`'s top-level layers, the uses of their forms marked as
/// their content, and the catalog's `/OCProperties`.
/// The optional content groups of `doc`'s layers and sublayers ([`pdf_layers`]), the uses of their
/// forms marked as their content, and the catalog's `/OCProperties`, listing sublayers under their
/// layers.
fn write_layers(
pdf: &[u8],
xref: &Xref,
@@ -247,11 +279,16 @@ fn write_layers(
set: &PdfSettings,
) -> Result<(), PdfError> {
// One group per layer, in paint order (bottom first).
let layers = pdf_layers(doc);
let mut groups: HashMap<usize, u32> = HashMap::new();
let (mut all, mut off, mut locked) = (vec![], vec![], vec![]);
for (i, l) in doc.layers.iter().enumerate() {
let NodeKind::Layer { template: false, printable, .. } = l.kind else { continue };
let name = l.name.clone().unwrap_or_else(|| format!("Layer {}", i + 1));
// Each layer's sublayers, and the top-level layers, in paint order.
let mut children: HashMap<Option<usize>, Vec<usize>> = HashMap::new();
for (i, PdfLayer { node: l, parent }) in layers.iter().enumerate() {
let siblings = children.entry(*parent).or_default();
siblings.push(i);
let name = l.name.clone().unwrap_or_else(|| format!("Layer {}", siblings.len()));
let printable = matches!(l.kind, NodeKind::Layer { printable: true, .. });
let on = |b: bool| if b { "ON" } else { "OFF" };
let g = patch.add_object(
format!("<</Type/OCG/Name{}/Usage<</View<</ViewState/{}>>/Print<</PrintState/{}>>>>>>", text_string(&name), on(l.visible), on(printable))
@@ -295,9 +332,7 @@ fn write_layers(
add_resources(patch, res, "Properties", &entries)?;
}
let refs = |v: &[u32]| v.iter().map(|g| format!("{g} 0 R")).collect::<Vec<_>>().join(" ");
// Layers panels list the top layer first.
let order: Vec<u32> = all.iter().rev().copied().collect();
let mut config = format!("/Name(Layers)/Order[{}]", refs(&order));
let mut config = format!("/Name(Layers)/Order[{}]", order(&children, &groups, None));
if !off.is_empty() {
config.push_str(&format!("/OFF[{}]", refs(&off)));
}
@@ -313,3 +348,35 @@ fn write_layers(
patch.replace(start + 2, start + 2, format!("/OCProperties<</OCGs[{}]/D<<{config}>>>>", refs(&all)).into_bytes());
Ok(())
}
/// A form's box as large as a page can be: the box of a layer's form is only the bounds of its
/// art, and a reader that makes a clipping group of a form's box (as importers do) would gather a
/// layer's art and its sublayers' in one group, which no layer can hold. A box round the whole
/// page clips nothing.
const UNBOXED: &[u8] = b"[-32767 -32767 32767 32767]";
/// Give the layer's form `o` the [`UNBOXED`] box.
fn unbox(pdf: &[u8], o: &Object<'_>, patch: &mut Patch) -> Result<(), PdfError> {
let Obj::Dict { start, end, .. } = o.dict else { return Err(bad("a layer's form has no dictionary")) };
let dict = pdf.get(start..end).ok_or_else(|| bad("a layer's form can't be read"))?;
// The writer writes the box as an array of numbers.
let at = dict.windows(5).position(|w| w == b"/BBox").ok_or_else(|| bad("a layer's form has no box"))? + 5;
let open = at + dict.get(at..).and_then(|d| d.iter().position(|&c| c == b'[')).ok_or_else(|| bad("a layer's form box isn't an array"))?;
let close = open + dict.get(open..).and_then(|d| d.iter().position(|&c| c == b']')).ok_or_else(|| bad("a layer's form box isn't an array"))? + 1;
patch.replace(start + open, start + close, UNBOXED.to_vec());
Ok(())
}
/// The `/Order` entries of `parent`'s sublayers (the top-level layers for none), the top one first
/// as Layers panels list them, each followed by an array of its own sublayers when it has some.
fn order(children: &HashMap<Option<usize>, Vec<usize>>, groups: &HashMap<usize, u32>, parent: Option<usize>) -> String {
let mut out = vec![];
for &i in children.get(&parent).into_iter().flatten().rev() {
let Some(g) = groups.get(&i) else { continue };
out.push(format!("{g} 0 R"));
if children.contains_key(&Some(i)) {
out.push(format!("[{}]", order(children, groups, Some(i))));
}
}
out.join(" ")
}
+18 -6
View File
@@ -537,14 +537,23 @@ struct Frame {
children: Vec<Arc<Node>>,
/// The first optional content group entered inside (where the frame's art goes).
group: Option<usize>,
/// The group each child was drawn in, where the frame's art goes when the frame dissolves
/// into its parent (a layer's form drawing its sublayers' forms).
child_groups: Vec<Option<usize>>,
}
impl Frame {
fn new(kind: FrameKind) -> Self {
Self { kind, children: vec![], group: None }
Self { kind, children: vec![], group: None, child_groups: vec![] }
}
}
/// A dissolving frame's `children`, each with the group it was drawn in (`groups`, else the
/// frame's `group`).
fn grouped(children: Vec<Arc<Node>>, groups: Vec<Option<usize>>, group: Option<usize>) -> impl Iterator<Item = (Arc<Node>, Option<usize>)> {
children.into_iter().zip(groups.into_iter().map(move |g| g.or(group)).chain(std::iter::repeat(group)))
}
/// Glyphs drawn consecutively with the same paint, merged into one path.
struct GlyphRun {
path: BezPath,
@@ -846,8 +855,11 @@ impl<'p> Builder<'p> {
// A frame's art goes where its first art was drawn (a clip can end in a later group).
if root {
self.root_groups.push(group.or(current));
} else if f.group.is_none() {
f.group = group.or(current);
} else {
f.child_groups.push(group.or(current));
if f.group.is_none() {
f.group = group.or(current);
}
}
}
@@ -925,7 +937,7 @@ impl<'p> Builder<'p> {
let node = match f.kind {
FrameKind::Root => None,
FrameKind::Skip => {
f.children.into_iter().for_each(|c| self.emit(c, group));
grouped(f.children, f.child_groups, group).for_each(|(c, g)| self.emit(c, g));
None
}
FrameKind::Clip(clip) => {
@@ -934,7 +946,7 @@ impl<'p> Builder<'p> {
None
} else if noop.is_some_and(|r| bounds(&f.children).is_some_and(|b| contains(r, b))) {
// A rectangle around all of its art (a form's box) clips nothing.
f.children.into_iter().for_each(|c| self.emit(c, group));
grouped(f.children, f.child_groups, group).for_each(|(c, g)| self.emit(c, g));
None
} else {
let mut ch = vec![Arc::new(*clip)];
@@ -957,7 +969,7 @@ impl<'p> Builder<'p> {
if children.is_empty() {
None
} else if plain {
children.into_iter().for_each(|c| self.emit(c, group));
grouped(children, f.child_groups, group).for_each(|(c, g)| self.emit(c, g));
None
} else if let [only] = children.as_slice()
&& !only.is_container()
+1 -1
View File
@@ -10,7 +10,7 @@
//! text in embedded subset fonts (Advanced). Colours are converted, tagged with ICC profiles and
//! given an output intent as the Output settings say. Hidden objects,
//! guides and template layers are skipped, and so are non-printing layers unless asked for.
//! Top-level layers can be PDF layers (optional content groups with their visibility, print
//! Layers and sublayers can be PDF layers (optional content groups with their visibility, print
//! state and lock), and overprinting fills and strokes overprint (Advanced).
//! Each page is its artboard (the trim box) grown by the bleed (the bleed box) and by the
//! printer's marks around it (the media box), drawn in Registration. [`PdfSettings`] is the Save PDF
+2 -2
View File
@@ -226,7 +226,7 @@ pub struct PdfSettings {
pub fast_web_view: bool,
/// The app opens the written file (frontends only; the writer ignores it).
pub view_after_saving: bool,
/// Write top-level layers as PDF layers (optional content).
/// Write layers and sublayers as PDF layers (optional content).
pub create_layers: bool,
/// Keep the layers whose Print option is off (they are left out otherwise, unless
/// `create_layers` is on).
@@ -449,7 +449,7 @@ impl PdfSettings {
within("advanced.fontSubsetPercent", self.advanced.font_subset_percent, 0.0, 100.0, "%")
}
/// Top-level layers are written as PDF layers: asked for, at a version that has them.
/// Layers and sublayers are written as PDF layers: asked for, at a version that has them.
pub fn writes_layers(&self) -> bool {
self.create_layers && self.compatibility.has_layers()
}
+51
View File
@@ -131,6 +131,57 @@ fn pdf_layers_import_back_as_layers() {
}
}
/// The rows of `nodes` in paint order, depth first: `depth name visible` for layers, `depth fill`
/// for art.
fn tree(nodes: &[std::sync::Arc<Node>], depth: usize, out: &mut Vec<String>) {
for n in nodes {
match &n.kind {
NodeKind::Layer { children, .. } => {
out.push(format!("{depth} {} {}", n.name.clone().unwrap_or_default(), n.visible));
tree(children, depth + 1, out);
}
_ => out.push(format!("{depth} {:?}", n.appearance.fill().and_then(|f| f.paint.color()))),
}
}
}
/// Sublayers are PDF layers listed under their layer's, hidden ones off with their art, and they
/// import back as sublayers (#372: other apps read a `.ai` file's PDF part).
#[test]
fn sublayers_are_nested_pdf_layers_and_import_back() {
let mut d = Document::new(200.0, 100.0);
d.layers.clear();
let layer = |d: &mut Document, name: &str, visible: bool, children: Vec<Node>| {
let mut l = Node::layer(d.alloc_id(), name, LayerColor::Preset(0));
l.visible = visible;
if let NodeKind::Layer { children: c, .. } = &mut l.kind {
c.extend(children.into_iter().map(std::sync::Arc::new));
}
l
};
let deep = vec![rect(&mut d, 90.0, GREEN)];
let deep = layer(&mut d, "Deep", true, deep);
let sub = vec![rect(&mut d, 50.0, BLUE), deep];
let sub = layer(&mut d, "Sub", false, sub);
let main = vec![rect(&mut d, 10.0, RED), sub];
let main = layer(&mut d, "Main", true, main);
d.layers.push(main.into());
let r = export(&d, json!({"createLayers": true, "compression": {"compressText": false}}));
oc_properties(&r.bytes, None, |props, xref| {
let props = props.expect("/OCProperties");
assert_eq!(names(xref, props.get(b"OCGs")), ["Main", "Sub", "Deep"]);
assert_eq!(names(xref, props.get::<Dict<'_>>(b"D").unwrap().get(b"OFF")), ["Sub"]);
});
let text = String::from_utf8_lossy(&r.bytes);
let order = text.split("/Order").nth(1).and_then(|o| o.split("]/").next()).unwrap().to_string();
assert_eq!(order.matches('[').count(), 3, "each layer's sublayers in an array after it: {order}");
let mut got = vec![];
tree(&import(&r.bytes).unwrap().layers, 0, &mut got);
// Paint order, as it was.
let fill = |depth, c: Color| format!("{depth} {:?}", Some(c));
assert_eq!(got, ["0 Main true".to_string(), fill(1, RED), "1 Sub false".into(), fill(2, BLUE), "2 Deep true".into(), fill(3, GREEN)]);
}
#[test]
fn identical_layers_stay_apart() {
let mut d = Document::new(200.0, 100.0);
+14
View File
@@ -68,6 +68,20 @@ fn wrapped_lines_get_one_tspan_each() {
assert!(!export(&d, &ExportOptions::default()).contains("text-anchor"));
}
#[test]
fn vertically_aligned_area_type_exports_where_it_is_drawn() {
let top = area_doc(vec![run("alpha beta", style(12.0))], 200.0, Justify::Left);
let mut centred = top.clone();
let id = centred.layers[0].children().unwrap()[0].id;
if let Some(NodeKind::Text(t)) = centred.node_mut(id).map(|n| &mut n.kind) {
t.area.vertical_align = vectorcraft_doc::VerticalAlign::Center;
}
let y = |d: &Document| attr(tspans(&export(d, &ExportOptions::default()))[0], "y").unwrap();
let (yt, yc) = (y(&top), y(&centred));
// The 160 pt frame holds one 12 pt line: centring moves it down about (160 - 14.4) / 2.
assert!(yc - yt > 60.0 && yc - yt < 80.0, "{yt} → {yc}");
}
#[test]
fn rich_text_writes_spacing_shift_and_scale() {
let shifted = CharStyle { baseline_shift: 4.0, ..style(12.0) };
+11 -1
View File
@@ -112,7 +112,17 @@ pub fn rich_session() -> Session {
exec(&mut s, "effect.apply", json!({"effect": "distort.roughen", "params": {"size": 3, "detail": 5, "seed": 7}}));
let l = id_of(&exec(&mut s, "shape.line", json!({"x1": 20, "y1": 300, "x2": 200, "y2": 350})));
exec(&mut s, "stroke.set", json!({"weight": 3, "endArrow": "Arrow"}));
let _ = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 300, "text": "VectorCraft", "size": 30})));
let tx = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 300, "text": "VectorCraft", "size": 30})));
// A non-default paragraph composer, so format round trips cover it.
exec(&mut s, "text.setFormat", json!({"ids": [tx.0], "composer": "singleLine"}));
// Area type with non-default Area Type Options (vertical alignment, inset).
let area = id_of(&exec(
&mut s,
"text.create",
json!({"x": 250, "y": 340, "text": "Centred area type", "size": 12, "area": {"width": 120, "height": 50}}),
));
select(&mut s, &[area]);
exec(&mut s, "text.areaOptions", json!({"verticalAlign": "center", "inset": 2}));
exec(&mut s, "layer.new", json!({"name": "Top"}));
let d = rect(&mut s, 350.0, 200.0, 80.0, 80.0);
let e = ellipse(&mut s, 380.0, 230.0, 80.0, 80.0);
+122 -38
View File
@@ -1,9 +1,17 @@
//! Every-line composer: a Knuth–Plass style total-fit line breaker for justified paragraphs.
//! Every-line composer: a Knuth–Plass style total-fit line breaker.
//!
//! Boxes are the paragraph's glyphs, glue is its spaces (word spacing may stretch to 150% and
//! shrink to 80%), and penalties are break opportunities after hyphens/dashes/CJK and at
//! hyphenation points. The breaks minimise the sum of squared (badness + penalty) demerits over
//! the whole paragraph, so loose lines are traded for evenly spaced ones.
//! Boxes are the paragraph's glyphs, glue is its spaces, and penalties are break opportunities
//! after hyphens/dashes/CJK and at hyphenation points. The breaks minimise the sum of squared
//! (badness + penalty) demerits over the whole paragraph, plus a demerit when neighbouring lines
//! fall in fitness classes more than one apart (a tight line next to a loose one).
//!
//! - **Justified** lines: word spacing may stretch to 150% and shrink to 80%; the badness comes
//! from the stretch/shrink ratio, so loose lines are traded for evenly spaced ones.
//! - **Ragged** lines (left/centre/right aligned): spaces keep their width, so a line never
//! shrinks (it must fit). The badness comes from the line's leftover space measured against a
//! rag zone of a sixth of the line width, so the rag is even rather than full lines followed by
//! a short one, and hyphenating costs less. The last line costs nothing unless it is shorter
//! than a third of the width (a word or two left dangling).
use crate::shape::SGlyph;
@@ -12,6 +20,21 @@ const SHRINK: f64 = 0.2;
const HYPHEN_PENALTY: f64 = 50.0;
const DOUBLE_HYPHEN_DEMERITS: f64 = 3000.0;
const LINE_PENALTY: f64 = 10.0;
/// Demerits for adjacent lines whose fitness classes differ by more than one.
const ADJ_DEMERITS_JUSTIFIED: f64 = 10_000.0;
const ADJ_DEMERITS_RAGGED: f64 = 1_000.0;
/// Ragged lines only gain from hyphenation by filling the rag, so it costs less than in
/// justified text (where it also evens the word spacing).
const HYPHEN_PENALTY_RAGGED: f64 = 25.0;
/// Ragged text: leftover space is measured in units of this fraction of the line width.
const RAG_ZONE: f64 = 1.0 / 6.0;
/// Ragged text: a last line shorter than this fraction of the width is penalised, by how much
/// shorter it is in units of `SHORT_LAST_ZONE` of the width.
const SHORT_LAST: f64 = 1.0 / 3.0;
const SHORT_LAST_ZONE: f64 = 1.0 / 3.0;
/// Give up (fall back to the single-line composer) beyond this many active breakpoints.
const MAX_ACTIVE: usize = 4096;
const EPS: f64 = 1e-6;
/// A place a line may end: glyph index `end` (exclusive), plus the width of the hyphen that is
/// added when breaking there (0 = no hyphen).
@@ -21,24 +44,56 @@ pub(crate) struct Breakpoint {
pub hyphen: f64,
}
/// How a paragraph is composed.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Params {
/// The last line is justified too (Justify All).
pub justify_last: bool,
/// Left/centre/right aligned text: spaces keep their width and lines are scored by their rag.
pub ragged: bool,
/// Maximum stretch ratio (justified) or leftover space in rag zones (ragged) of a line.
pub tolerance: f64,
/// Lines from this index on all have the same width, so their line numbers are interchangeable
/// (keeps the number of active breakpoints small).
pub uniform_from: usize,
}
struct Node {
pos: usize,
/// Line number of the next line, clamped to `uniform_from`.
line: usize,
fitness: u8,
demerits: f64,
hyphenated: bool,
prev: Option<usize>,
}
/// Fitness class 0 (tight) … 3 (very loose) of a line with adjustment ratio `r`.
fn fitness(r: f64, ragged: bool) -> u8 {
let bounds = if ragged { [0.15, 0.4, 0.75] } else { [-0.5, 0.5, 1.0] };
if r < bounds[0] {
0
} else if r <= bounds[1] {
1
} else if r <= bounds[2] {
2
} else {
3
}
}
/// Compose the paragraph `g` into lines. `width(k)` is the available width of line `k`;
/// `cands` are the break opportunities in increasing order (the paragraph end is added).
/// `justify_last`: the last line is justified too (Justify All). Returns `(end, hyphen)` per line,
/// or `None` if no set of breaks fits within `tolerance` (maximum stretch ratio).
/// `start_credit(i)` is the width a wrapped line starting at glyph `i` gives back (Mojikumi sets
/// an opening bracket there flush with the line's start); `cands` are the break opportunities
/// in increasing order (the paragraph end is added).
/// Returns `(end, hyphen)` per line, or `None` if no set of breaks fits within the tolerance
/// (the caller then falls back to single-line breaking).
pub(crate) fn compose(
g: &[SGlyph],
width: &dyn Fn(usize) -> f64,
start_credit: &dyn Fn(usize) -> f64,
cands: &[Breakpoint],
justify_last: bool,
tolerance: f64,
p: &Params,
) -> Option<Vec<(usize, bool)>> {
let n = g.len();
if n == 0 {
@@ -51,68 +106,93 @@ pub(crate) fn compose(
w[i + 1] = w[i] + gl.adv;
sp[i + 1] = sp[i] + if gl.is_space() { gl.adv } else { 0.0 };
}
if !w[n].is_finite() {
return None;
}
// Trailing spaces are dropped at a break.
let trim = |mut b: usize, a: usize| {
while b > a && g[b - 1].is_space() {
while b > a && g.get(b - 1).is_some_and(SGlyph::is_space) {
b -= 1;
}
b
};
let mut all: Vec<Breakpoint> = cands.iter().copied().filter(|c| c.end > 0 && c.end < n).collect();
all.push(Breakpoint { end: n, hyphen: 0.0 });
let mut nodes = vec![Node { pos: 0, line: 0, demerits: 0.0, hyphenated: false, prev: None }];
let (adj_demerits, hyphen_penalty) =
if p.ragged { (ADJ_DEMERITS_RAGGED, HYPHEN_PENALTY_RAGGED) } else { (ADJ_DEMERITS_JUSTIFIED, HYPHEN_PENALTY) };
let mut nodes = vec![Node { pos: 0, line: 0, fitness: 1, demerits: 0.0, hyphenated: false, prev: None }];
let mut active: Vec<usize> = vec![0];
for bp in &all {
let last = bp.end == n;
let mut best: Vec<(usize, f64, usize)> = vec![]; // (line, demerits, from)
let mut best: Vec<(usize, u8, f64, usize)> = vec![]; // (line, fitness, demerits, from)
let mut keep = Vec::with_capacity(active.len());
for &ai in &active {
let a = &nodes[ai];
let Some(a) = nodes.get(ai) else { continue };
let t = trim(bp.end, a.pos);
let natural = w[t] - w[a.pos] + bp.hyphen;
let spaces = sp[t] - sp[a.pos];
let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 };
let natural = w[t] - w[a.pos] - credit + bp.hyphen;
let lw = width(a.line);
let ratio = if natural < lw {
if last && !justify_last {
0.0
} else if spaces > 0.0 {
(lw - natural) / (spaces * STRETCH)
// Adjustment ratio, badness and whether the line ends the active node's reach.
let ratio = if p.ragged {
if natural > lw + EPS {
// Ragged lines never shrink; longer lines from this node only get worse.
continue;
}
if last && !p.justify_last {
((lw * SHORT_LAST - natural) / (lw * SHORT_LAST_ZONE).max(1.0)).max(0.0)
} else {
f64::INFINITY
(lw - natural).max(0.0) / (lw * RAG_ZONE).max(1.0)
}
} else if natural > lw {
if spaces > 0.0 { (lw - natural) / (spaces * SHRINK) } else { f64::NEG_INFINITY }
} else {
0.0
let spaces = sp[t] - sp[a.pos];
if natural < lw {
if last && !p.justify_last {
0.0
} else if spaces > 0.0 {
(lw - natural) / (spaces * STRETCH)
} else {
f64::INFINITY
}
} else if natural > lw {
if spaces > 0.0 { (lw - natural) / (spaces * SHRINK) } else { f64::NEG_INFINITY }
} else {
0.0
}
};
if ratio < -1.0 {
// Too long already; longer lines from this node only get worse.
continue;
}
keep.push(ai);
if ratio > tolerance && !(last && ratio.is_infinite() && justify_last) {
let free_last = last && (p.ragged || !p.justify_last);
if ratio > p.tolerance && !(last && (p.ragged || (ratio.is_infinite() && p.justify_last))) {
continue;
}
let badness = if ratio.is_finite() { (100.0 * ratio.abs().powi(3)).min(10_000.0) } else { 10_000.0 };
let penalty = if bp.hyphen > 0.0 { HYPHEN_PENALTY } else { 0.0 };
let penalty = if bp.hyphen > 0.0 { hyphen_penalty } else { 0.0 };
let mut d = (LINE_PENALTY + badness).powi(2) + penalty * penalty;
if bp.hyphen > 0.0 && a.hyphenated {
d += DOUBLE_HYPHEN_DEMERITS;
}
// A ragged last line's length says nothing about the rag: it keeps its neighbour's class.
let fit = if p.ragged && free_last { a.fitness } else { fitness(ratio, p.ragged) };
if a.prev.is_some() && fit.abs_diff(a.fitness) > 1 {
d += adj_demerits;
}
let total = a.demerits + d;
let line = a.line + 1;
match best.iter_mut().find(|b| b.0 == line) {
Some(b) if b.1 <= total => {}
Some(b) => *b = (line, total, ai),
None => best.push((line, total, ai)),
let line = (a.line + 1).min(p.uniform_from);
match best.iter_mut().find(|b| b.0 == line && b.1 == fit) {
Some(b) if b.2 <= total => {}
Some(b) => *b = (line, fit, total, ai),
None => best.push((line, fit, total, ai)),
}
}
active = keep;
for (line, demerits, from) in best {
nodes.push(Node { pos: bp.end, line, demerits, hyphenated: bp.hyphen > 0.0, prev: Some(from) });
for (line, fitness, demerits, from) in best {
nodes.push(Node { pos: bp.end, line, fitness, demerits, hyphenated: bp.hyphen > 0.0, prev: Some(from) });
active.push(nodes.len() - 1);
}
if active.is_empty() {
if active.is_empty() || active.len() > MAX_ACTIVE {
return None;
}
}
@@ -120,10 +200,14 @@ pub(crate) fn compose(
let mut out = vec![];
let mut cur = Some(end);
while let Some(i) = cur {
if nodes[i].prev.is_some() {
out.push((nodes[i].pos, nodes[i].hyphenated));
let nd = nodes.get(i)?;
if nd.prev.is_some() {
out.push((nd.pos, nd.hyphenated));
}
cur = nd.prev;
if out.len() > n {
return None;
}
cur = nodes[i].prev;
}
out.reverse();
Some(out)
+296 -29
View File
@@ -9,11 +9,11 @@ use vectorcraft_doc::{
};
use vectorcraft_geom::{ArcPath, PathData};
use crate::composer::{Breakpoint, compose};
use crate::composer::{Breakpoint, Params, compose};
use crate::fontdb::FontDb;
use crate::hyphen::hyphen_points;
use crate::shape::{Punct, SGlyph, Tcy, cap_x_heights, hyphen_glyph, is_cjk, no_line_end, no_line_start, punct, shape_range, style_metrics};
use crate::{Composer, FirstBaseline, LayoutOptions, LineInfo, OtFeatures, PositionedGlyph, TextLayout};
use crate::{Composer, FirstBaseline, LayoutOptions, LineInfo, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign};
const EPS: f64 = 1e-6;
@@ -127,6 +127,7 @@ pub fn layout(db: &FontDb, t: &TextObject) -> TextLayout {
inset: a.inset,
first_baseline: a.first_baseline,
first_baseline_min: a.first_baseline_min,
vertical_align: a.vertical_align,
..LayoutOptions::default()
};
layout_with(db, t, &opts)
@@ -183,9 +184,12 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay
} else {
t.wrap.clone()
};
let regions = Region::cells(&(to_lines * frame.to_bezpath()), opts, &wrap);
let mut regions = Region::cells(&(to_lines * frame.to_bezpath()), opts, &wrap);
cx.out.frames = regions.iter().map(|r| line_xf.transform_rect_bbox(r.cell)).collect();
flow(&mut cx, &paras, &t.para, Some(&regions));
if opts.vertical_align != VerticalAlign::Top {
align_vertically(&mut cx, &paras, &t.para, &mut regions);
}
}
TextKind::OnPath { path, .. } => on_path(&mut cx, &paras, t, path),
}
@@ -416,6 +420,125 @@ fn finish_bounds(out: &mut TextLayout) {
out.bounds = b.unwrap_or_default();
}
/// Space left in each cell after flowing top-aligned: (space above the first line's ascent, space
/// below the last line's descent, number of distinct baselines). Cells without lines are `None`.
fn cell_space(out: &TextLayout, regions: &[Region]) -> Vec<Option<(f64, f64, usize)>> {
regions
.iter()
.enumerate()
.map(|(ri, r)| {
let mut top = f64::INFINITY;
let mut bottom = f64::NEG_INFINITY;
let mut baselines: Vec<f64> = vec![];
for l in out.lines.iter().filter(|l| l.region == ri) {
top = top.min(l.baseline - l.ascent);
bottom = bottom.max(l.baseline + l.descent);
if !baselines.iter().any(|b| (b - l.baseline).abs() < 1e-6) {
baselines.push(l.baseline);
}
}
if baselines.is_empty() || !top.is_finite() || !bottom.is_finite() {
return None;
}
// Never negative: a full (or overflowing) cell stays where top alignment put it.
Some(((top - r.top()).max(0.0), (r.bottom() - bottom).max(0.0), baselines.len()))
})
.collect()
}
/// Area Type Options "Align" other than Top: move each cell's lines down. Rectangular cells
/// without text wrap shift their lines (centre: half the space left below the last line;
/// bottom: all of it; justify: the first line stays, each further line gets an equal share of it).
/// Other frames give lines different widths at different heights, so the text flows again with
/// each cell's lines started lower (or spaced wider) until it settles, at most eight passes; a
/// pass that would push text out of the frame is undone and retried with half the step.
fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: &mut [Region]) {
let align = cx.opts.vertical_align;
let plain = regions.iter().all(|r| (r.rect || r.polys.is_empty()) && r.wraps.is_empty());
if plain {
let space = cell_space(&cx.out, regions);
// Each distinct baseline's index within its cell, for justify.
let mut seen: Vec<Vec<f64>> = vec![vec![]; regions.len()];
let offs: Vec<f64> = cx
.out
.lines
.iter()
.map(|l| {
let Some(Some((_, below, n))) = space.get(l.region).copied() else { return 0.0 };
match align {
VerticalAlign::Top => 0.0,
VerticalAlign::Center => below * 0.5,
VerticalAlign::Bottom => below,
VerticalAlign::Justify => {
let Some(s) = seen.get_mut(l.region) else { return 0.0 };
let k = s.iter().position(|b| (b - l.baseline).abs() < 1e-6).unwrap_or_else(|| {
s.push(l.baseline);
s.len() - 1
});
if n > 1 { below * k as f64 / (n - 1) as f64 } else { 0.0 }
}
}
})
.collect();
for (l, d) in cx.out.lines.iter_mut().zip(&offs) {
l.baseline += d;
}
for g in &mut cx.out.glyphs {
let d = offs.get(g.line).copied().unwrap_or(0.0);
if d != 0.0 {
let m = Affine::translate((0.0, d));
g.outline.apply_affine(m);
g.xf = m * g.xf;
g.origin.y += d;
}
}
return;
}
let laid_out = |out: &TextLayout| out.lines.last().map_or(0, |l| l.end);
// How much of the measured space a pass takes up: halved after a pass that lost text.
let mut step = 1.0;
for _ in 0..8 {
let space = cell_space(&cx.out, regions);
let mut moved = false;
let saved: Vec<(f64, f64)> = regions.iter().map(|r| (r.shift, r.gap)).collect();
for (r, s) in regions.iter_mut().zip(&space) {
let Some((above, below, n)) = *s else { continue };
let (shift, gap) = match align {
VerticalAlign::Top => (r.shift, r.gap),
VerticalAlign::Center => (r.shift + (below - above) * 0.5 * step, r.gap),
VerticalAlign::Bottom => (r.shift + below * step, r.gap),
VerticalAlign::Justify if n > 1 => (r.shift, r.gap + below * step / (n - 1) as f64),
VerticalAlign::Justify => (r.shift, r.gap),
};
let (shift, gap) = (shift.clamp(0.0, r.cell.height().max(0.0)), gap.clamp(0.0, r.cell.height().max(0.0)));
if (shift - r.shift).abs() > 0.25 || (gap - r.gap).abs() > 0.01 {
moved = true;
}
r.shift = shift;
r.gap = gap;
}
if !moved {
return;
}
let before = laid_out(&cx.out);
let prev = (std::mem::take(&mut cx.out.glyphs), std::mem::take(&mut cx.out.lines), std::mem::replace(&mut cx.out.overflow, false));
flow(cx, paras, para, Some(regions));
if laid_out(&cx.out) < before {
// Text no longer fits (lines got narrower, or flow around a wrap object): undo the
// pass and try a smaller step.
(cx.out.glyphs, cx.out.lines, cx.out.overflow) = prev;
for (r, (shift, gap)) in regions.iter_mut().zip(saved) {
r.shift = shift;
r.gap = gap;
}
step *= 0.5;
if step < 0.1 {
return;
}
}
}
}
/// One cell of a flattened area-type frame (the whole frame, or one row/column of it).
struct Region {
/// The cell (frame bounds, or a grid cell of them).
@@ -427,6 +550,10 @@ struct Region {
rect: bool,
/// Text Wrap shapes: (polygons, offset, invert).
wraps: Vec<(Vec<Vec<Point>>, f64, bool)>,
/// Vertical alignment: how far below the top-aligned position the first line starts.
shift: f64,
/// Vertical justification: extra space added between consecutive lines.
gap: f64,
}
/// Flattened closed polygons of a path.
@@ -529,7 +656,7 @@ impl Region {
let x0 = bbox.x0 + c as f64 * (cw + gutter);
let y0 = bbox.y0 + r as f64 * (rh + gutter);
let cell = if rows * cols == 1 { bbox } else { Rect::new(x0, y0, x0 + cw, y0 + rh) };
out.push(Region { cell, inset: opts.inset.max(0.0), polys: polys.clone(), rect, wraps: wraps.clone() });
out.push(Region { cell, inset: opts.inset.max(0.0), polys: polys.clone(), rect, wraps: wraps.clone(), shift: 0.0, gap: 0.0 });
}
}
out
@@ -674,9 +801,9 @@ impl Pen<'_> {
loop {
let r = regions.get(self.ri)?;
let mut baseline = match self.prev {
None if self.model == LeadingModel::EmBoxTop => r.top() + est.top.max(self.fb_min),
None => r.top() + est.first_baseline(self.fb, self.fb_min),
Some(b) => self.next_baseline(b, est),
None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min),
None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min),
Some(b) => self.next_baseline(b, est) + r.gap,
};
loop {
if baseline + est.desc > r.bottom() + 0.01 {
@@ -761,10 +888,15 @@ fn break_line(text: &str, g: &[SGlyph], i: usize, width: f64, hyphenate: bool, b
let mut j = i;
while j < g.len() {
let gl = &g[j];
if j > i && !gl.is_space() && x + gl.adv > width + EPS {
let mut cluster_end = j + 1;
while g.get(cluster_end).is_some_and(|next| next.byte == gl.byte) {
cluster_end += 1;
}
let cluster_width: f64 = g[j..cluster_end].iter().map(|glyph| glyph.adv).sum();
if j > i && !gl.is_space() && x + cluster_width > width + EPS {
// It ends the line with the spaces after it.
if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, j) && g.get(j + 1).is_none_or(|n| n.byte != gl.byte) {
let mut end = j + 1;
if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, cluster_end - 1) {
let mut end = cluster_end;
while g.get(end).is_some_and(SGlyph::is_space) {
end += 1;
}
@@ -772,17 +904,18 @@ fn break_line(text: &str, g: &[SGlyph], i: usize, width: f64, hyphenate: bool, b
}
break;
}
x += gl.adv;
if gl.break_after() && kinsoku_allows(g, j) {
if gl.is_soft_hyphen() {
if x + hyphen_glyph(gl).adv <= width + EPS {
last_break = Some((j + 1, true));
x += cluster_width;
let last = &g[cluster_end - 1];
if last.break_after() && kinsoku_allows(g, cluster_end - 1) {
if last.is_soft_hyphen() {
if x + hyphen_glyph(last).adv <= width + EPS {
last_break = Some((cluster_end, true));
}
} else {
last_break = Some((j + 1, false));
last_break = Some((cluster_end, false));
}
}
j += 1;
j = cluster_end;
}
if j >= g.len() {
return (g.len(), false);
@@ -805,14 +938,12 @@ fn break_line(text: &str, g: &[SGlyph], i: usize, width: f64, hyphenate: bool, b
}
}
}
// Don't separate a cluster's glyphs.
let (mut end, hy) = match last_break {
// Break candidates and greedy overflow are cluster boundaries; hyphenation also returns only
// cluster starts, so the resulting end always keeps each source cluster together.
let (end, hy) = match last_break {
Some(b) if b.0 > i => b,
_ => (j, false),
};
while end > i + 1 && end < g.len() && g[end].byte == g[end - 1].byte {
end -= 1;
}
(end, hy)
}
@@ -835,6 +966,123 @@ fn kinsoku_between(before: char, after: Option<char>) -> bool {
!no_line_end(before) && after.is_none_or(|c| !no_line_start(c))
}
#[cfg(test)]
mod wrapping_tests {
use super::*;
use std::sync::Arc;
fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec<SGlyph> {
// The face is only a required SGlyph field here; advances and cluster boundaries below are
// entirely synthetic, so the regressions don't depend on a particular font's shaping.
static DB: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
let db = DB.get_or_init(|| FontDb::with_font_dirs(vec![]));
let face = db.face("Source Sans 3", "Regular").expect("bundled test face");
specs
.iter()
.map(|&(byte, len, adv, ch)| SGlyph {
face: Arc::clone(&face),
gid: 0,
byte,
len,
run: 0,
adv,
dx: 0.0,
dy: 0.0,
sx: 1.0,
sy: 1.0,
bshift: 0.0,
rotation: 0.0,
ascent: 8.0,
descent: 2.0,
leading: 0.0,
cap: 6.0,
xh: 4.0,
ch,
tcy: None,
lead: 0.0,
level: unicode_bidi::Level::ltr(),
})
.collect()
}
fn source_range(glyphs: &[SGlyph], start: usize, end: usize) -> Range<usize> {
let first = glyphs.get(start).expect("nonempty source range");
let last = glyphs.get(end - 1).expect("nonempty source range");
first.byte..last.byte + last.len
}
#[test]
fn greedy_wrap_keeps_an_oversized_first_cluster_and_its_source_range() {
let text = "بَت";
let glyphs = synthetic_glyphs(&[(0, 4, 2.0, 'ب'), (0, 4, 2.0, 'ب'), (4, 2, 1.0, 'ت')]);
let (end, hyphenated) = break_line(text, &glyphs, 0, 3.0, false, Burasagari::None);
assert!(!hyphenated);
assert_eq!(end, 2, "oversized base-plus-mark cluster must stay together");
assert_eq!(source_range(&glyphs, 0, end), 0..4);
assert_eq!(glyphs.get(end).map(|g| g.byte), Some(4));
}
#[test]
fn greedy_wrap_keeps_an_oversized_cluster_after_a_line_start_atomic() {
let text = "بَتَث";
let glyphs = synthetic_glyphs(&[(0, 4, 1.0, 'ب'), (4, 4, 2.0, 'ت'), (4, 4, 2.0, 'ت'), (8, 2, 1.0, 'ث')]);
let (first_end, _) = break_line(text, &glyphs, 0, 3.0, false, Burasagari::None);
assert_eq!(first_end, 1);
assert_eq!(source_range(&glyphs, 0, first_end), 0..4);
let (second_end, hyphenated) = break_line(text, &glyphs, first_end, 3.0, false, Burasagari::None);
assert!(!hyphenated);
assert_eq!(second_end, 3, "oversized cluster at the next line start must stay together");
assert_eq!(source_range(&glyphs, first_end, second_end), 4..8);
assert_eq!(glyphs.get(second_end).map(|g| g.byte), Some(8));
}
#[test]
fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() {
let db = FontDb::global();
let Some(face) = db.face_covering('ب').filter(|face| face.covers('َ')) else {
// Arabic integration coverage depends on an installed font; synthetic tests above are
// the font-independent regression oracle.
return;
};
let text = "بَت";
let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size: 20.0, ..CharStyle::default() };
let bidi = para_bidi(text, None);
let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels);
let mut shaped = Vec::new();
shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &OtFeatures::default(), levels, &mut shaped);
let Some(first) = shaped.first() else { return };
let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count();
if first.byte != 0 || first_end < 2 || first_end >= shaped.len() {
return;
}
// Pick a narrow width that fits glyphs before one positive-advance glyph but not that next
// glyph. This ensures the old per-glyph loop would have returned inside the first cluster.
let mut prefix = shaped.first().map_or(0.0, |g| g.adv);
let width = (1..first_end).find_map(|k| {
let advance = shaped.get(k)?.adv;
if prefix > EPS && advance > EPS {
Some(prefix)
} else {
prefix += advance;
None
}
});
let Some(width) = width else { return };
let mut object = TextObject::point(Point::ZERO, text, style);
object.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, width, 100.0).to_path(0.1)) };
let result = layout_with(db, &object, &LayoutOptions::default());
let next_cluster_byte = shaped.get(first_end).map(|g| g.byte);
assert_eq!(result.lines.first().map(|line| line.end), next_cluster_byte);
}
}
#[cfg(test)]
#[test]
fn japanese_letters_for_the_latin_space_are_kana_kanji_and_marks_not_hangul_or_punctuation() {
@@ -914,14 +1162,18 @@ fn candidates(text: &str, g: &[SGlyph], hyphenate: bool) -> Vec<Breakpoint> {
v
}
/// Every-line composition of paragraph glyphs `sg` if applicable (justified area text with uniform
/// line metrics); `None` falls back to the greedy single-line composer.
fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>) -> Option<Vec<(usize, bool)>> {
let justified = !matches!(para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right);
/// Paragraphs longer than this (glyphs) are always broken line by line.
const MAX_COMPOSE_GLYPHS: usize = 200_000;
/// Every-line composition of paragraph glyphs `sg` if applicable (area text with uniform line
/// metrics, justified or ragged); `None` falls back to the greedy single-line composer.
fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>, rtl: bool) -> Option<Vec<(usize, bool)>> {
let ragged = matches!(para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right);
let composer = cx.opts.composer.unwrap_or(para.composer);
// A paragraph whose commas or full stops may hang is composed line by line (as the Japanese
// single-line composer does).
let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs);
if cx.opts.composer != Composer::EveryLine || !justified || pen.regions.is_none() || sg.len() < 2 || may_hang {
if composer != Composer::EveryLine || pen.regions.is_none() || sg.len() < 2 || sg.len() > MAX_COMPOSE_GLYPHS || may_hang {
return None;
}
let m = Metrics::of(&sg[0]);
@@ -948,9 +1200,21 @@ fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>) ->
}
let last = *widths.last()?;
let width = |k: usize| widths.get(k).copied().unwrap_or(last);
// Lines from `uniform_from` on are interchangeable (same width).
let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1);
let cands = candidates(cx.text, sg, para.hyphenate);
let justify_last = para.justify == Justify::JustifyAll;
compose(sg, &width, &cands, justify_last, 1.0).or_else(|| compose(sg, &width, &cands, justify_last, 4.0))
let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from };
// Ragged: first look for breaks that leave at most one rag zone (a sixth of the width) on
// each line, then accept any lines that fit.
let (strict, loose) = if ragged { (1.0, f64::INFINITY) } else { (1.0, 4.0) };
// The same rule as the line loop below: an opening bracket starting a wrapped line gives up
// the space before it.
let start_credit = |i: usize| {
let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf;
sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0)
};
compose(sg, &width, &start_credit, &cands, &params(strict)).or_else(|| compose(sg, &width, &start_credit, &cands, &params(loose)))
}
fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Option<&[Region]>) {
@@ -985,7 +1249,7 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
pen.pending += para.space_before;
}
let n = sg.len();
let composed = compose_para(cx, &sg, para, &pen);
let composed = compose_para(cx, &sg, para, &pen, rtl);
let mut li_para = 0;
let mut i = 0;
loop {
@@ -1189,6 +1453,7 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
glyph_start,
glyph_end: cx.out.glyphs.len(),
avail: if regions.is_some() { (ax0, ax1) } else { (start_x, x_end) },
region: if regions.is_some() { pen.ri } else { 0 },
});
pen.settled(baseline, m);
// Further spans of this line band share the settled baseline.
@@ -1265,6 +1530,7 @@ fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, path: &Path
glyph_start: 0,
glyph_end: 0,
avail: (0.0, 0.0),
region: 0,
});
return;
}
@@ -1349,6 +1615,7 @@ fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, path: &Path
glyph_start: 0,
glyph_end: cx.out.glyphs.len(),
avail: (0.0, ap.len()),
region: 0,
});
}
+11 -12
View File
@@ -31,17 +31,10 @@ use kurbo::{Affine, BezPath, Point, Rect, Vec2};
pub use layout::{layout, layout_with};
pub use vectorcraft_doc::TextObject;
pub use vectorcraft_doc::FirstBaseline;
pub use vectorcraft_doc::{FirstBaseline, VerticalAlign};
/// Paragraph composer (Paragraph panel menu).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Composer {
/// Break each line as soon as it is full.
SingleLine,
/// Knuth–Plass total fit over the paragraph (justified area text only).
#[default]
EveryLine,
}
/// Paragraph composer; stored per text object in [`vectorcraft_doc::ParaStyle::composer`].
pub use vectorcraft_doc::Composer;
/// Layout parameters that the document model doesn't store per object (Area Type Options,
/// composer, OpenType features). [`layout`] takes rows/columns/inset/first baseline from the object.
@@ -57,7 +50,10 @@ pub struct LayoutOptions {
pub first_baseline: FirstBaseline,
/// Minimum first-baseline offset in points.
pub first_baseline_min: f64,
pub composer: Composer,
/// Vertical alignment of the lines in each row/column (Area Type Options "Align").
pub vertical_align: VerticalAlign,
/// Overrides the object's paragraph composer (`None` = use `ParaStyle::composer`).
pub composer: Option<Composer>,
pub features: OtFeatures,
}
@@ -70,7 +66,8 @@ impl Default for LayoutOptions {
inset: 0.0,
first_baseline: FirstBaseline::Ascent,
first_baseline_min: 0.0,
composer: Composer::EveryLine,
vertical_align: VerticalAlign::Top,
composer: None,
features: OtFeatures::default(),
}
}
@@ -130,6 +127,8 @@ pub struct LineInfo {
/// Horizontal span available to the line (frame span minus indents; the content extent for
/// point type). Used for hit testing across columns.
pub avail: (f64, f64),
/// Area type: index of the frame cell ([`TextLayout::frames`]) the line sits in (0 otherwise).
pub region: usize,
}
#[derive(Clone, Debug, Default)]
+49 -5
View File
@@ -196,20 +196,43 @@ pub(crate) fn shape_range(
levels: &[Level],
out: &mut Vec<SGlyph>,
) {
if text.get(range.clone()).is_none() || range.is_empty() {
return;
}
let level_at = |i: usize| levels.get(i - range.start).copied().unwrap_or_else(Level::ltr);
let output_start = out.len();
// Text runs also carry non-shaping attributes (fill, stroke, etc.). Coalesce adjacent equal
// styles so an editor split does not become an accidental OpenType shaping boundary. Keep
// original run spans: each emitted cluster is attributed by its source byte below.
let mut spans: Vec<(Range<usize>, &CharStyle, Range<usize>)> = Vec::new();
for (ri, (rr, st)) in runs.iter().enumerate() {
let a = rr.start.max(range.start);
let b = rr.end.min(range.end);
if a >= b {
if a >= b || text.get(a..b).is_none() {
continue;
}
if let Some((previous, previous_style, source_runs)) = spans.last_mut()
&& previous.end == a
&& *previous_style == *st
{
previous.end = b;
source_runs.end = ri + 1;
continue;
}
spans.push((a..b, *st, ri..ri + 1));
}
for (span, st, source_runs) in spans {
let a = span.start;
let b = span.end;
let Some(primary) = db.face(&st.font_family, &st.font_style) else { continue };
let pmap = primary.skrifa().map(|f| f.charmap());
// Synthesized Small Caps shape lowercase letters separately (as smaller capitals).
let small_caps = st.small_caps.is_some() && !st.all_caps;
// Split into segments by font coverage (and case, for Small Caps).
let mut seg = Segment { range: a..a, run: ri, st, face: primary.clone(), small: false, level: level_at(a) };
let group_output_start = out.len();
let mut seg = Segment { range: a..a, run: source_runs.start, st, face: primary.clone(), small: false, level: level_at(a) };
let mut cache: Vec<(char, Arc<FontFace>)> = Vec::new();
let mut script = Script::Common;
for (i, c) in text[a..b].char_indices() {
@@ -233,7 +256,7 @@ pub(crate) fn shape_range(
if (face.id() != seg.face.id() || small != seg.small || level != seg.level || script_change) && !is_mark(c) {
if i > seg.range.start {
seg.range.end = i;
shape_segment(text, &seg, feats, out);
shape_segment(text, &range, &seg, feats, out);
}
seg = Segment { range: i..i, face, small, level, ..seg };
}
@@ -243,7 +266,10 @@ pub(crate) fn shape_range(
}
if b > seg.range.start {
seg.range.end = b;
shape_segment(text, &seg, feats, out);
shape_segment(text, &range, &seg, feats, out);
}
for glyph in &mut out[group_output_start..] {
glyph.run = source_run_at(runs, &source_runs, glyph.byte).unwrap_or(source_runs.start);
}
}
// Right-to-left segments come out of the shaper in visual order: back to logical order for
@@ -255,6 +281,15 @@ pub(crate) fn shape_range(
}
}
/// Index in the original run list containing `byte`, limited to one coalesced shaping span.
/// Source runs are ordered and non-overlapping; partitioning keeps attribution bounded when a
/// document contains many adjacent style runs.
fn source_run_at(runs: &[(Range<usize>, &CharStyle)], span: &Range<usize>, byte: usize) -> Option<usize> {
let source = runs.get(span.clone())?;
let i = source.partition_point(|(range, _)| range.end <= byte);
source.get(i).filter(|(range, _)| range.contains(&byte)).map(|_| span.start + i)
}
/// The script `c` is shaped in: Japanese and Chinese text mixes Han, Hiragana, Katakana and
/// Bopomofo, shaped together (splitting them would cost a shaper call per change of script).
fn shaping_script(c: char) -> Script {
@@ -281,7 +316,7 @@ fn is_mark(c: char) -> bool {
|| matches!(c, '\u{200D}' | '\u{FE00}'..='\u{FE0F}')
}
fn shape_segment(text: &str, seg: &Segment, feats: &OtFeatures, out: &mut Vec<SGlyph>) {
fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFeatures, out: &mut Vec<SGlyph>) {
let Segment { range, run, st, face, small, level } = seg;
let (range, run, small) = (range.clone(), *run, *small);
let text_seg = &text[range.clone()];
@@ -320,6 +355,15 @@ fn shape_segment(text: &str, seg: &Segment, feats: &OtFeatures, out: &mut Vec<SG
}
buf.set_direction(if level.is_rtl() { Direction::RightToLeft } else { Direction::LeftToRight });
buf.guess_segment_properties();
// Harfrust keeps this Unicode context for joining/positional shaping, but does not emit
// glyphs for it. This retains context at real style/font segmentation boundaries without
// shaping across those boundaries or claiming cross-style ligatures/mark attachment.
if let Some(pre) = text.get(context.start..range.start) {
buf.set_pre_context(pre);
}
if let Some(post) = text.get(range.end..context.end) {
buf.set_post_context(post);
}
let feats: Vec<Feature> = feats.resolve(st);
let gb = shaper.shape(buf, ShapeOptions::new().features(&feats));
for (info, pos) in gb.glyph_infos().iter().zip(gb.glyph_positions()) {
+103 -5
View File
@@ -1,12 +1,42 @@
//! Direction, source-cluster and editing regressions; no RTL font assets required.
use super::*;
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{CharStyle, TextKind};
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, TextKind, TextRun};
fn text_layout(s: &str) -> TextLayout {
layout(FontDb::global(), &TextObject::point(Point::ZERO, s, CharStyle::default()))
}
fn arabic_test_face(test: &str) -> Option<Arc<FontFace>> {
let db = FontDb::global();
let face = ["Geeza Pro", "Arial", "Noto Sans Arabic"]
.into_iter()
.filter_map(|name| db.face(name, "Regular"))
.find(|face| face.covers('ب') && face.covers('ل') && face.covers('ا'));
if let Some(face) = &face {
let path = face.path().map_or_else(|| "bundled font".to_string(), |p| p.display().to_string());
eprintln!("ASSERTIONS RUN: {test}; Arabic font {} {} ({path})", face.family, face.style);
} else {
eprintln!("SKIPPED: {test}; no installed candidate font covers Arabic beh, lam, and alef");
}
face
}
fn arabic_style(face: &FontFace) -> CharStyle {
CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), ..CharStyle::default() }
}
fn assert_same_shaped_glyphs(left: &TextLayout, right: &TextLayout) {
assert_eq!(left.glyphs.len(), right.glyphs.len());
for (a, b) in left.glyphs.iter().zip(&right.glyphs) {
assert_eq!(
(a.gid, a.byte, a.len, a.font_id, a.advance, a.origin, a.xf, a.rtl),
(b.gid, b.byte, b.len, b.font_id, b.advance, b.origin, b.xf, b.rtl),
);
}
}
#[test]
fn hebrew_and_arabic_are_visually_rtl_with_exact_source_clusters() {
for s in ["שלום", "مرحبا"] {
@@ -85,10 +115,14 @@ fn hebrew_marks_stay_with_base_clusters() {
fn arabic_contextual_forms_and_lam_alef_use_the_shaper() {
let db = FontDb::global();
// Installed fonts are optional; no proprietary or test font is copied into the repo.
let face =
["Geeza Pro", "Arial", "Noto Sans Arabic"].into_iter().filter_map(|name| db.face(name, "Regular")).find(|f| f.covers('ل') && f.covers('ا'));
let Some(face) = face else { return };
let st = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), ..CharStyle::default() };
let Some(face) = arabic_test_face("arabic_contextual_forms_and_lam_alef_use_the_shaper") else { return };
let st = arabic_style(&face);
let pair = "لا";
let lam_alef = layout(db, &TextObject::point(Point::ZERO, pair, st.clone()));
let ligature = lam_alef.glyphs.iter().find(|g| g.byte == 0 && g.len == pair.len());
assert!(ligature.is_some(), "lam-alef must retain one cluster spanning both source letters: {lam_alef:?}");
assert_ne!(ligature.unwrap().gid, face.glyph_for('ل'), "lam-alef must use a shaped glyph");
for s in ["سلام", "שלום سلام"] {
let l = layout(db, &TextObject::point(Point::ZERO, s, st.clone()));
let arabic: Vec<_> = l.glyphs.iter().filter(|g| s.get(g.byte..).is_some_and(|t| t.starts_with(['س', 'ل', 'ا', 'م']))).collect();
@@ -100,6 +134,70 @@ fn arabic_contextual_forms_and_lam_alef_use_the_shaper() {
}
}
#[test]
fn identical_style_arabic_run_splits_keep_joining_and_source_attribution() {
let db = FontDb::global();
let Some(face) = arabic_test_face("identical_style_arabic_run_splits_keep_joining_and_source_attribution") else { return };
let style = arabic_style(&face);
let text = "بب";
let mut single = TextObject::point(Point::ZERO, text, style.clone());
single.runs = vec![TextRun { text: text.to_string(), style: style.clone() }];
let mut split = TextObject::point(Point::ZERO, text, style.clone());
split.runs = vec![TextRun { text: "ب".into(), style: style.clone() }, TextRun { text: "ب".into(), style }];
let single = layout(db, &single);
let split = layout(db, &split);
assert!(single.glyphs.iter().any(|glyph| glyph.gid != face.glyph_for('ب')), "single run must exercise contextual beh forms");
assert_same_shaped_glyphs(&single, &split);
assert_eq!(split.glyphs.len(), 2, "beh-beh should remain two source clusters");
for glyph in &split.glyphs {
let expected_run = usize::from(glyph.byte >= "ب".len());
assert_eq!(glyph.run, expected_run, "source byte {} belongs to run {expected_run}", glyph.byte);
}
}
#[test]
fn different_style_arabic_boundary_receives_joining_context() {
let db = FontDb::global();
let Some(face) = arabic_test_face("different_style_arabic_boundary_receives_joining_context") else { return };
let style = arabic_style(&face);
let text = "بب";
let joined = layout(db, &TextObject::point(Point::ZERO, text, style.clone()));
assert!(joined.glyphs.iter().any(|glyph| glyph.gid != face.glyph_for('ب')), "reference must use contextual beh forms");
let mut split = TextObject::point(Point::ZERO, text, style.clone());
split.runs =
vec![TextRun { text: "ب".into(), style: style.clone() }, TextRun { text: "ب".into(), style: CharStyle { size: style.size * 1.5, ..style } }];
let split = layout(db, &split);
assert_eq!(joined.glyphs.len(), 2);
assert_eq!(split.glyphs.len(), 2);
for glyph in &joined.glyphs {
let actual = split.glyphs.iter().find(|other| other.byte == glyph.byte).expect("same source cluster");
assert_eq!(actual.gid, glyph.gid, "joining form changed at style boundary for byte {}", glyph.byte);
assert_eq!(actual.len, glyph.len);
assert_eq!(actual.run, usize::from(glyph.byte >= "ب".len()));
}
}
#[test]
fn shape_range_handles_empty_runs_and_selected_utf8_subranges() {
let db = FontDb::global();
let style = CharStyle::default();
let text = "Aب";
let runs = [(0..text.len(), &style)];
let mut glyphs = Vec::new();
shape::shape_range(db, text, 0..0, &runs, &OtFeatures::default(), &[], &mut glyphs);
shape::shape_range(db, text, 0..text.len(), &[], &OtFeatures::default(), &[], &mut glyphs);
shape::shape_range(db, text, 1..2, &runs, &OtFeatures::default(), &[], &mut glyphs);
assert!(glyphs.is_empty());
shape::shape_range(db, text, 1..text.len(), &runs, &OtFeatures::default(), &[], &mut glyphs);
assert!(!glyphs.is_empty());
assert!(glyphs.iter().all(|g| (1..text.len()).contains(&g.byte)));
}
#[test]
fn bidi_isolates_numbers_and_brackets_keep_valid_clusters() {
for s in ["שלום (123)", "مرحبا (Rust 42)", "English \u{2067}שלום 123\u{2069} end"] {
+311 -15
View File
@@ -227,7 +227,7 @@ fn composer_lines_never_exceed_frame() {
for (hy, composer) in [(false, Composer::EveryLine), (true, Composer::EveryLine), (false, Composer::SingleLine), (true, Composer::SingleLine)] {
let mut t = area(&COPY.repeat(2), style(12.0), Rect::new(0.0, 0.0, 180.0, 2000.0), Justify::JustifyLeft);
t.para.hyphenate = hy;
let l = layout_with(db(), &t, &LayoutOptions { composer, ..Default::default() });
let l = layout_with(db(), &t, &LayoutOptions { composer: Some(composer), ..Default::default() });
assert!(l.lines.len() > 10);
for (i, li) in l.lines.iter().enumerate() {
assert!(li.x1 - li.x0 <= 180.0 + 1e-6, "{composer:?} hy={hy} line {i} too wide: {li:?}");
@@ -246,7 +246,7 @@ fn composer_lines_never_exceed_frame() {
fn every_line_composer_is_more_even() {
let t = area(&COPY.repeat(2), style(12.0), Rect::new(0.0, 0.0, 190.0, 2000.0), Justify::JustifyLeft);
let spread = |c: Composer| {
let l = layout_with(db(), &t, &LayoutOptions { composer: c, ..Default::default() });
let l = layout_with(db(), &t, &LayoutOptions { composer: Some(c), ..Default::default() });
// Worst word-space stretch (space glyph advance) over all justified lines.
let mut worst: f64 = 0.0;
for li in &l.lines[..l.lines.len() - 1] {
@@ -269,7 +269,7 @@ fn burasagari_keeps_the_every_line_composer_for_latin_text() {
// A measure where the two composers break the copy differently.
let mut t = area(&COPY.repeat(2), style(12.0), Rect::new(0.0, 0.0, 300.0, 4000.0), Justify::JustifyLeft);
let ends = |t: &TextObject, c: Composer| {
let l = layout_with(db(), t, &LayoutOptions { composer: c, ..Default::default() });
let l = layout_with(db(), t, &LayoutOptions { composer: Some(c), ..Default::default() });
l.lines.iter().map(|li| li.glyph_end).collect::<Vec<_>>()
};
let every_line = ends(&t, Composer::EveryLine);
@@ -278,6 +278,102 @@ fn burasagari_keeps_the_every_line_composer_for_latin_text() {
assert_eq!(ends(&t, Composer::EveryLine), every_line);
}
/// Width of `s` set on one line.
fn natural_width(s: &str, size: f64) -> f64 {
let l = layout(db(), &TextObject::point(Point::ZERO, s, style(size)));
l.lines[0].x1 - l.lines[0].x0
}
/// The text of each line.
fn line_texts(t: &TextObject, l: &TextLayout) -> Vec<String> {
let text = t.plain_text();
l.lines.iter().map(|li| text[li.start..li.end].trim_end().to_string()).collect()
}
/// Ragged text: Every-line breaks before a word that would fit, to avoid leaving a lone short
/// word on the last line (single-line keeps filling the first line). Auto alignment is ragged
/// too, in either paragraph direction: set right to left, the lines break the same and stay
/// flush right.
#[test]
fn every_line_composer_balances_ragged_lines() {
use vectorcraft_doc::ParaDirection;
const S: &str = "Destroy all creatures with toughness X or less.";
let w = natural_width("Destroy all creatures with toughness X or", 12.0) + 2.0;
assert!(w < natural_width(S, 12.0), "the sentence needs two lines");
let cases = [
(Justify::Left, None),
(Justify::Center, None),
(Justify::Right, None),
(Justify::Auto, None),
(Justify::Auto, Some(ParaDirection::RightToLeft)),
(Justify::Left, Some(ParaDirection::RightToLeft)),
];
for (justify, direction) in cases {
let mut t = area(S, style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify);
t.para.direction = direction;
t.para.composer = Composer::SingleLine;
let greedy = line_texts(&t, &layout(db(), &t));
assert_eq!(greedy, ["Destroy all creatures with toughness X or", "less."], "{justify:?} {direction:?}");
t.para.composer = Composer::EveryLine;
let every = line_texts(&t, &layout(db(), &t));
assert_eq!(every, ["Destroy all creatures with toughness X", "or less."], "{justify:?} {direction:?}");
// Burasagari (new type's Standard) leaves Latin text to the every-line composer.
t.para.burasagari = vectorcraft_doc::Burasagari::Standard;
assert_eq!(line_texts(&t, &layout(db(), &t)), every, "{justify:?} {direction:?} with burasagari");
if (justify, direction) == (Justify::Auto, Some(ParaDirection::RightToLeft)) {
let l = layout(db(), &t);
assert!(l.lines.iter().all(|li| li.rtl && (li.x1 - w).abs() < 1e-6), "right to left Auto is flush right: {:?}", l.lines);
}
// The options override wins over the object's setting.
let forced = layout_with(db(), &t, &LayoutOptions { composer: Some(Composer::SingleLine), ..Default::default() });
assert_eq!(line_texts(&t, &forced), greedy);
}
}
/// Every-line evens the rag of a long ragged paragraph: the spread of the line ends is no worse
/// than greedy breaking, every line fits, and nothing is lost.
#[test]
fn every_line_composer_evens_the_rag() {
for (width, hy) in [(150.0, false), (190.0, false), (240.0, true), (310.0, false)] {
let mut t = area(&COPY.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), Justify::Left);
t.para.hyphenate = hy;
let rag = |c: Composer| {
let mut t = t.clone();
t.para.composer = c;
let l = layout(db(), &t);
assert!(!l.overflow);
for li in &l.lines {
assert!(li.x1 - li.x0 <= width + 1e-6, "{c:?} {width}: line too wide {li:?}");
}
let clusters: std::collections::BTreeSet<(usize, usize)> = l.glyphs.iter().filter(|g| g.len > 0).map(|g| (g.byte, g.len)).collect();
assert_eq!(clusters.iter().map(|c| c.1).sum::<usize>(), COPY.len() * 2, "every character placed");
// Leftover space of all lines but the last: its sum of squares (how ragged) and the
// sum of squared differences between neighbours (how jagged).
let slack: Vec<f64> = l.lines[..l.lines.len() - 1].iter().map(|li| width - (li.x1 - li.x0)).collect();
let jag: f64 = slack.windows(2).map(|p| (p[0] - p[1]).powi(2)).sum();
(slack.iter().map(|s| s * s).sum::<f64>(), jag, l.lines.len())
};
let ((kp, kp_jag, kp_lines), (greedy, greedy_jag, greedy_lines)) = (rag(Composer::EveryLine), rag(Composer::SingleLine));
assert!(kp <= greedy + 1e-6, "{width}: every-line rag {kp} vs greedy {greedy}");
assert!(kp_jag <= greedy_jag + 1e-6, "{width}: every-line jag {kp_jag} vs greedy {greedy_jag}");
assert!(kp_lines <= greedy_lines + 1, "{width}: {kp_lines} lines vs {greedy_lines}");
}
}
/// Single-line breaking is the greedy breaker: each line takes as many words as fit.
#[test]
fn single_line_composer_is_greedy() {
let width = 190.0;
let mut t = area(COPY, style(12.0), Rect::new(0.0, 0.0, width, 2000.0), Justify::Left);
t.para.composer = Composer::SingleLine;
let l = layout(db(), &t);
let lines = line_texts(&t, &l);
for pair in lines.windows(2) {
let next_word = pair[1].split(' ').next().unwrap();
assert!(natural_width(&format!("{} {next_word}", pair[0]), 12.0) > width - 1e-6, "{pair:?}");
}
}
#[test]
fn hyphenation_rules() {
assert_eq!(hyphen::hyphenate_word("typography"), "typo-gra-phy");
@@ -361,6 +457,201 @@ fn rows_and_columns_flow_in_order() {
}
}
// ---------- vertical alignment ----------
fn valign(a: VerticalAlign) -> LayoutOptions {
LayoutOptions { vertical_align: a, ..Default::default() }
}
/// (space above the first line's ascent, space below the last line's descent) in `0..h`.
fn block_space(l: &TextLayout, h: f64) -> (f64, f64) {
let (first, last) = (l.lines.first().unwrap(), l.lines.last().unwrap());
(first.baseline - first.ascent, h - (last.baseline + last.descent))
}
#[test]
fn vertical_align_center_bottom_and_justify_in_a_rectangle() {
let t = area("First line\nSecond line\nThird line", style(12.0), Rect::new(0.0, 0.0, 200.0, 300.0), Justify::Left);
let top = layout(db(), &t);
let (above, below) = block_space(&top, 300.0);
assert!(above.abs() < 1e-6 && below > 200.0);
let center = layout_with(db(), &t, &valign(VerticalAlign::Center));
let (a, b) = block_space(&center, 300.0);
assert!((a - b).abs() < 1e-6 && a > 100.0, "{a} {b}");
// The model field reaches layout().
let mut tc = t.clone();
tc.area.vertical_align = VerticalAlign::Center;
assert!((layout(db(), &tc).lines[0].baseline - center.lines[0].baseline).abs() < 1e-9);
// Lines, glyph origins, outlines and transforms move together.
let d = center.lines[0].baseline - top.lines[0].baseline;
for (g, h) in center.glyphs.iter().zip(&top.glyphs) {
assert!((g.origin.y - h.origin.y - d).abs() < 1e-9);
assert!((g.xf.translation().y - h.xf.translation().y - d).abs() < 1e-9);
if !h.outline.elements().is_empty() {
assert!((g.outline.bounding_box().y0 - h.outline.bounding_box().y0 - d).abs() < 1e-6);
}
}
assert!(center.bounds.y0 > top.bounds.y0 + 100.0);
let bottom = layout_with(db(), &t, &valign(VerticalAlign::Bottom));
let (a, b) = block_space(&bottom, 300.0);
assert!(b.abs() < 1e-6 && a > 200.0);
// Justify: the first line stays, the last one reaches the bottom, gaps are equal.
let just = layout_with(db(), &t, &valign(VerticalAlign::Justify));
let (a, b) = block_space(&just, 300.0);
assert!(a.abs() < 1e-6 && b.abs() < 1e-6, "{a} {b}");
let gaps: Vec<f64> = just.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect();
assert!(gaps.len() == 2 && (gaps[0] - gaps[1]).abs() < 1e-6 && gaps[0] > 100.0);
// A single line justifies to the top.
let one = area("Alone", style(12.0), Rect::new(0.0, 0.0, 200.0, 300.0), Justify::Left);
assert_eq!(layout_with(db(), &one, &valign(VerticalAlign::Justify)).lines[0].baseline, layout(db(), &one).lines[0].baseline);
// Inset: the space is measured inside it.
let inset = layout_with(db(), &t, &LayoutOptions { inset: 10.0, vertical_align: VerticalAlign::Bottom, ..Default::default() });
assert!(block_space(&inset, 290.0).1.abs() < 1e-6);
}
#[test]
fn vertical_align_leaves_overflowing_text_where_it_is() {
let text = COPY.repeat(4);
let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 200.0, 100.0), Justify::Left);
let top = layout(db(), &t);
assert!(top.overflow);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
let l = layout_with(db(), &t, &valign(a));
assert!(l.overflow);
assert_eq!(l.lines.len(), top.lines.len());
assert_eq!(l.lines.last().unwrap().end, top.lines.last().unwrap().end);
// A full cell has less than a line of space left: the lines barely move.
assert!(l.lines[0].baseline - top.lines[0].baseline < top.lines[0].ascent + top.lines[0].descent);
assert!(block_space(&l, 100.0).1 >= -1e-6);
}
}
#[test]
fn vertical_align_acts_on_each_column_on_its_own() {
// Enough text for column 1 and a few lines of column 2.
let t = area(COPY, style(12.0), Rect::new(0.0, 0.0, 420.0, 120.0), Justify::Left);
let opts = |a| LayoutOptions { columns: 2, gutter: 20.0, vertical_align: a, ..Default::default() };
let top = layout_with(db(), &t, &opts(VerticalAlign::Top));
let col = |l: &TextLayout, c: usize| l.lines.iter().filter(|li| li.region == c).cloned().collect::<Vec<_>>();
assert!(!top.overflow && !col(&top, 0).is_empty() && !col(&top, 1).is_empty());
assert!(col(&top, 1).iter().all(|li| li.x0 >= 220.0 - 1e-6));
let bottom = layout_with(db(), &t, &opts(VerticalAlign::Bottom));
for c in 0..2 {
let last = col(&bottom, c).last().cloned().unwrap();
assert!((last.baseline + last.descent - 120.0).abs() < 1e-6, "column {c} ends at the bottom");
}
let shift = |c: usize| col(&bottom, c)[0].baseline - col(&top, c)[0].baseline;
assert!(shift(1) > shift(0) + 20.0, "the short column moves further: {} {}", shift(0), shift(1));
}
#[test]
fn vertical_align_in_a_circle_reflows_and_stays_inside() {
let circle = Circle::new((150.0, 150.0), 120.0).to_path(0.1);
let t = area_path("Centred text in a round frame flows again at its new height.", style(12.0), &circle, Justify::Left);
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
let l = layout_with(db(), &t, &valign(a));
assert!(!l.overflow, "{a:?}");
assert_eq!(l.lines.last().unwrap().end, top.lines.last().unwrap().end);
let moved = if a == VerticalAlign::Justify {
l.lines.last().unwrap().baseline - top.lines.last().unwrap().baseline
} else {
l.lines[0].baseline - top.lines[0].baseline
};
assert!(moved > 20.0, "{a:?} {moved}");
for g in l.glyphs.iter().filter(|g| !g.outline.elements().is_empty()) {
let b = g.outline.bounding_box();
for p in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y1)] {
assert!((p - Point::new(150.0, 150.0)).hypot() <= 121.0, "{a:?} {p:?}");
}
}
}
let c = layout_with(db(), &t, &valign(VerticalAlign::Center));
let (above, below) = block_space(&c, 270.0);
assert!((above - 30.0 - below).abs() < 10.0, "roughly centred: {above} {below}");
}
#[test]
fn vertical_align_with_text_wrap_flows_again_around_the_object() {
let mut t = area(COPY, style(12.0), Rect::new(0.0, 0.0, 300.0, 400.0), Justify::Left);
let obstacle = Rect::new(100.0, 250.0, 200.0, 330.0).to_path(0.1);
t.wrap = vec![vectorcraft_doc::WrapShape { path: PathData::from_bezpath(&obstacle), wrap: Default::default() }];
let top = layout(db(), &t);
let bottom = layout_with(db(), &t, &valign(VerticalAlign::Bottom));
assert!(!bottom.overflow);
assert_eq!(bottom.lines.last().unwrap().end, top.lines.last().unwrap().end);
let last = bottom.lines.last().unwrap();
assert!(400.0 - (last.baseline + last.descent) < 15.0, "near the bottom: {}", last.baseline);
// Lines beside the object leave room for it (offset 6 pt).
for li in bottom.lines.iter().filter(|li| li.baseline + li.descent > 244.0 && li.baseline - li.ascent < 336.0) {
assert!(li.x1 <= 94.0 + 1e-6 || li.x0 >= 206.0 - 1e-6, "{li:?}");
}
}
#[test]
fn vertical_align_on_vertical_type_moves_columns_along_the_block_axis() {
// Vertical type: the block axis runs right to left, so "bottom" is the frame's left edge.
let mut t = area("Tate\nYoko", style(20.0), Rect::new(0.0, 0.0, 200.0, 100.0), Justify::Left);
t.vertical = true;
let top = layout(db(), &t);
let bottom = layout_with(db(), &t, &valign(VerticalAlign::Bottom));
let center = layout_with(db(), &t, &valign(VerticalAlign::Center));
assert!(top.bounds.x1 > 190.0 && top.bounds.x0 > 100.0, "{:?}", top.bounds);
assert!(bottom.bounds.x0.abs() < 0.5, "{:?}", bottom.bounds);
assert!((center.bounds.x0 - (200.0 - center.bounds.x1)).abs() < 0.5, "{:?}", center.bounds);
// Glyphs stay inside the frame; lines keep line-space coordinates.
for g in &bottom.glyphs {
assert!(g.origin.x >= -1e-6 && g.origin.x <= 200.0 + 1e-6);
}
}
/// Top-to-Top leading (em box top to em box top): the first line hangs from the frame's top and a
/// line's leading is the space below it. Vertical alignment measures the space from the lines that
/// model placed, keeps their spacing when it shifts them, and justify adds its share on top of it.
#[test]
fn vertical_align_with_top_to_top_leading() {
use vectorcraft_doc::LeadingModel;
let st = |size: f64| CharStyle { size, leading: Some(size * 1.5), ..style(size) };
let mut t = area("", st(40.0), Rect::new(0.0, 0.0, 200.0, 300.0), Justify::Left);
t.runs = vec![TextRun { text: "大\n".into(), style: st(40.0) }, TextRun { text: "小\n中".into(), style: st(20.0) }];
t.para.leading_model = LeadingModel::EmBoxTop;
let top = layout(db(), &t);
assert_eq!(top.lines.len(), 3);
// The em box top sits 0.88 em above the baseline in the craft-fonts CJK faces; a system
// fallback (no craft-fonts) has its own metrics, which the relative checks below don't need.
if !crate::CRAFT_FONTS.is_empty() {
assert!((top.lines[0].baseline - 0.88 * 40.0).abs() < 0.01, "first em box at the top: {}", top.lines[0].baseline);
}
let gaps = |l: &TextLayout| l.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect::<Vec<_>>();
let bottom = layout_with(db(), &t, &valign(VerticalAlign::Bottom));
assert!(block_space(&bottom, 300.0).1.abs() < 1e-6, "{:?}", block_space(&bottom, 300.0));
for (a, b) in gaps(&bottom).iter().zip(gaps(&top)) {
assert!((a - b).abs() < 1e-6, "spacing kept: {a} {b}");
}
let center = layout_with(db(), &t, &valign(VerticalAlign::Center));
let d = center.lines[0].baseline - top.lines[0].baseline;
assert!((d - block_space(&top, 300.0).1 * 0.5).abs() < 1e-6, "{d}");
let just = layout_with(db(), &t, &valign(VerticalAlign::Justify));
assert!((just.lines[0].baseline - top.lines[0].baseline).abs() < 1e-9, "the first line stays");
assert!(block_space(&just, 300.0).1.abs() < 1e-6);
let extra: Vec<f64> = gaps(&just).iter().zip(gaps(&top)).map(|(a, b)| a - b).collect();
assert!(extra.len() == 2 && (extra[0] - extra[1]).abs() < 1e-6 && extra[0] > 50.0, "{extra:?}");
// A round frame reflows with Top-to-Top leading too, without losing text.
let circle = Circle::new((150.0, 150.0), 120.0).to_path(0.1);
let mut round = area_path("", st(20.0), &circle, Justify::Left);
round.runs = t.runs.clone();
round.para.leading_model = LeadingModel::EmBoxTop;
let rtop = layout(db(), &round);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
let l = layout_with(db(), &round, &valign(a));
assert!(!l.overflow, "{a:?}");
assert_eq!(l.lines.last().unwrap().end, rtop.lines.last().unwrap().end);
// The 40 pt line starts low in the circle already, so centring moves it a little.
let want = if a == VerticalAlign::Center { 1.0 } else { 20.0 };
assert!(l.lines.last().unwrap().baseline > rtop.lines.last().unwrap().baseline + want, "{a:?}");
}
}
// ---------- OpenType ----------
#[test]
@@ -419,17 +710,22 @@ fn uncovered_characters_do_not_break_layout() {
#[test]
fn layout_10k_area_text_is_fast() {
let text: String = COPY.chars().cycle().take(10_000).collect();
let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), Justify::JustifyLeft);
t.para.hyphenate = true;
let _ = layout(db(), &t);
let n = 5;
let start = std::time::Instant::now();
for _ in 0..n {
let l = layout(db(), &t);
assert!(!l.overflow);
for (justify, composer) in
[(Justify::JustifyLeft, Composer::EveryLine), (Justify::Left, Composer::EveryLine), (Justify::Left, Composer::SingleLine)]
{
let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify);
t.para.hyphenate = true;
t.para.composer = composer;
let _ = layout(db(), &t);
let n = 5;
let start = std::time::Instant::now();
for _ in 0..n {
let l = layout(db(), &t);
assert!(!l.overflow);
}
let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64;
eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {per:.3} ms");
let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 };
assert!(per < budget, "{justify:?} {composer:?}: {per} ms");
}
let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64;
eprintln!("layout of 10k chars (justified, hyphenated): {per:.3} ms");
let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 };
assert!(per < budget, "{per} ms");
}
+41 -11
View File
@@ -201,15 +201,21 @@ fn anchor_owners(cx: &ToolContext, f: fn(&Node) -> bool) -> Vec<NodeId> {
v
}
/// Anchor of any visible path or area type frame under `p`, topmost first: (id, si, ai, where it is).
/// The anchor within `tol` of `p` nearest to it, of the topmost visible path or area type frame
/// that has one: (id, si, ai, where it is).
fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> {
let owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n));
owners.into_iter().find_map(|id| {
let pd = cx.doc.node(id).and_then(editable_path)?;
pd.anchors().find(|(_, _, a)| a.p.distance(p) <= tol).map(|(si, ai, a)| (id, si, ai, a.p))
nearest_anchor(&pd, p, tol).map(|(si, ai, a)| (id, si, ai, a))
})
}
/// The anchor of `pd` within `tol` of `p` nearest to it: (subpath, anchor, where it is).
fn nearest_anchor(pd: &PathData, p: Point, tol: f64) -> Option<(usize, usize, Point)> {
pd.anchors().map(|(si, ai, a)| (si, ai, a.p)).filter(|(.., a)| a.distance(p) <= tol).min_by(|x, y| x.2.distance(p).total_cmp(&y.2.distance(p)))
}
/// An edge of an area type frame under `p`, topmost first: (text, the edge's two anchors).
fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec<AnchorRef>)> {
anchor_owners(cx, is_area_type).into_iter().find_map(|id| {
@@ -290,7 +296,8 @@ impl Tool for DirectSelectionTool {
return out;
}
let p = ev.pos;
let tol = cx.pick_tol();
// Anchors and handle ends are picked from a little further than segments and objects.
let (tol, point) = (cx.pick_tol(), cx.point_tol());
match (ev.kind, self.state.clone()) {
(PointerKind::Down, _) if self.group => {
if let Some(out) = self.guide.press(cx, ev) {
@@ -332,7 +339,7 @@ impl Tool for DirectSelectionTool {
return vec![];
}
if let Some(sel) = self.spine.filter(|(id, _)| cx.selection.contains(*id))
&& let Some(out) = hit_spine_handle(cx, sel, p, tol)
&& let Some(out) = hit_spine_handle(cx, sel, p, point)
{
self.state = State::SpineHandle { id: sel.0, anchor: sel.1, out };
return vec![Action::Begin("Reshape Spine".into())];
@@ -343,17 +350,17 @@ impl Tool for DirectSelectionTool {
return self.mesh.press(g);
}
self.mesh.unfocus();
if let Some((id, si, ai, out)) = hit_handle(cx, p, tol) {
if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
self.state = State::Handle { id, si, ai, out };
self.handle_snap = HandleSnap::default();
return vec![Action::Begin("Reshape".into())];
}
if let Some((id, anchor, from)) = hit_spine_point(cx, p, tol) {
if let Some((id, anchor, from)) = hit_spine_point(cx, p, point) {
self.spine = Some((id, anchor));
self.state = State::SpinePoint { id, anchor, from, start: p, began: false };
return if cx.selection.contains(id) { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] };
}
if let Some((id, si, ai, grab)) = hit_anchor(cx, p, tol) {
if let Some((id, si, ai, grab)) = hit_anchor(cx, p, point) {
if cx.doc.node(id).is_some_and(is_area_type) {
return self.press_type_area(cx, id, vec![(si, ai)], p, ev.mods.shift);
}
@@ -608,14 +615,14 @@ impl Tool for DirectSelectionTool {
}
}
/// The anchor within the selection tolerance of `p`, of a selected path or the path under `p`:
/// what Highlight anchors on mouse over marks (a press there picks it).
/// The anchor within a press's reach of `p` ([`ToolContext::point_tol`]), of a selected path or the
/// path under `p`: what Highlight anchors on mouse over marks (a press there picks it).
fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> {
let under = hit_test(cx.doc, p, cx.hit_options()).map(|h| h.leaf);
let tol = cx.pick_tol();
let tol = cx.point_tol();
cx.selection.objects.iter().copied().chain(under).find_map(|id| {
let path = cx.doc.node(id).and_then(editable_path)?;
path.anchors().find(|(_, _, a)| a.p.distance(p) <= tol).map(|(_, _, a)| (id, a.p))
nearest_anchor(&path, p, tol).map(|(.., a)| (id, a))
})
}
@@ -685,6 +692,29 @@ mod tests {
assert_eq!(down(&mut t, 100.0), vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))]);
}
/// An anchor is picked from 2 px past its drawn square even where its segment is nearer, and
/// further with a larger anchor Size or Tolerance (#593); away from it the segment is.
#[test]
fn anchors_are_picked_before_the_segments_through_them() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let corner = vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))];
let press = |cx: &ToolContext, x: f64, y: f64| DirectSelectionTool::new(false).pointer(cx, &PointerEvent::new(PointerKind::Down, x, y));
let c = cx(&d, &s, &p);
// 4.3 px from the corner, 0.5 px from the top edge.
assert_eq!(press(&c, 104.2, 100.5), corner);
assert_ne!(press(&c, 110.0, 100.5), corner, "the segment, away from the anchor");
assert_ne!(press(&c, 105.0, 100.5), corner, "past the default reach (4.5 px)");
let large = ToolContext { anchor_size: 7, ..cx(&d, &s, &p) };
assert_eq!(press(&large, 106.0, 100.5), corner, "Size 7 draws them 9 px wide");
let loose = ToolContext { selection_tolerance: 8.0, ..cx(&d, &s, &p) };
assert_eq!(press(&loose, 107.5, 100.5), corner);
// On screen: at 200% the reach is half as far in the document.
let zoomed = ToolContext { zoom: 2.0, ..cx(&d, &s, &p) };
assert_eq!(press(&zoomed, 102.1, 100.2), corner);
assert_ne!(press(&zoomed, 102.6, 100.2), corner);
}
/// A blend of two 20 pt squares centred on (110, 310) and (210, 310), selected.
fn blend_doc() -> (vectorcraft_doc::Document, NodeId, NodeId) {
let (mut d, _) = doc_with_rect();
+6 -5
View File
@@ -48,7 +48,7 @@ impl AnchorTool {
}
fn delete(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_anchor(cx, p, cx.pick_tol()).map(remove_anchor).into_iter().collect()
hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
}
}
@@ -61,7 +61,8 @@ impl Tool for AnchorTool {
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
let tol = cx.pick_tol();
// Anchors and handle ends are picked from a little further than segments.
let (tol, point) = (cx.pick_tol(), cx.point_tol());
match (self.id, ev.kind) {
("addAnchor", PointerKind::Down) => {
if ev.mods.alt {
@@ -78,7 +79,7 @@ impl Tool for AnchorTool {
}
}
("scissors", PointerKind::Down) => {
if let Some((id, si, ai)) = hit_anchor(cx, p, tol) {
if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))];
}
match hit_segment(cx, p, tol) {
@@ -87,10 +88,10 @@ impl Tool for AnchorTool {
}
}
("anchorPoint", PointerKind::Down) => {
if let Some((id, si, ai, out)) = hit_handle(cx, p, tol) {
if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
self.state = State::Handle { id, si, ai, out, began: false };
self.snap = HandleSnap::default();
} else if let Some((id, si, ai)) = hit_anchor(cx, p, tol) {
} else if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
self.state = State::Convert { id, si, ai, start: p, began: false };
} else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) {
self.state = State::Reshape { id, si, seg, t, start: p, began: false };
+11
View File
@@ -274,6 +274,8 @@ pub struct ToolContext<'a> {
/// Selection & Anchor Display → Tolerance: how near (screen pixels) a click must be to a path
/// or an anchor to pick it.
pub selection_tolerance: f64,
/// Selection & Anchor Display → Size (1–7, default 3): how big anchors and handles are drawn.
pub anchor_size: u32,
/// Selection & Anchor Display → Object Selection by Path Only: a click inside a filled path
/// doesn't pick it, only one on its path does.
pub path_only: bool,
@@ -362,6 +364,14 @@ impl ToolContext<'_> {
pub fn pick_tol(&self) -> f64 {
self.tol(self.selection_tolerance)
}
/// How near (document units) a press picks an anchor or a direction handle's end: the
/// selection tolerance, but at least 2 px past the drawn point, so a point is easy to catch
/// and wins over the segments through it, which are tested after it (#593).
pub fn point_tol(&self) -> f64 {
// Anchors are drawn 5 px wide at the default Size 3, a pixel more or less per step.
let half = (5.0 + f64::from(self.anchor_size.clamp(1, 7)) - 3.0) / 2.0;
self.tol(self.selection_tolerance.max(half + 2.0))
}
pub fn hit_options(&self) -> vectorcraft_doc::hit::HitOptions {
vectorcraft_doc::hit::HitOptions {
tol: self.pick_tol(),
@@ -666,6 +676,7 @@ pub(crate) mod testutil {
slices_locked: false,
auto_add_delete: true,
selection_tolerance: 3.0,
anchor_size: 3,
path_only: false,
type_path_only: false,
double_click_isolate: true,
+6 -6
View File
@@ -91,11 +91,11 @@ fn last_anchor(cx: &ToolContext, id: NodeId) -> Option<(usize, usize)> {
/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's
/// gesture, within its tolerance.
fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
let tol = cx.pick_tol();
let point = cx.point_tol();
m.alt
&& (hit_handle(cx, p, tol).is_some()
|| crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).is_some()
|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).is_some())
&& (hit_handle(cx, p, point).is_some()
|| crate::draw2::anchor_in(cx, editable_paths(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, editable_paths(cx), p, cx.pick_tol()).is_some())
}
/// The selected paths the pen edits (not guides, nor locked or hidden ones).
@@ -123,7 +123,7 @@ impl Tool for PenTool {
self.drag.is_some() || self.handle.is_some() || self.convert.is_some()
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let tol = cx.tol(5.0);
let tol = cx.tol(5.0).max(cx.point_tol());
// The path a press began is the selected one by the next event.
if self.drawing && self.path.is_none() {
self.path = active_path(cx).map(|a| a.0);
@@ -297,7 +297,7 @@ impl Tool for PenTool {
o
}
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
let tol = cx.tol(5.0);
let tol = cx.tol(5.0).max(cx.point_tol());
if let Some((id, first, last, _)) = self.active(cx) {
let one = last_anchor(cx, id).is_some_and(|(_, ai)| ai == 0);
if p.distance(first) <= tol && !one {
+49
View File
@@ -38,6 +38,8 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
match (command, key) {
("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS),
("type.pathOptions", "alignToPath") => Some(PATH_ALIGN),
("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE),
("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN),
_ => None,
}
}
@@ -45,6 +47,13 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
/// Type on a Path Options › Align to Path.
const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")];
/// Area Type Options › First Baseline.
const FIRST_BASELINE: form::Choices =
&[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")];
/// Area Type Options › Align (vertical alignment of the lines in each row/column).
const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")];
/// Closes before running, so a dialog the command opens stays open.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let cmd = d.str("__command");
@@ -59,3 +68,43 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
}
app.run(&cmd, params)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use vectorcraft_doc::{NodeKind, VerticalAlign};
use vectorcraft_engine::Session;
use super::*;
#[test]
fn area_type_options_choices_match_the_params_doc() {
let doc = vectorcraft_engine::find_command("text.areaOptions").unwrap().params;
for key in ["firstBaseline", "verticalAlign"] {
let values: Vec<&str> = choices("text.areaOptions", key).unwrap().iter().map(|(_, v)| *v).collect();
assert!(doc.contains(&format!("{key}?: {}", values.join("|"))), "{key}: {values:?}");
}
assert!(choices("text.areaOptions", "firstBaselineMin").is_none(), "a distance, not a choice");
assert!(choices("text.areaOptions", "inset").is_none());
}
#[test]
fn area_type_options_dialog_sets_the_vertical_alignment() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"]
.as_u64()
.unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
crate::menus::invoke(&mut app, "text.areaOptions", json!({}));
assert_eq!(app.ui.dialog.as_ref().unwrap().str("verticalAlign"), "top");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));
out.textures_delta.clear();
app.ui.dialog.as_mut().unwrap().fields.insert("verticalAlign".into(), json!("center"));
crate::dialogs::confirm(&mut app).unwrap();
let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") };
assert_eq!(t.area.vertical_align, VerticalAlign::Center);
}
}
+1 -1
View File
@@ -455,7 +455,7 @@ fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) {
flag(ui, d, "viewAfterSaving", tl!("View PDF after saving"), true);
// PDF layers need PDF 1.5, and PDF/X-1a and PDF/X-3 have none.
let layers = standard.allows_layers() && choice::<Compatibility>(d, "compatibility").unwrap_or_default().has_layers();
flag(ui, d, "createLayers", tl!("Create PDF layers from top-level layers"), layers);
flag(ui, d, "createLayers", tl!("Create PDF layers from layers and sublayers"), layers);
flag(ui, d, "includeNonPrinting", tl!("Include non-printing layers"), true);
if editor {
heading(ui, tl!("Description"));
+1 -1
View File
@@ -508,7 +508,7 @@
Create Object Mosaic… Crear mosaico de objetos…
Create Outlines Crear contornos
Create Path Crear trazado
Create PDF layers from top-level layers Crear capas PDF a partir de las capas de nivel superior
Create PDF layers from layers and sublayers Crear capas PDF a partir de las capas y subcapas
Create PDF-Compatible File Crear archivo compatible con PDF
Create Report Crear informe
Create Slice Crear sector
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1 -1
View File
@@ -508,7 +508,7 @@
Create Object Mosaic… Crea mosaico di oggetti…
Create Outlines Crea contorni
Create Path Crea tracciato
Create PDF layers from top-level layers Crea livelli PDF dai livelli principali
Create PDF layers from layers and sublayers Crea livelli PDF dai livelli e sottolivelli
Create PDF-Compatible File Crea file compatibile PDF
Create Report Crea rapporto
Create Slice Crea sezione
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1 -1
View File
@@ -983,7 +983,7 @@
Create New Sublayer 新規サブレイヤーを作成
Create New Swatch… 新規スウォッチを作成…
Create New {kind} Style 新しい{kind}スタイルを作成
Create PDF layers from top-level layers 最上位レイヤーから PDF レイヤーを作成
Create PDF layers from layers and sublayers レイヤーとサブレイヤーから PDF レイヤーを作成
Create PDF-Compatible File PDF 互換ファイルを作成
Create Path パスを作成
Create Slice スライスを作成
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1 -1
View File
@@ -497,7 +497,7 @@
Create New {kind} Style Criar Novo Estilo de {kind}
Create Object Mosaic… Criar Mosaico de Objetos…
Create Outlines Criar Contornos
Create PDF layers from top-level layers Criar camadas de PDF a partir das camadas de nível superior
Create PDF layers from layers and sublayers Criar camadas de PDF a partir das camadas e subcamadas
Create PDF-Compatible File Criar Arquivo Compatível com PDF
Create Path Criar Caminho
Create Slice Criar Fatia
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1 -1
View File
@@ -506,7 +506,7 @@
Create Object Mosaic… Создать мозаику объектов…
Create Outlines Создать контуры
Create Path Создать контур
Create PDF layers from top-level layers Создавать слои PDF из слоёв верхнего уровня
Create PDF layers from layers and sublayers Создавать слои PDF из слоёв и подслоёв
Create PDF-Compatible File Создать файл, совместимый с PDF
Create Report Создать отчёт
Create Slice Создать фрагмент
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1 -1
View File
@@ -508,7 +508,7 @@
Create Object Mosaic… 创建对象马赛克…
Create Outlines 创建轮廓
Create Path 创建路径
Create PDF layers from top-level layers 从顶层图层创建 PDF 图层
Create PDF layers from layers and sublayers 从图层和子图层创建 PDF 图层
Create PDF-Compatible File 创建与 PDF 兼容的文件
Create Report 创建报告
Create Slice 创建切片
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1 -1
View File
@@ -523,7 +523,7 @@
Create Object Mosaic… 建立物件馬賽克…
Create Outlines 建立外框
Create Path 建立路徑
Create PDF layers from top-level layers 從最上層圖層建立 PDF 圖層
Create PDF layers from layers and sublayers 從圖層和子圖層建立 PDF 圖層
Create PDF-Compatible File 建立與 PDF 相容的檔案
Create Report 建立報告
Create Slice 建立切片
Can't render this file because it contains an unexpected character in line 6 and column 47.
+54 -8
View File
@@ -503,21 +503,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let mut new: Option<(Color, Live, Vec<f32>)> = None;
let mut behind: Option<(Color, Live)> = None;
let mut tinted: Option<(f32, Live)> = None;
let gamut = color.filter(|_| matches!(mode, Mode::Rgb | Mode::Hsb)).and_then(|c| gamut_fix(app, ui.ctx(), "color-gamut", &c));
// The warnings the mode shows: out of gamut in RGB and HSB, out of web colours but in Web Safe
// RGB and Grayscale.
let (shows_gamut, shows_web) = (matches!(mode, Mode::Rgb | Mode::Hsb), !matches!(mode, Mode::WebSafe | Mode::Grayscale));
let gamut = color.filter(|_| shows_gamut).and_then(|c| gamut_fix(app, ui.ctx(), "color-gamut", &c));
ui.horizontal(|ui| {
// Left column: proxy, out-of-gamut and out-of-web warnings.
ui.vertical(|ui| {
ui.set_width(44.0);
super::proxy(app, ui, 40.0);
let web = color.filter(|c| !matches!(mode, Mode::WebSafe | Mode::Grayscale) && !is_web_safe(c)).map(|c| web_safe(&c));
for (warning, fix) in [(GAMUT_WARNING, gamut), (WEB_WARNING, web)] {
if let Some(fix) = fix {
ui.add_space(6.0);
if warning_chip(ui, warning, &fix) {
new = Some((fix, Live::Released, components(mode, &fix)));
}
let web = color.filter(|c| shows_web && !is_web_safe(c)).map(|c| web_safe(&c));
let warnings: Vec<_> = [(GAMUT_WARNING, gamut), (WEB_WARNING, web)].into_iter().filter_map(|(w, fix)| Some((w, fix?))).collect();
for (warning, fix) in &warnings {
ui.add_space(6.0);
if warning_chip(ui, *warning, fix) {
new = Some((*fix, Live::Released, components(mode, fix)));
}
}
// Room for the mode's other warnings: the panel keeps its height as the colour changes,
// else the spectrum below moves under a dragging pointer and the colour flips every
// frame, e.g. between a pale colour out of gamut and white above the spectrum (#578).
for _ in warnings.len()..usize::from(shows_gamut) + usize::from(shows_web) {
ui.add_space(6.0);
ui.scope(|ui| {
ui.set_invisible();
warning_chip(ui, WEB_WARNING, &Color::WHITE)
});
}
});
// Sliders (Shift-drag moves them in tandem).
ui.vertical(|ui| {
@@ -705,6 +717,40 @@ mod tests {
(f.color().map(|c| c.to_hex()).unwrap_or_default(), s.color().map(|c| c.to_hex()).unwrap_or_default())
}
#[test]
fn a_drag_on_the_spectrum_holds_still_near_white() {
let mut app = app();
let ctx = egui::Context::default();
let none = egui::Modifiers::NONE;
// White needs no warning, #fefefe the web one, a pale violet both: one panel height.
let heights: Vec<f32> = ["#ffffff", "#fefefe", "#ded3ff"]
.iter()
.map(|c| {
app.run("paint.setFill", json!({"color": c})).unwrap();
frame(&mut app, &ctx, vec![], none);
frame(&mut app, &ctx, vec![], none).1
})
.collect();
assert!(heights.windows(2).all(|w| w[0] == w[1]), "{heights:?}");
// Drag along the spectrum's top edge (pale colours, some out of gamut), stopping at each
// point: the colour holds while the pointer does.
let r = frame(&mut app, &ctx, vec![], none).0.expect("the spectrum is drawn");
let at = |x: f32| egui::pos2(r.left() + x * r.width(), r.top() + 2.0);
let button = |pressed| egui::Event::PointerButton { pos: at(0.02), button: egui::PointerButton::Primary, pressed, modifiers: none };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(0.02)), button(true)], none);
for i in 1..20 {
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(i as f32 * 0.05))], none);
let fills: Vec<String> = (0..3)
.map(|_| {
frame(&mut app, &ctx, vec![], none);
paints_hex(&app).0
})
.collect();
assert!(fills.windows(2).all(|w| w[0] == w[1]), "at {}: {fills:?}", i as f32 * 0.05);
}
frame(&mut app, &ctx, vec![button(false)], none);
}
#[test]
fn tandem_keeps_ratios() {
let t = tandem(Mode::Rgb, &[100.0, 50.0, 25.0], 0, 200.0);
+12 -5
View File
@@ -1,9 +1,10 @@
//! Paragraph panel: seven alignment buttons, Paragraph Direction (with the Indic options), indents,
//! space before/after, Hyphenate and Mojikumi Set (with the East Asian options).
//! space before/after, Hyphenate and Mojikumi Set (with the East Asian options); the panel menu
//! picks the Single-line or Every-line Composer.
use egui::{Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::{Justify, NodeKind, ParaDirection, ParaStyle};
use vectorcraft_doc::{Composer, Justify, NodeKind, ParaDirection, ParaStyle};
use super::character::text_style;
use super::{pstate, set_pstate};
@@ -181,14 +182,20 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
});
}
ui.separator();
menu_item(ui, tl!("Single-line Composer"), false, false);
menu_item(ui, tl!("Every-line Composer"), false, true);
let composer = style.as_ref().map(|(_, p)| p.composer);
for (c, label, id) in
[(Composer::SingleLine, tl!("Single-line Composer"), "singleLine"), (Composer::EveryLine, tl!("Every-line Composer"), "everyLine")]
{
if menu_item(ui, label, has, composer == Some(c)) {
format(app, json!({ "composer": id }));
}
}
ui.separator();
if menu_item(ui, tl!("Reset Panel"), has, false) {
para_cmd(app, "text.setStyle", json!({"justify": "auto"}));
format(
app,
json!({"leftIndent": 0, "rightIndent": 0, "firstLineIndent": 0, "spaceBefore": 0, "spaceAfter": 0, "hyphenate": false, "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard"}),
json!({"leftIndent": 0, "rightIndent": 0, "firstLineIndent": 0, "spaceBefore": 0, "spaceAfter": 0, "hyphenate": false, "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard", "composer": "everyLine"}),
);
}
}
+35 -3
View File
@@ -355,9 +355,11 @@ A `security` password encrypts the file (RC4 40-bit at PDF 1.3, RC4 128-bit at 1
Pattern fills and strokes are written as their tiles clipped to the area they paint (a stroke's outline, with its
dashes, caps, profile, arrowheads and alignment), and freeform gradients as an image of their colour field at the
document's raster effects resolution, clipped the same way.
`createLayers` writes each top-level layer (template layers are left out) as a PDF layer, an optional content group
named as the layer: hidden layers are off, non-printing ones have `/PrintState /OFF` and locked ones are locked. It needs
PDF 1.5 or later (at 1.4 it warns), and the file reopens with those layers.
`createLayers` writes each layer and sublayer (template layers are left out) as a PDF layer, an optional content group
named as the layer and listed under its parent layer's: hidden layers are off (their art is written, for the reader to
show), non-printing ones have `/PrintState /OFF` and locked ones are locked. It needs PDF 1.5 or later (at 1.4 it
warns), and the file reopens with those layers and sublayers. A `.ai` file writes them unless `createLayers` is false,
so apps that read its PDF part find the layers, hidden ones included; hidden objects aren't in the PDF part.
Images follow the `compression` settings of their kind (`color`, `gray`, or `mono` for black-and-white images): above
`abovePpi` as placed they are resampled (`downsample`: `average`, `subsample` or `bicubic`) to `ppi`, and compressed
with `zip`, `jpeg` (at `quality`; images with transparency stay lossless) or `auto` (JPEGs stay JPEG, the others
@@ -2201,6 +2203,22 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane
{"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}}
```
### Vertical alignment
`text.areaOptions {verticalAlign: top|center|bottom|justify}` (Area Type Options › Align) places the lines of each
row/column cell on its own: `center` centres the block of lines in the cell, `bottom` puts the last line's descent on
the cell's bottom (inside the inset), `justify` keeps the first line at the top, moves the last one to the bottom and
shares the space left over equally between the lines (there is no paragraph spacing limit: every line gap grows by
the same amount). A cell with a single line justifies to the top, and a full or overflowing cell only moves by the
less-than-a-line of space it has left. In rectangular frames without text wrap the lines just move; in other
frames (and around wrap objects) the text flows again starting lower until it settles, never losing text that fit
top-aligned. Vertical type aligns along its block axis (`bottom` is the frame's left edge). Exports lay type out
again, so SVG, PDF and EPS show the aligned text.
```json
{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"verticalAlign":"center"}}}
```
## Converting between point type and area type
With the Selection tool, a single selected point or area type object shows the type widget: a small circle beside
@@ -2550,6 +2568,20 @@ canvas as they export. `object.blend.expand` and `object.blend.release` keep the
opacity mask and appearance (Release on a group around the keys and spine when the blend has any), and
`object.expand` with `object: true` expands the blends in the selection.
## Paragraph composer
`text.setFormat {ids?, composer: "singleLine"|"everyLine"}` sets how a text object's lines are broken (the Paragraph
panel menu's Single-line and Every-line Composer; stored in the paragraph attributes as `para.composer`, saved only
when it is Single-line). Every-line, the default, picks the breaks of the whole paragraph together in area type:
justified text gets even word spacing, ragged text (left, centre or right aligned) an even rag, so it may move a word
that fits to the next line to avoid a lone short word on the last line or a full line next to a short one.
Single-line fills each line as far as it goes. Point type and type on a path have no line width, so both composers
give the same result there; paragraphs that mix type sizes fall back to Single-line.
```json
{"name":"run_command","arguments":{"command":"text.setFormat","params":{"ids":[7],"composer":"singleLine"}}}
```
## Editing envelopes
`object.envelope.editContents {editing}` switches between editing the envelope and its contents (the menu item reads