mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 01:44:57 +01:00
Merge remote-tracking branch 'origin/main' into feat/width-smooth-profile
# Conflicts: # crates/tools/src/builder.rs # docs/target-app-parity.md
This commit is contained in:
commit
8efeeaf279
109 files changed
+5168
-393
No files matched your search
Generated
+29
-28
@@ -4574,7 +4574,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"block2 0.6.2",
|
||||
@@ -4613,7 +4613,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-affinity"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -4624,7 +4624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-brush"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -4636,7 +4636,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4652,7 +4652,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"objc2-core-foundation",
|
||||
@@ -4674,7 +4674,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-color"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
@@ -4686,7 +4686,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-doc"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"hayro-ccitt",
|
||||
@@ -4705,7 +4705,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4721,7 +4721,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"crc32fast",
|
||||
@@ -4759,7 +4759,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"flate2",
|
||||
@@ -4782,7 +4782,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-format"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"proptest",
|
||||
@@ -4797,7 +4797,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -4809,7 +4809,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -4828,7 +4828,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4842,7 +4842,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"linesweeper",
|
||||
@@ -4854,7 +4854,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
@@ -4885,7 +4885,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4899,7 +4899,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-render"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"gif",
|
||||
@@ -4926,14 +4926,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-scriptcheck"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-svg"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"flate2",
|
||||
@@ -4958,7 +4958,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"image",
|
||||
@@ -4976,7 +4976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-text"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
@@ -4990,13 +4990,14 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom",
|
||||
"vello_cpu 0.2.0",
|
||||
"windows-registry",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-three-d"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
@@ -5004,7 +5005,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -5020,7 +5021,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -5032,7 +5033,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-ui",
|
||||
@@ -5068,7 +5069,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-web"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -6106,7 +6107,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -258,7 +258,7 @@ The scores are self-assessed from our code against public documentation;
|
||||
- reliable exchange of .ai files (layer structure in real files; proprietary editing data isn't written);
|
||||
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
|
||||
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
|
||||
- the Effect Gallery (all 57 Photoshop-style raster filters are available, approximated, under Artistic, Blur, Brush Strokes, Distort, Pixelate, Sharpen, Sketch, Stylize, Texture and Video);
|
||||
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
|
||||
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
|
||||
- scripting, and the rest of Variables (image and graph kinds, dataset import);
|
||||
- generative AI features.
|
||||
|
||||
+7
-3
@@ -9,7 +9,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -76,7 +76,7 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
|
||||
| Strokes, brushes, width profiles | 88% | 8–15 |
|
||||
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
|
||||
| Live vector effects | 85% | 6–10 |
|
||||
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 82% | 4–6 |
|
||||
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 |
|
||||
| 3D and Materials | ~25% | 30–55 |
|
||||
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
|
||||
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
|
||||
@@ -123,11 +123,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
|
||||
3. **Launch and stability on real machines** (G10): 20–35 h.
|
||||
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
|
||||
5. **Raster effects** (G2) alongside: the Effect Gallery (every Photoshop-style filter is in), 4–6 h.
|
||||
5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h.
|
||||
6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3).
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-10-23: COLR colour fonts (v0 and v1, as in Noto Color Emoji's vector build, Segoe UI Emoji, Nabla) draw as vector art: their layers' colours, gradients, clips and blend modes on the canvas and in SVG, EPS, legacy `.ai` and PDF, and as editable paths with Create Outlines; glyphs using sweep gradients or compositing modes are drawn as images of the glyph.
|
||||
- 2026-10-22: The Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step. Filter thumbnails and a preview area inside the dialog remain ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). Raster effects 82% → 85% (estimated); headline numbers unchanged.
|
||||
- 2026-10-22: Colour emoji fonts with bitmap glyphs draw and export: `sbix` (Apple Color Emoji, macOS's emoji font) and `CBDT` (bitmap Noto Color Emoji) glyphs show as their pictures on the canvas, whatever the type's fill, scale and turn with the type, and export to PDF (in the font's Type 3 glyphs, or as images), SVG (images when type is outlined; live text leaves emoji to the viewer), EPS and legacy `.ai` (images); Create Outlines turns them into embedded images. Fonts with bitmaps but no outlines, such as Noto Color Emoji, are now found among the installed fonts. COLR and OpenType SVG fonts remain; headline numbers unchanged.
|
||||
|
||||
- 2026-10-22: Effect › Sketch › Conté Crayon: a black crayon in the dark areas and a white one in the light areas, on mid-grey paper whose texture (Brick, Burlap, Canvas, Sandstone; Scaling, Relief, Light Direction, Invert) breaks the strokes, with Foreground Level and Background Level; an original approximation, defaults unverified. Every Photoshop-style filter is now in (57/57); the Effect Gallery remains (4–6 h).
|
||||
@@ -194,6 +196,8 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. |
|
||||
| 2026-10-22 | minor | G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview. |
|
||||
| 2026-10-22 | minor | Progress log row for colour emoji fonts with bitmap glyphs; headline numbers unchanged. |
|
||||
| 2026-10-22 | minor | Effects: Sketch › Conté Crayon; measured Photoshop-style filters 57/57, the Effect Gallery remains (G2 estimate 4–6 h). |
|
||||
| 2026-10-21 | minor | 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged |
|
||||
|
||||
@@ -154,3 +154,8 @@ display_name = "Don Omondi"
|
||||
|
||||
[people.alpha-rock]
|
||||
display_name = "Aditya Sisodiya"
|
||||
|
||||
[people.Ronfo2013]
|
||||
real_name = "Angelo Bernardini"
|
||||
display_name = "Angelo Bernardini"
|
||||
sync_github_name = false
|
||||
@@ -261,6 +261,32 @@ mod archive {
|
||||
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
|
||||
}
|
||||
|
||||
// Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's
|
||||
// window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than
|
||||
// the format permits for a block. 0.9.1 refuses it.
|
||||
#[test]
|
||||
fn a_zstd_block_larger_than_its_frames_window_is_refused() {
|
||||
const LEN: u32 = 100_000;
|
||||
let plain = vec![0x61u8; LEN as usize];
|
||||
let file = synth::container(&[("doc.dat", &plain, Method::Zstd)], None);
|
||||
// A Zstandard frame with a 1 KiB window (descriptor byte 0, window byte 0) holding one RLE
|
||||
// block, the last, that repeats a byte LEN times: block header = last | RLE << 1 | LEN << 3.
|
||||
let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
|
||||
frame.extend((1 | (1 << 1) | (LEN << 3)).to_le_bytes().get(..3).unwrap());
|
||||
frame.push(0x61);
|
||||
// Swap it in for the entry's compressed bytes (they follow the "#Fil" tag at offset 72).
|
||||
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
|
||||
let old_len = u64::from_le_bytes(file[fat + 59 + 21..fat + 59 + 29].try_into().unwrap()) as usize;
|
||||
let mut swapped = file[..76].to_vec();
|
||||
swapped.extend(&frame);
|
||||
swapped.extend(&file[76 + old_len..]);
|
||||
let new_fat = fat - old_len + frame.len();
|
||||
swapped[16..24].copy_from_slice(&(new_fat as u64).to_le_bytes());
|
||||
swapped[new_fat + 59 + 21..new_fat + 59 + 29].copy_from_slice(&(frame.len() as u64).to_le_bytes());
|
||||
let mut a = Archive::open(&swapped, Limits::default()).unwrap();
|
||||
assert!(a.read("doc.dat").is_err(), "a block of {LEN} bytes was decompressed from a frame with a 1 KiB window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() {
|
||||
let big = vec![7u8; 1 << 20];
|
||||
|
||||
@@ -44,6 +44,7 @@ pub mod perspective;
|
||||
mod pixels;
|
||||
pub use pixels::MAX_RASTER_ALLOC;
|
||||
pub mod placed_document;
|
||||
pub mod plugin_data;
|
||||
pub mod profiles;
|
||||
pub mod puppet;
|
||||
pub mod range;
|
||||
|
||||
+60
-2
@@ -467,11 +467,49 @@ fn cumulative_lengths(pts: &[Point]) -> Vec<f64> {
|
||||
cum
|
||||
}
|
||||
|
||||
/// Most pieces [`map_nonlinear`] splits one segment into.
|
||||
const MAX_PIECES: usize = 64;
|
||||
|
||||
/// How many pieces of about `piece` a segment of length `len` is split into: one to `most`.
|
||||
pub fn pieces(len: f64, piece: f64, most: usize) -> usize {
|
||||
((len / piece).ceil() as usize).clamp(1, most.max(1))
|
||||
}
|
||||
|
||||
/// The piece length to split segments of lengths `lens` with ([`pieces`], at most `most` each) so
|
||||
/// that the pieces past each segment's first number at most `room`: `piece` when they already do,
|
||||
/// longer pieces otherwise. A segment of `n` pieces adds `n - 1 ≤ len / piece` points to a path,
|
||||
/// so pieces of the total length over `room` fit; with no room every segment stays one piece.
|
||||
pub fn fit_piece(lens: &[f64], piece: f64, most: usize, room: usize) -> f64 {
|
||||
let added = lens.iter().map(|&len| pieces(len, piece, most) - 1).fold(0, usize::saturating_add);
|
||||
if added <= room {
|
||||
return piece;
|
||||
}
|
||||
if room == 0 {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
// A NaN length is always one piece.
|
||||
piece.max(lens.iter().filter(|len| !len.is_nan()).sum::<f64>() / room as f64)
|
||||
}
|
||||
|
||||
/// Map every point of `path` through the non-linear function `f`. Segments are split into pieces
|
||||
/// no longer than about `max_piece` (up to 64 per segment) and their control points mapped, which
|
||||
/// approximates the image curve to O(h²). Closedness and subpath structure are preserved.
|
||||
pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point) -> PathData {
|
||||
let max_piece = max_piece.max(1e-3);
|
||||
map_nonlinear_within(path, max_piece, usize::MAX, f)
|
||||
}
|
||||
|
||||
/// [`map_nonlinear`] whose result has at most `max` anchors, or `path`'s count when that is more:
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
let segs = path.subpaths.iter().map(SubPath::segment_count).fold(0, usize::saturating_add);
|
||||
if segs.saturating_mul(MAX_PIECES - 1) > room {
|
||||
let lens: Vec<f64> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| poly_len(&seg_cubic(sp, i)))).collect();
|
||||
max_piece = fit_piece(&lens, max_piece, MAX_PIECES, room);
|
||||
}
|
||||
let mut subs = Vec::with_capacity(path.subpaths.len());
|
||||
for sp in &path.subpaths {
|
||||
let n = sp.anchors.len();
|
||||
@@ -487,7 +525,7 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = ((poly_len(&c) / max_piece).ceil() as usize).clamp(1, 64);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
if let Some(last) = res.last_mut() {
|
||||
@@ -1884,6 +1922,26 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
|
||||
/// down to one a segment, and matches the plain map where the budget leaves room.
|
||||
#[test]
|
||||
fn map_nonlinear_within_keeps_to_its_anchor_budget() {
|
||||
let square = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let f = |p: Point| Point::new(p.x + (p.y / 10.0).sin(), p.y);
|
||||
let full = map_nonlinear(&square, 1.0, f);
|
||||
assert_eq!(full.anchor_count(), 4 * 64);
|
||||
assert_eq!(map_nonlinear_within(&square, 1.0, 4 * 64, f), full);
|
||||
// Every side takes the same pieces: of 400 / (max - 4) pt, so 12 a side for 50 anchors.
|
||||
for (max, want) in [(0, 4), (4, 4), (5, 4), (50, 4 * 12), (255, 4 * 63)] {
|
||||
assert_eq!(map_nonlinear_within(&square, 1.0, max, f).anchor_count(), want, "{max}");
|
||||
}
|
||||
// Lengths that are not numbers stay one piece; with no room every segment is one piece.
|
||||
assert_eq!(fit_piece(&[f64::NAN, 10.0], 1.0, 64, 5), 2.0);
|
||||
assert_eq!(fit_piece(&[f64::INFINITY, 10.0], 1.0, 64, 0), f64::INFINITY);
|
||||
assert_eq!(pieces(f64::INFINITY, f64::INFINITY, 64), 1);
|
||||
assert_eq!(pieces(10.0, 1.0, 0), 1);
|
||||
}
|
||||
|
||||
/// #1578: Arc bends in the box's real proportions. In half-width units (y scaled by the
|
||||
/// aspect), the top and bottom edges are concentric circles about the bend's centre, at their
|
||||
/// real distance from the centre line; an inner edge that would pass the centre stops there.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! What plug-ins keep with a document: settings that belong to the whole document rather than to
|
||||
//! one object, such as the pens a plotter holds or a machine's profile.
|
||||
//!
|
||||
//! They are the document's foreign data ([`Document::unknown`], under [`PLUGIN_DATA`]), as the
|
||||
//! perspective grid and the brushes are, so the native file has no section of its own for them
|
||||
//! and a version from before them keeps them when it saves. The host never reads them: a filter
|
||||
//! plug-in writes its own and reads only its own back, and an exporter, which is given the whole
|
||||
//! document, can read them all (`vectorcraft-plugins`, which caps what one plug-in keeps).
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::Document;
|
||||
|
||||
/// `Document::unknown` key: `{"<plug-in id>": <what it keeps>}`.
|
||||
pub const PLUGIN_DATA: &str = "pluginData";
|
||||
|
||||
impl Document {
|
||||
/// What plug-in `id` keeps with the document, if anything.
|
||||
pub fn plugin_data(&self, id: &str) -> Option<&Value> {
|
||||
self.unknown.get(PLUGIN_DATA).and_then(|m| m.get(id))
|
||||
}
|
||||
|
||||
/// Keeps `data` for plug-in `id` in place of what it kept; `None` forgets it, and the key goes
|
||||
/// once no plug-in keeps anything. A value under the key that isn't a map of plug-in ids (a
|
||||
/// damaged file) is replaced when a plug-in keeps something.
|
||||
pub fn set_plugin_data(&mut self, id: &str, data: Option<Value>) {
|
||||
let Some(data) = data else {
|
||||
// Nothing to forget: don't copy the foreign data the undo history shares.
|
||||
if self.plugin_data(id).is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(m) = self.unknown.get_mut(PLUGIN_DATA).and_then(Value::as_object_mut) else { return };
|
||||
m.remove(id);
|
||||
if m.is_empty() {
|
||||
self.unknown.remove(PLUGIN_DATA);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let kept = self.unknown.entry(PLUGIN_DATA.to_string()).or_insert_with(|| Value::Object(Map::new()));
|
||||
if !kept.is_object() {
|
||||
*kept = Value::Object(Map::new());
|
||||
}
|
||||
if let Some(m) = kept.as_object_mut() {
|
||||
m.insert(id.to_string(), data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Each plug-in has its own entry, replaced when it keeps something else; forgetting the last
|
||||
/// one removes the key, and forgetting what isn't kept copies nothing.
|
||||
#[test]
|
||||
fn each_plug_in_keeps_its_own_data() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
assert_eq!(d.plugin_data("a"), None);
|
||||
d.set_plugin_data("a", Some(json!({"pens": 2})));
|
||||
d.set_plugin_data("b", Some(json!([1, 2])));
|
||||
d.set_plugin_data("a", Some(json!({"pens": 3})));
|
||||
assert_eq!((d.plugin_data("a"), d.plugin_data("b")), (Some(&json!({"pens": 3})), Some(&json!([1, 2]))));
|
||||
d.set_plugin_data("a", None);
|
||||
assert_eq!(d.unknown[PLUGIN_DATA], json!({"b": [1, 2]}));
|
||||
let before = d.clone();
|
||||
d.set_plugin_data("a", None);
|
||||
assert!(crate::Shared::ptr_eq(&before.unknown, &d.unknown), "still shared with the earlier version");
|
||||
d.set_plugin_data("b", None);
|
||||
assert!(!d.unknown.contains_key(PLUGIN_DATA));
|
||||
}
|
||||
|
||||
/// A damaged file's value under the key holds nothing for any plug-in, stays while there is
|
||||
/// nothing to forget, and is replaced when a plug-in keeps something.
|
||||
#[test]
|
||||
fn a_damaged_value_holds_nothing() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
d.unknown.insert(PLUGIN_DATA.into(), json!(5));
|
||||
assert_eq!(d.plugin_data("a"), None);
|
||||
d.set_plugin_data("a", None);
|
||||
assert_eq!(d.unknown[PLUGIN_DATA], json!(5));
|
||||
d.set_plugin_data("a", Some(json!(true)));
|
||||
assert_eq!(d.unknown[PLUGIN_DATA], json!({"a": true}));
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,9 @@ fn diag(b: Rect) -> f64 {
|
||||
b.width().hypot(b.height()).max(1e-6)
|
||||
}
|
||||
|
||||
/// Free Distort: bilinear map of the bounding box onto four new corners (unit box coordinates).
|
||||
pub fn free_distort(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
/// Free Distort: bilinear map of the bounding box onto four new corners (unit box coordinates),
|
||||
/// making at most `max` anchors ([`map_nonlinear_within`]).
|
||||
pub fn free_distort(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
let mut c = [Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(1.0, 1.0), Point::new(0.0, 1.0)];
|
||||
if let Some(arr) = p.get("corners").and_then(Value::as_array) {
|
||||
for (i, v) in arr.iter().take(4).enumerate() {
|
||||
@@ -34,7 +35,7 @@ pub fn free_distort(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
let bot = c[3].lerp(c[2], u);
|
||||
top.lerp(bot, v)
|
||||
};
|
||||
map_nonlinear(path, diag(b) / 16.0, f)
|
||||
map_nonlinear_within(path, diag(b) / 16.0, max, f)
|
||||
}
|
||||
|
||||
/// Pucker & Bloat: anchors move toward (bloat) or away from (pucker) the centre, handles the
|
||||
@@ -67,21 +68,29 @@ pub fn pucker_bloat(path: &PathData, b: Rect, amount: f64) -> PathData {
|
||||
}
|
||||
}
|
||||
|
||||
/// Roughen: resample at `detail` points per inch and jitter each point by up to `size`.
|
||||
pub fn roughen(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
/// Most points Roughen resamples one segment into.
|
||||
const MAX_ROUGHEN_POINTS: usize = 2000;
|
||||
|
||||
/// Roughen: resample at `detail` points per inch and jitter each point by up to `size`. Where
|
||||
/// that would make more than `max` anchors, the points are spaced further apart until it doesn't
|
||||
/// (stacked Roughens multiply their points, #3578).
|
||||
pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
let size = num(p, "size", 5.0).clamp(0.0, 1e4);
|
||||
let amp = if flag(p, "relative", true) { size / 100.0 * mean_size(b) } else { size };
|
||||
let detail = num(p, "detail", 10.0).clamp(0.0, 100.0);
|
||||
let spacing = if detail > 0.0 { 72.0 / detail } else { f64::INFINITY };
|
||||
// A segment of k points adds k - 1 anchors to the path.
|
||||
let lens: Vec<f64> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i).arclen(0.1))).collect();
|
||||
let spacing = fit_piece(&lens, spacing, MAX_ROUGHEN_POINTS, max.saturating_sub(path.anchor_count()));
|
||||
let mut lens = lens.iter();
|
||||
let smooth = smooth_points(p);
|
||||
let seed = seed(p);
|
||||
let mut subs = vec![];
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
let mut pts = vec![];
|
||||
for i in 0..sp.segment_count() {
|
||||
for (i, &len) in (0..sp.segment_count()).zip(&mut lens) {
|
||||
let c = sp.segment(i);
|
||||
let len = vectorcraft_geom::kurbo::ParamCurveArclen::arclen(&c, 0.1);
|
||||
let k = if spacing.is_finite() { ((len / spacing).ceil() as usize).clamp(1, 2000) } else { 1 };
|
||||
let k = pieces(len, spacing, MAX_ROUGHEN_POINTS);
|
||||
for j in 0..k {
|
||||
pts.push(c.eval(j as f64 / k as f64));
|
||||
}
|
||||
@@ -246,8 +255,9 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
out
|
||||
}
|
||||
|
||||
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle.
|
||||
pub fn twist(path: &PathData, b: Rect, angle: f64) -> PathData {
|
||||
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
|
||||
/// making at most `max` anchors ([`map_nonlinear_within`]).
|
||||
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
|
||||
if ang == 0.0 {
|
||||
return path.clone();
|
||||
@@ -261,8 +271,8 @@ pub fn twist(path: &PathData, b: Rect, angle: f64) -> PathData {
|
||||
let (s, co) = a.sin_cos();
|
||||
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
|
||||
};
|
||||
let pieces = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
|
||||
map_nonlinear(path, pieces, f)
|
||||
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
|
||||
map_nonlinear_within(path, piece, max, f)
|
||||
}
|
||||
|
||||
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
|
||||
@@ -280,11 +290,17 @@ struct Ridge {
|
||||
/// displaced along the normal. Corner points join them with straight lines. Smooth points make a
|
||||
/// wave: every peak and valley is a smooth point whose handles run along the path, a third of the
|
||||
/// way to the next ridge, so each span between them follows a half cosine (an S through the path)
|
||||
/// whatever the size of the ridges (#2343).
|
||||
pub fn zig_zag(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
/// whatever the size of the ridges (#2343). Where `ridges` would make more than `max` anchors,
|
||||
/// each segment gets as many as fit (stacked Zig Zags multiply their points, #3578).
|
||||
pub fn zig_zag(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
let size = num(p, "size", 10.0).clamp(-1e4, 1e4);
|
||||
let amp = if flag(p, "relative", false) { size / 100.0 * mean_size(b) } else { size };
|
||||
let ridges = num(p, "ridges", 4.0).clamp(0.0, 100.0) as usize;
|
||||
// Each segment makes `ridges + 1` points, and an open path's end one more (all its anchors
|
||||
// when it has no segment). With no ridges, that is at most the path's own anchors.
|
||||
let segs = path.subpaths.iter().map(SubPath::segment_count).fold(0, usize::saturating_add);
|
||||
let ends: usize = path.subpaths.iter().filter(|sp| !sp.closed).map(|sp| if sp.segment_count() > 0 { 1 } else { sp.anchors.len() }).sum();
|
||||
let fit = (max.saturating_sub(ends) / segs.max(1)).saturating_sub(1);
|
||||
let ridges = (num(p, "ridges", 4.0).clamp(0.0, 100.0) as usize).min(fit);
|
||||
let smooth = smooth_points(p);
|
||||
let mut subs = vec![];
|
||||
for sp in &path.subpaths {
|
||||
|
||||
+101
-9
@@ -1083,15 +1083,80 @@ impl<'a> GeomContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Most anchors a chain of geometry effects makes of one path, or of all the paths of a type,
|
||||
/// symbol or image art together; a path that already has more keeps its own count as the limit.
|
||||
/// Roughen resamples each segment into up to 2000 points, Zig Zag into up to 101 and the warps
|
||||
/// into up to 64, so stacked effects multiply: three Roughens of a rectangle needed tens of
|
||||
/// gigabytes (#3578). Each effect builds within it, and one whose result would still pass it is
|
||||
/// left out.
|
||||
pub(crate) const MAX_EFFECT_ANCHORS: usize = 2_000_000;
|
||||
|
||||
/// Most lines the renderer is estimated to draw a chain of geometry effects' result with at
|
||||
/// 1 px/pt ([`util::line_estimate`]), or the path's own estimate when that is more. A large
|
||||
/// Roughen or Zig Zag makes segments thousands of points long, each drawn as up to hundreds of
|
||||
/// lines: two million anchors of them came to 141 million lines, 7 GB in the renderer and past
|
||||
/// the 2²⁷ lines vello takes of one path (#3578). Art of small curves draws its anchors as a few
|
||||
/// lines each, so this rarely binds before [`MAX_EFFECT_ANCHORS`] does.
|
||||
pub(crate) const MAX_EFFECT_LINES: usize = 8_000_000;
|
||||
|
||||
/// What geometry effects may make of a path, or what a path costs: its anchors and the lines the
|
||||
/// renderer is estimated to draw it with.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Budget {
|
||||
pub anchors: usize,
|
||||
pub lines: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
/// The budget of a chain of geometry effects.
|
||||
pub(crate) const EFFECTS: Self = Self { anchors: MAX_EFFECT_ANCHORS, lines: MAX_EFFECT_LINES };
|
||||
|
||||
/// What `path` costs.
|
||||
pub(crate) fn of(path: &PathData) -> Self {
|
||||
Self { anchors: path.anchor_count(), lines: util::line_estimate(path) }
|
||||
}
|
||||
|
||||
/// This budget, raised to `cost` where that is more.
|
||||
pub(crate) fn at_least(self, cost: Self) -> Self {
|
||||
Self { anchors: self.anchors.max(cost.anchors), lines: self.lines.max(cost.lines) }
|
||||
}
|
||||
|
||||
/// Does `cost` fit this budget?
|
||||
pub(crate) fn fits(self, cost: Self) -> bool {
|
||||
cost.anchors <= self.anchors && cost.lines <= self.lines
|
||||
}
|
||||
|
||||
/// What is left of this budget once `cost` is spent.
|
||||
pub(crate) fn minus(self, cost: Self) -> Self {
|
||||
Self { anchors: self.anchors.saturating_sub(cost.anchors), lines: self.lines.saturating_sub(cost.lines) }
|
||||
}
|
||||
|
||||
/// This cost and `cost` together.
|
||||
pub(crate) fn plus(self, cost: Self) -> Self {
|
||||
Self { anchors: self.anchors.saturating_add(cost.anchors), lines: self.lines.saturating_add(cost.lines) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate the visible geometry effects of `effects` on `path`, in order. `bounds` is the
|
||||
/// reference box of the first effect (usually the object's geometric bounds); each later effect
|
||||
/// uses the bounds of its input. Raster and unknown effects are skipped.
|
||||
/// uses the bounds of its input. Raster and unknown effects are skipped, and so is an effect
|
||||
/// whose result would pass 2 million anchors or 8 million lines drawn (or the path's own counts,
|
||||
/// when they are more).
|
||||
pub fn apply_geometry(effects: &[Effect], path: &PathData, bounds: Rect) -> PathData {
|
||||
apply_geometry_with(effects, path, bounds, &GeomContext::default())
|
||||
}
|
||||
|
||||
/// [`apply_geometry`] with an explicit [`GeomContext`].
|
||||
pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext) -> PathData {
|
||||
apply_geometry_within(effects, path, bounds, ctx, Budget::EFFECTS)
|
||||
}
|
||||
|
||||
/// [`apply_geometry_with`] whose effects keep to `budget`, raised to what `path` costs where that
|
||||
/// is more.
|
||||
pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext, budget: Budget) -> PathData {
|
||||
// `budget` raised to what `path` costs, measured once, and only for a path that has geometry
|
||||
// effects.
|
||||
let mut limit = None;
|
||||
let mut cur = path.clone();
|
||||
let mut b = bounds;
|
||||
let mut first = true;
|
||||
@@ -1104,7 +1169,10 @@ pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ct
|
||||
break;
|
||||
}
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
cur = apply_one(&e.id, &p, &cur, b, ctx);
|
||||
let limit = *limit.get_or_insert_with(|| budget.at_least(Budget::of(path)));
|
||||
if let Some(next) = apply_one(&e.id, &p, &cur, b, ctx, limit) {
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
cur
|
||||
}
|
||||
@@ -1114,20 +1182,44 @@ pub fn apply_geometry_bez(effects: &[Effect], path: &BezPath, bounds: Rect, ctx:
|
||||
apply_geometry_with(effects, &PathData::from_bezpath(path), bounds, ctx).to_bezpath()
|
||||
}
|
||||
|
||||
pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext) -> PathData {
|
||||
/// Geometry effect `id` with params `p` on `path`, whose reference box is `b`; `None` when its
|
||||
/// result would not fit `budget` (the effects that multiply anchors build within its anchors).
|
||||
pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, budget: Budget) -> Option<PathData> {
|
||||
let out = apply_unchecked(id, p, path, b, ctx, budget.anchors);
|
||||
let cost = Budget::of(&out);
|
||||
if budget.fits(cost) {
|
||||
return Some(out);
|
||||
}
|
||||
if cost.lines <= budget.lines || !builds_within(id) {
|
||||
return None;
|
||||
}
|
||||
// Anchors drawn as many lines each (a large Roughen or Zig Zag): once more with as many fewer
|
||||
// anchors as there were lines too many, and a tenth to spare, as segments vary in their lines.
|
||||
let fewer = (cost.anchors as f64 * 0.9 * (budget.lines as f64 / cost.lines as f64)) as usize;
|
||||
let out = apply_unchecked(id, p, path, b, ctx, fewer.min(budget.anchors));
|
||||
budget.fits(Budget::of(&out)).then_some(out)
|
||||
}
|
||||
|
||||
/// Does geometry effect `id` build within the anchors it is given?
|
||||
fn builds_within(id: &str) -> bool {
|
||||
matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.")
|
||||
}
|
||||
|
||||
/// [`apply_one`] whose result may pass `max` when the effect doesn't build within it.
|
||||
fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData {
|
||||
use util::*;
|
||||
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item };
|
||||
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints).unwrap_or_else(|| path.clone());
|
||||
}
|
||||
match id {
|
||||
"distort.freeDistort" => distort::free_distort(path, b, p),
|
||||
"distort.freeDistort" => distort::free_distort(path, b, p, max),
|
||||
"distort.puckerBloat" => distort::pucker_bloat(path, b, num(p, "amount", 0.0)),
|
||||
"distort.roughen" => distort::roughen(path, b, p),
|
||||
"distort.transform" => distort::transform(path, b, p, ctx.seed),
|
||||
"distort.roughen" => distort::roughen(path, b, p, max),
|
||||
"distort.transform" => distort::transform_within(path, b, p, ctx.seed, max),
|
||||
"distort.tweak" => distort::tweak(path, b, p),
|
||||
"distort.twist" => distort::twist(path, b, num(p, "angle", 10.0)),
|
||||
"distort.zigZag" => distort::zig_zag(path, b, p),
|
||||
"distort.twist" => distort::twist(path, b, num(p, "angle", 10.0), max),
|
||||
"distort.zigZag" => distort::zig_zag(path, b, p, max),
|
||||
"path.offsetPath" => {
|
||||
let off = num(p, "offset", 10.0).clamp(-1e5, 1e5);
|
||||
if off.abs() < 1e-9 {
|
||||
@@ -1160,7 +1252,7 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo
|
||||
"stylize.roundCorners" => stylize::round_corners(path, num(p, "radius", 10.0)),
|
||||
"stylize.scribble" => stylize::scribble(path, b, p),
|
||||
_ => match id.strip_prefix("warp.").and_then(WarpStyle::from_id) {
|
||||
Some(style) => warp::warp(path, b, style, p),
|
||||
Some(style) => warp::warp(path, b, style, p, max),
|
||||
None => path.clone(),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, shapes};
|
||||
|
||||
use crate::{GeomContext, apply_one, is_geometry, merged_params};
|
||||
use crate::{Budget, GeomContext, apply_one, is_geometry, merged_params};
|
||||
|
||||
/// Can object-level effects apply to `n` only through [`outline_art`] / an offscreen layer (it is
|
||||
/// neither a path nor a container)?
|
||||
@@ -372,35 +372,52 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
|
||||
/// Apply `fx` to every path under `art` as one piece: each effect takes the whole art's bounds as
|
||||
/// its reference box and the art's seed (a random Transform moves the pieces together). Images and
|
||||
/// symbol instances follow a Transform effect the same way ([`transform_placed`]); other geometry
|
||||
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp).
|
||||
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The
|
||||
/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
|
||||
/// whose effect would pass what the others leave of it keeps its shape.
|
||||
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) {
|
||||
reshape_leaves_within(art, fx, Budget::EFFECTS);
|
||||
}
|
||||
|
||||
/// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost.
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) {
|
||||
if fx.is_empty() {
|
||||
return;
|
||||
}
|
||||
let seed = art.id.0;
|
||||
// The placed gradients of type's outlines in `art` (`outline_text`) move and scale with the
|
||||
// pieces, from the outlines' bounds before the effects to their bounds after them.
|
||||
let mut outlines = vec![];
|
||||
type_outline_bounds(art, &mut outlines);
|
||||
let mut used = art_cost(art);
|
||||
let max = budget.at_least(used);
|
||||
for e in fx {
|
||||
let Some(bounds) = art.geometric_bounds() else { break };
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let transform = (e.id == "distort.transform").then(|| crate::distort::transform_map(bounds, ¶ms, seed));
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
// What the other paths leave of the budget.
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
// A gradient paints each copy by itself, not the one piece the copies make together.
|
||||
if let Some((m, copies)) = transform
|
||||
&& copies > 0
|
||||
&& (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient())
|
||||
{
|
||||
copy_with_gradients(leaf, &path, m, copies);
|
||||
let made = copy_with_gradients(leaf, &path, m, copies, room);
|
||||
used = used.minus(before).plus(made);
|
||||
return;
|
||||
}
|
||||
let out = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) });
|
||||
let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else { return };
|
||||
used = used.minus(before).plus(Budget::of(&out));
|
||||
set_geometry(leaf, out, rule);
|
||||
});
|
||||
if let Some((m, copies)) = transform {
|
||||
transform_placed(art, m, copies);
|
||||
}
|
||||
}
|
||||
if !fx.is_empty() && outlines.iter().any(Option::is_some) {
|
||||
if outlines.iter().any(Option::is_some) {
|
||||
rebase_type_outlines(art, &mut outlines.into_iter());
|
||||
}
|
||||
}
|
||||
@@ -408,29 +425,32 @@ pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) {
|
||||
/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies`
|
||||
/// more, each mapped once more by `m` than the last, as a Transform effect copies an object. Each
|
||||
/// copy is an object of its own, so its gradients fit it (a placed gradient moves with it) rather
|
||||
/// than spanning every copy. The copies stop where [`crate::distort::transform_within`]'s would.
|
||||
fn copy_with_gradients(leaf: &mut Node, path: &PathData, m: Affine, copies: usize) {
|
||||
let each = path.anchor_count();
|
||||
let mut anchors = each;
|
||||
/// than spanning every copy. The copies stop where [`crate::distort::transform_within`]'s would,
|
||||
/// or before they pass `budget`. Returns what the copies cost, the original included.
|
||||
fn copy_with_gradients(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, budget: Budget) -> Budget {
|
||||
let mut made = Budget::of(path);
|
||||
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..copies {
|
||||
anchors = anchors.saturating_add(each);
|
||||
if anchors > crate::distort::MAX_COPY_ANCHORS {
|
||||
xf *= m;
|
||||
// A copy scaled up is drawn with more lines.
|
||||
let cost = Budget::of(&path.transformed(xf));
|
||||
if !budget.fits(made.plus(cost)) {
|
||||
break;
|
||||
}
|
||||
xf *= m;
|
||||
let mut copy = leaf.clone();
|
||||
copy.transform(xf, vectorcraft_doc::Scaling::default());
|
||||
if !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
|
||||
break;
|
||||
}
|
||||
placements.push(Arc::new(copy));
|
||||
made = made.plus(cost);
|
||||
}
|
||||
// The copies become nodes of their own under a group with the object's id and name.
|
||||
let mut g = Node::group(leaf.id, placements);
|
||||
g.name = leaf.name.clone();
|
||||
*leaf = g;
|
||||
made
|
||||
}
|
||||
|
||||
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
|
||||
@@ -597,6 +617,18 @@ fn for_each_leaf(n: &mut Node, f: &mut dyn FnMut(&mut Node)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the paths under `n` that [`for_each_leaf`] visits cost together, as [`leaf_geometry`]
|
||||
/// gives them.
|
||||
fn art_cost(n: &Node) -> Budget {
|
||||
let none = Budget { anchors: 0, lines: 0 };
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, path, .. } => Budget::of(path),
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).map(Budget::of).fold(none, Budget::plus),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().map(|c| art_cost(c)).fold(none, Budget::plus),
|
||||
_ => none,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn leaf_geometry(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => Some((path.clone(), *rule)),
|
||||
|
||||
@@ -287,6 +287,153 @@ fn stacked_transform_copies_stay_within_the_image_budget() {
|
||||
assert_eq!(count(&evaluate_container(&g).unwrap()), 1001);
|
||||
}
|
||||
|
||||
/// What `effects` make of `path` within `budget`.
|
||||
fn within(effects: &[Effect], path: &PathData, budget: Budget) -> PathData {
|
||||
apply_geometry_within(effects, path, path.bounds().unwrap(), &GeomContext::default(), budget)
|
||||
}
|
||||
|
||||
/// What `effects` make of `path` within a budget of `max` anchors (and any number of lines).
|
||||
fn anchors_within(effects: &[Effect], path: &PathData, max: usize) -> PathData {
|
||||
within(effects, path, Budget { anchors: max, lines: usize::MAX })
|
||||
}
|
||||
|
||||
/// #3578: stacked Roughens multiply their points (up to 2000 a segment); the anchors they make
|
||||
/// stay within the budget, each Roughen spacing its points further apart where it must.
|
||||
#[test]
|
||||
fn stacked_roughens_stay_within_the_anchor_budget() {
|
||||
let rough = fx("distort.roughen", json!({"size": 10000, "relative": false, "detail": 100}));
|
||||
let outs: Vec<PathData> = (1..=3).map(|n| anchors_within(&vec![rough.clone(); n], &square(), 10_000)).collect();
|
||||
let counts: Vec<usize> = outs.iter().map(PathData::anchor_count).collect();
|
||||
// 100 pt sides at 100 points per inch: 139 points each, within the budget.
|
||||
assert_eq!(counts[0], 4 * 139);
|
||||
assert_eq!(outs[0], run("distort.roughen", rough.params.clone(), &square()));
|
||||
assert!(counts[1..].iter().all(|&c| c > 5_000 && c <= 10_000), "{counts:?}");
|
||||
// The third Roughen still roughens, with its points spaced to fit.
|
||||
assert_ne!(outs[2], outs[1]);
|
||||
assert!(outs.iter().all(all_finite));
|
||||
}
|
||||
|
||||
/// #3578: stacked Zig Zags multiply their points (up to 101 a segment); each segment gets as many
|
||||
/// ridges as fit the budget.
|
||||
#[test]
|
||||
fn stacked_zig_zags_stay_within_the_anchor_budget() {
|
||||
let zig = fx("distort.zigZag", json!({"ridges": 100, "points": "corner"}));
|
||||
let counts: Vec<usize> = (1..=3).map(|n| anchors_within(&vec![zig.clone(); n], &square(), 10_000).anchor_count()).collect();
|
||||
// 4 × 101 points; then 23 ridges a segment fit (404 × 24); then none, each point displaced.
|
||||
assert_eq!(counts, [404, 9_696, 9_696]);
|
||||
let twice = anchors_within(&vec![zig.clone(); 2], &square(), 10_000);
|
||||
assert_ne!(anchors_within(&vec![zig.clone(); 3], &square(), 10_000), twice);
|
||||
// An open path's end point counts as well.
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false));
|
||||
assert_eq!(anchors_within(&[zig], &line, 30).anchor_count(), 30, "the start, 28 ridges and the end");
|
||||
}
|
||||
|
||||
/// #3578: every effect that multiplies anchors builds within the budget, stacked or not, and one
|
||||
/// that doesn't (Round Corners doubles them) is left out where it would pass it.
|
||||
#[test]
|
||||
fn stacked_geometry_effects_stay_within_the_anchor_budget() {
|
||||
let star = shapes::star(Point::new(150.0, 100.0), 70.0, 32.0, 5, 0.0);
|
||||
for (id, params) in [
|
||||
("distort.roughen", json!({"size": 50, "detail": 100})),
|
||||
("distort.zigZag", json!({"ridges": 100, "size": 30})),
|
||||
("distort.twist", json!({"angle": 3600})),
|
||||
("distort.freeDistort", json!({"corners": [[0.3, -2], [1, 0], [4, 1], [0, 3]]})),
|
||||
("warp.twist", json!({"bend": 100})),
|
||||
("distort.transform", json!({"copies": 1000, "moveH": 1})),
|
||||
] {
|
||||
for n in 1..=4 {
|
||||
let out = anchors_within(&vec![fx(id, params.clone()); n], &star, 2_000);
|
||||
assert!(out.anchor_count() <= 2_000 && all_finite(&out), "{id} × {n}: {}", out.anchor_count());
|
||||
}
|
||||
}
|
||||
let zig = fx("distort.zigZag", json!({"ridges": 100, "points": "corner"}));
|
||||
let full = anchors_within(&[zig.clone(), zig.clone()], &square(), 10_000);
|
||||
let round = fx("stylize.roundCorners", json!({"radius": 1}));
|
||||
assert_eq!(anchors_within(&[zig.clone(), zig.clone(), round.clone()], &square(), 10_000), full);
|
||||
assert_ne!(anchors_within(&[zig, round], &square(), 10_000), run("distort.zigZag", json!({"ridges": 100, "points": "corner"}), &square()));
|
||||
}
|
||||
|
||||
/// #3578: a path with more anchors than the budget keeps its count as its budget: effects that
|
||||
/// add none apply, and the others add none.
|
||||
#[test]
|
||||
fn a_path_past_the_anchor_budget_still_takes_effects() {
|
||||
let star = shapes::star(Point::new(150.0, 100.0), 70.0, 32.0, 25, 0.0);
|
||||
let n = star.anchor_count();
|
||||
for (id, params) in [
|
||||
("distort.tweak", json!({})),
|
||||
("distort.roughen", json!({"detail": 100})),
|
||||
("distort.zigZag", json!({"ridges": 100})),
|
||||
("distort.twist", json!({"angle": 90})),
|
||||
] {
|
||||
let out = anchors_within(&[fx(id, params)], &star, 10);
|
||||
assert_eq!(out.anchor_count(), n, "{id}");
|
||||
assert_ne!(out, star, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: the effects on type, symbols and images reshape all their paths within one budget.
|
||||
#[test]
|
||||
fn stacked_effects_on_art_stay_within_the_anchor_budget() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::NodeId;
|
||||
let id = NodeId(9);
|
||||
let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), Appearance::default()));
|
||||
let mut art = Node::group(id, (0..10).map(|k| leaf(k as f64 * 120.0)).collect());
|
||||
let rough = fx("distort.roughen", json!({"size": 50, "detail": 100}));
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&rough, &rough, &rough], Budget { anchors: 5_000, lines: usize::MAX });
|
||||
let mut total = 0;
|
||||
let mut reshaped = 0;
|
||||
for c in art.children().into_iter().flatten() {
|
||||
let path = c.path_data().unwrap();
|
||||
total += path.anchor_count();
|
||||
reshaped += usize::from(path.anchor_count() > 4);
|
||||
}
|
||||
// One Roughen alone makes 10 × 556: the budget binds, and goes to the paths in turn.
|
||||
assert!(total > 4_000 && total <= 5_000, "{total}");
|
||||
assert_eq!(reshaped, 10);
|
||||
}
|
||||
|
||||
/// #3578: a large Roughen draws each of its points as many lines; they stay within the budget,
|
||||
/// the Roughen built again with fewer points where they wouldn't.
|
||||
#[test]
|
||||
fn large_roughens_stay_within_the_line_budget() {
|
||||
let rough = fx("distort.roughen", json!({"size": 10000, "relative": false, "detail": 100}));
|
||||
let budget = Budget { anchors: 100_000, lines: 200_000 };
|
||||
let once = within(std::slice::from_ref(&rough), &square(), budget);
|
||||
assert_eq!(once, run("distort.roughen", rough.params.clone(), &square()), "within both budgets");
|
||||
let twice = within(&[rough.clone(), rough], &square(), budget);
|
||||
let cost = Budget::of(&twice);
|
||||
assert!(budget.fits(cost) && cost.lines > 100_000, "{cost:?}");
|
||||
assert!(cost.anchors < 10_000 && twice != once, "the second Roughen with fewer points: {cost:?}");
|
||||
// Art of small curves draws its anchors as a few lines each: the anchors bind first.
|
||||
let zig = fx("distort.zigZag", json!({"ridges": 100, "size": 2}));
|
||||
let out = within(&[zig.clone(), zig], &square(), Budget { anchors: 10_000, lines: 100_000 });
|
||||
assert!(out.anchor_count() > 9_000 && util::line_estimate(&out) < 50_000, "{}", util::line_estimate(&out));
|
||||
}
|
||||
|
||||
/// Straight segments are one line each, and a curve as many as Wang's formula takes at 0.25 px.
|
||||
#[test]
|
||||
fn line_estimate_counts_the_lines_a_path_is_drawn_with() {
|
||||
assert_eq!(util::line_estimate(&square()), 4);
|
||||
let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert_eq!(util::line_estimate(&circle), 4 * 9, "a quarter circle of 50 pt in 9 lines");
|
||||
let big = shapes::ellipse(Rect::new(0.0, 0.0, 10_000.0, 10_000.0));
|
||||
assert_eq!(util::line_estimate(&big), 4 * 84, "100 times as large: about 10 times the lines");
|
||||
}
|
||||
|
||||
/// #3578: the issue's input, a large rectangle with three max-detail Roughens of the largest
|
||||
/// size, at the real budgets: two million anchors of it were 141 million lines to draw.
|
||||
#[test]
|
||||
fn three_max_detail_roughens_stay_within_the_effect_budget() {
|
||||
let rough = fx("distort.roughen", json!({"size": 10000, "relative": false, "detail": 100}));
|
||||
let rect = shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0));
|
||||
let out = apply_geometry(&vec![rough.clone(); 3], &rect, rect.bounds().unwrap());
|
||||
let cost = Budget::of(&out);
|
||||
assert!(Budget::EFFECTS.fits(cost) && cost.lines > MAX_EFFECT_LINES / 2, "{cost:?}");
|
||||
assert_ne!(out, apply_geometry(&[rough], &rect, rect.bounds().unwrap()), "more than one Roughen applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_copies_stop_before_they_overflow() {
|
||||
let out = run("distort.transform", json!({"scaleH": 100000, "scaleV": 100000, "copies": 1000}), &square());
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Parameter parsing, deterministic noise and path-mapping helpers.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Anchor, CubicBez, ParamCurve, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_geom::{Anchor, CubicBez, ParamCurve, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
/// Number param (also accepts numeric strings such as `"10 pt"`); non-finite → default.
|
||||
pub fn num(p: &Value, key: &str, default: f64) -> f64 {
|
||||
@@ -69,8 +69,25 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
if sp.segment_is_line(i) { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }
|
||||
}
|
||||
|
||||
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`).
|
||||
pub use vectorcraft_doc::live::map_nonlinear;
|
||||
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
|
||||
/// segments into pieces within an anchor budget.
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, pieces};
|
||||
|
||||
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
|
||||
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
|
||||
/// `sqrt(0.75 × d / 0.25)` for the largest second difference `d` of its control points.
|
||||
pub fn line_estimate(path: &PathData) -> usize {
|
||||
let curve = |c: CubicBez| {
|
||||
let d =
|
||||
(c.p0.to_vec2() - c.p1.to_vec2() * 2.0 + c.p2.to_vec2()).hypot().max((c.p1.to_vec2() - c.p2.to_vec2() * 2.0 + c.p3.to_vec2()).hypot());
|
||||
// A NaN casts to 0 and an infinity to the largest count.
|
||||
((3.0 * d).sqrt().ceil() as usize).max(1)
|
||||
};
|
||||
path.subpaths
|
||||
.iter()
|
||||
.flat_map(|sp| (0..sp.segment_count()).map(move |i| if sp.segment_is_line(i) { 1 } else { curve(sp.segment(i)) }))
|
||||
.fold(0, usize::saturating_add)
|
||||
}
|
||||
|
||||
/// Smooth subpath through `pts` (Catmull-Rom tangents, see [`turn_tangent`] for sharp turns).
|
||||
pub fn catmull_rom(pts: &[Point], closed: bool, tension: f64) -> SubPath {
|
||||
|
||||
@@ -10,8 +10,8 @@ use crate::util::*;
|
||||
|
||||
pub use vectorcraft_doc::live::{WarpStyle, warp_point};
|
||||
|
||||
/// Apply a warp to `path` using box `b`.
|
||||
pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value) -> PathData {
|
||||
/// Apply a warp to `path` using box `b`, making at most `max` anchors ([`map_nonlinear_within`]).
|
||||
pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -> PathData {
|
||||
let bend = num(p, "bend", 50.0).clamp(-100.0, 100.0) / 100.0;
|
||||
let dh = num(p, "horizontal", 0.0).clamp(-100.0, 100.0) / 100.0;
|
||||
let dv = num(p, "vertical", 0.0).clamp(-100.0, 100.0) / 100.0;
|
||||
@@ -30,5 +30,5 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value) -> PathData {
|
||||
Point::new(c.x + x2 * hw, c.y + y2 * hh)
|
||||
};
|
||||
let piece = b.width().hypot(b.height()) / 24.0;
|
||||
map_nonlinear(path, piece, f)
|
||||
map_nonlinear_within(path, piece, max, f)
|
||||
}
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Builder",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it goes directly above it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} → {ids, merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
|
||||
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} → {ids, merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
|
||||
has_selection_or_ids,
|
||||
sb_merge
|
||||
),
|
||||
@@ -283,10 +283,14 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& let Some((i, run)) = map.stroke_at(&outlines, q, tol)
|
||||
&& let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i))
|
||||
&& let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn))
|
||||
&& !rest.is_empty()
|
||||
&& rest.length() > b::outline_snap(drawn)
|
||||
{
|
||||
// The path keeps the rest of it, and a copy of it with the run under the click goes
|
||||
// directly above it; the other objects stay as they are.
|
||||
// directly above it; the other objects stay as they are. Gradients fitted to the
|
||||
// path's bounds keep that fit on both.
|
||||
if let Some(n) = d.node_mut(leaf.id) {
|
||||
n.pin_gradients();
|
||||
}
|
||||
let pieces = [rest, PathData::single(run)].into_iter().filter(|pd| !pd.is_empty()).collect();
|
||||
let mut replaced = Beside::replacing(d, &[leaf.id]);
|
||||
let new_ids = replace_with_pieces(d, &mut replaced, leaf.id, pieces)?;
|
||||
@@ -423,7 +427,8 @@ fn replace_roots(d: &mut Document, roots: &[NodeId], nodes: Vec<Node>) -> Result
|
||||
|
||||
/// What is left of path or compound path `src`: a copy of it with a fresh id and the geometry `path`
|
||||
/// (a path for one subpath, else a compound path, as [`shape_node`] makes them). It keeps the rest
|
||||
/// of `src`: its look, name, opacity mask and attributes, and its fill rule unless `rule` is given.
|
||||
/// of `src`: its look, with gradients fitted to its bounds kept where they were on it, its name,
|
||||
/// opacity mask and attributes, and its fill rule unless `rule` is given.
|
||||
fn remnant(d: &mut Document, src: &Node, path: PathData, rule: Option<FillRule>) -> Node {
|
||||
let own = match &src.kind {
|
||||
NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule,
|
||||
@@ -431,6 +436,7 @@ fn remnant(d: &mut Document, src: &Node, path: PathData, rule: Option<FillRule>)
|
||||
};
|
||||
let shaped = shape_node(d, path, None);
|
||||
let mut n = src.clone();
|
||||
n.pin_gradients();
|
||||
n.id = shaped.id;
|
||||
n.kind = shaped.kind;
|
||||
if let NodeKind::Path { rule: r, .. } | NodeKind::Compound { rule: r, .. } = &mut n.kind {
|
||||
|
||||
@@ -4,7 +4,7 @@ use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::dimension::{ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, TextAlignment, TextPosition};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -227,15 +227,58 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<()> {
|
||||
next.moved = None;
|
||||
}
|
||||
}
|
||||
if next != old || before.node(id).and_then(|n| n.extras().dimension.as_deref()).is_some_and(|d| d != &next) {
|
||||
// A new document colour mode (Document Color Mode) redraws every dimension in it.
|
||||
if next != old
|
||||
|| before.color_mode != doc.color_mode
|
||||
|| before.node(id).and_then(|n| n.extras().dimension.as_deref()).is_some_and(|d| d != &next)
|
||||
{
|
||||
replace(doc, id, next)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn paint(c: [u8; 3]) -> Paint {
|
||||
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
|
||||
/// Redraw the dimensions of an opened document whose art isn't in its colour mode: files saved
|
||||
/// before dimensions followed the colour mode have RGB dimensions in CMYK documents. A dimension
|
||||
/// that can't be redrawn keeps the art it has.
|
||||
pub(crate) fn conform(doc: &mut Document) {
|
||||
if !doc.dimensions {
|
||||
return;
|
||||
}
|
||||
let mode = doc.color_mode;
|
||||
let off_mode = |c: &Color| match mode {
|
||||
ColorMode::Rgb => matches!(c, Color::Cmyk { .. }),
|
||||
ColorMode::Cmyk => matches!(c, Color::Rgb { .. }),
|
||||
};
|
||||
let mut stale = Vec::new();
|
||||
doc.walk(|n| {
|
||||
if let Some(d) = &n.extras().dimension {
|
||||
let mut off = false;
|
||||
n.walk(&mut |c| off |= [c.appearance.fill_paint(), c.appearance.stroke_paint()].iter().filter_map(|p| p.color()).any(|c| off_mode(&c)));
|
||||
if off {
|
||||
stale.push((n.id, (**d).clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
for (id, d) in stale {
|
||||
// An error leaves this dimension as it was; the others are still redrawn.
|
||||
let _ = replace(doc, id, d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Option colour `c` as a paint in the document's colour model: in a CMYK document black is K
|
||||
/// only (a rich four-ink black would print a black dimension in every plate) and other colours
|
||||
/// convert through the active colour settings.
|
||||
fn paint(c: [u8; 3], mode: ColorMode) -> Paint {
|
||||
let rgb = Color::rgb8(c[0], c[1], c[2]);
|
||||
Paint::solid(match mode {
|
||||
ColorMode::Rgb => rgb,
|
||||
ColorMode::Cmyk if c == [0, 0, 0] => Color::cmyk(0.0, 0.0, 0.0, 1.0),
|
||||
ColorMode::Cmyk => {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cms.convert(&rgb, vectorcraft_color::cms::Model::Cmyk, cms.settings().intent)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn line(a: Point, b: Point) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
@@ -244,10 +287,10 @@ fn line(a: Point, b: Point) -> BezPath {
|
||||
p
|
||||
}
|
||||
|
||||
fn appearance(o: &DimensionOptions, ext: bool, arrows: bool) -> Appearance {
|
||||
fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> Appearance {
|
||||
let (color, width, kind) =
|
||||
if ext { (o.extension_color, o.extension_weight, o.extension_type) } else { (o.line_color, o.line_weight, o.line_type) };
|
||||
let mut a = Appearance::basic(Paint::None, paint(color), width);
|
||||
let mut a = Appearance::basic(Paint::None, paint(color, mode), width);
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
st.dash = match kind {
|
||||
LineType::Dashed => Some(Dash { pattern: vec![width * 5.0, width * 3.0], ..Default::default() }),
|
||||
@@ -285,6 +328,7 @@ fn along(o: &DimensionOptions) -> f64 {
|
||||
fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<Node>>> {
|
||||
d.validate().map_err(error)?;
|
||||
let o = &d.options;
|
||||
let mode = doc.color_mode;
|
||||
let label = d.label().map_err(error)?;
|
||||
let mut paths: Vec<(BezPath, Appearance)> = Vec::new();
|
||||
let mut angle = 0.0;
|
||||
@@ -301,11 +345,11 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
for i in 1..=64 {
|
||||
arc.line_to(on(i as f64 / 64.0));
|
||||
}
|
||||
paths.push((arc, appearance(o, false, true)));
|
||||
paths.push((arc, appearance(o, mode, false, true)));
|
||||
if !o.hide_extensions {
|
||||
for p in [d.a, d.b] {
|
||||
let dir = (p - d.vertex) / (p - d.vertex).hypot();
|
||||
paths.push((line(d.vertex + dir * o.extension_offset, d.vertex + dir * (r + o.extension_length)), appearance(o, true, false)));
|
||||
paths.push((line(d.vertex + dir * o.extension_offset, d.vertex + dir * (r + o.extension_length)), appearance(o, mode, true, false)));
|
||||
}
|
||||
}
|
||||
let dir = Vec2::from_angle(start + sweep * along(o));
|
||||
@@ -333,7 +377,7 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
};
|
||||
if d.mode == DimensionMode::Linear && !o.hide_extensions {
|
||||
for (p, q) in [(d.a, a), (d.b, b)] {
|
||||
paths.push((line(p + outward * o.extension_offset, q + outward * o.extension_length), appearance(o, true, false)));
|
||||
paths.push((line(p + outward * o.extension_offset, q + outward * o.extension_length), appearance(o, mode, true, false)));
|
||||
}
|
||||
}
|
||||
angle = u.atan2();
|
||||
@@ -342,13 +386,13 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
}
|
||||
let shift = o.text_offset + o.font_size * 0.5;
|
||||
text_at = a.lerp(b, along(o)) + outward * if away { shift } else { -shift };
|
||||
paths.push((line(a, b), appearance(o, false, true)));
|
||||
paths.push((line(a, b), appearance(o, mode, false, true)));
|
||||
}
|
||||
let style = CharStyle {
|
||||
font_family: o.font_family.clone(),
|
||||
font_style: o.font_style.clone(),
|
||||
size: o.font_size,
|
||||
fill: paint(o.text_color),
|
||||
fill: paint(o.text_color, mode),
|
||||
..Default::default()
|
||||
};
|
||||
let mut text = TextObject::point(Point::ZERO, &label, style);
|
||||
@@ -366,7 +410,7 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
}
|
||||
let id = old.get(children.len()).copied().unwrap_or_else(|| doc.alloc_id());
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(text)));
|
||||
node.appearance = Appearance::basic(paint(o.text_color), Paint::None, 0.0).into();
|
||||
node.appearance = Appearance::basic(paint(o.text_color, mode), Paint::None, 0.0).into();
|
||||
children.push(Arc::new(node));
|
||||
Ok(children)
|
||||
}
|
||||
@@ -477,10 +477,12 @@ pub(crate) fn ok() -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Leaves whose appearance a paint command changes: groups and layers expand to their contents,
|
||||
/// and compound paths own their children's appearance.
|
||||
/// and compound paths own their children's appearance, so a member stands for its compound path
|
||||
/// (#3692), which is listed once.
|
||||
pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let d = &s.doc()?.doc;
|
||||
let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
@@ -490,11 +492,13 @@ pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
out.push(c.id)
|
||||
}
|
||||
}),
|
||||
_ => out.push(*id),
|
||||
_ => out.push(compound(*id).unwrap_or(*id)),
|
||||
}
|
||||
}
|
||||
let comp: Vec<NodeId> = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect();
|
||||
out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c)));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|id| seen.insert(*id));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
//! [`Session::attach_plugin_store`]) or from every `*.wasm` in the Additional Plug-ins Folder
|
||||
//! preference, and listed with `plugin.list` / `plugin.info`. Object filters run
|
||||
//! with `plugin.run` on the selected paths and compound paths (one undo step, transactional: a
|
||||
//! plug-in that fails leaves the document untouched); live-effect plug-ins are applied like any
|
||||
//! effect (`effect.apply {effect: "plugin.<id>"}`) and drawn by `vectorcraft-effects`; exporters
|
||||
//! add a file format that `document.export` writes (`fileio::plugin_formats`).
|
||||
//! plug-in that fails leaves the document untouched), and read and write the data they keep with
|
||||
//! the document ([`vectorcraft_doc::plugin_data`], theirs alone); live-effect plug-ins are applied
|
||||
//! like any effect (`effect.apply {effect: "plugin.<id>"}`) and drawn by `vectorcraft-effects`;
|
||||
//! exporters add a file format that `document.export` writes (`fileio::plugin_formats`).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -60,8 +61,9 @@ fn plugin_by_id(cmd: &str, p: &Value) -> Result<Arc<Plugin>> {
|
||||
}
|
||||
|
||||
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
|
||||
/// parameters and `_context`, and applies its output as one undo step ([`objects::apply_output`];
|
||||
/// effect records as [`admit_effects`] admits them). → `{plugin, ids}`: what it made or changed,
|
||||
/// parameters and `_context` (what it keeps with the document included), and applies its output as
|
||||
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them),
|
||||
/// with what it keeps with the document from now on. → `{plugin, ids}`: what it made or changed,
|
||||
/// which is then selected.
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.run";
|
||||
@@ -85,12 +87,17 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bounds = st.doc.bounds_of(&inputs, false);
|
||||
let board = bounds.and_then(|b| st.doc.artboard_at(b.center())).and_then(|i| st.doc.artboards.get(i)).or(st.doc.artboards.first());
|
||||
let rect = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]);
|
||||
params["_context"] = json!({"mode": "filter", "bounds": bounds.map(rect), "artboard": board.map(|a| rect(a.rect))});
|
||||
// What the plug-in keeps with the document, as it last wrote it.
|
||||
let data = st.doc.plugin_data(&m.id).cloned().unwrap_or(Value::Null);
|
||||
params["_context"] = json!({"mode": "filter", "bounds": bounds.map(rect), "artboard": board.map(|a| rect(a.rect)), "documentData": data});
|
||||
let input = objects::encode_input(&st.doc, &inputs);
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| bad(C, e.to_string()))?;
|
||||
let out = objects::decode(&plugin.run(&input, ¶ms).map_err(err)?).map_err(err)?;
|
||||
let out = objects::decode_output(&plugin.run(&input, ¶ms).map_err(err)?).map_err(err)?;
|
||||
let ids = s.edit(m.name.trim_end_matches('…'), |d, sel| {
|
||||
let ids = objects::apply_output(d, &inputs, out, parent, &admit_effects).map_err(err)?;
|
||||
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
|
||||
if let Some(data) = out.document_data {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
|
||||
@@ -235,6 +235,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("measurementLabels", "Smart Guides", "Display Options", "Measurement Labels", bool),
|
||||
p!("spacingGuides", "Smart Guides", "Display Options", "Spacing Guides", bool),
|
||||
p!("snappingTolerance", "Smart Guides", "", "Snapping Tolerance", num(0.0, 40.0, "pt")),
|
||||
p!("snapTangent", "Smart Guides", "Geometric Guides", "Snap to Tangent", bool),
|
||||
p!("snapPerpendicular", "Smart Guides", "Geometric Guides", "Snap to Perpendicular", bool),
|
||||
// Slices
|
||||
p!("showSliceNumbers", "Slices", "", "Show Slice Numbers", bool),
|
||||
p!("sliceLineColor", "Slices", "", "Line Color", color),
|
||||
|
||||
@@ -573,6 +573,11 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
children.push(Arc::new(Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))));
|
||||
continue;
|
||||
}
|
||||
// COLR glyphs become groups of their layers, in place, with ids of the document's.
|
||||
if let Some(art) = g.placed_colour(t.xf) {
|
||||
children.push(Arc::new(d.reid(&art)));
|
||||
continue;
|
||||
}
|
||||
let path = PathData::from_bezpath(&g.outline).transformed(t.xf);
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
|
||||
@@ -969,6 +969,8 @@ pub struct Prefs {
|
||||
pub measurement_labels: bool,
|
||||
pub spacing_guides: bool,
|
||||
pub snapping_tolerance: f64,
|
||||
pub snap_tangent: bool,
|
||||
pub snap_perpendicular: bool,
|
||||
// Slices
|
||||
pub show_slice_numbers: bool,
|
||||
pub slice_line_color: String,
|
||||
@@ -1218,6 +1220,8 @@ impl Default for Prefs {
|
||||
measurement_labels: true,
|
||||
spacing_guides: true,
|
||||
snapping_tolerance: 4.0,
|
||||
snap_tangent: true,
|
||||
snap_perpendicular: true,
|
||||
show_slice_numbers: true,
|
||||
slice_line_color: s("#ff3f3f"),
|
||||
hyphenation_language: s("English: USA"),
|
||||
@@ -1415,6 +1419,9 @@ pub struct Session {
|
||||
/// Where folder searches may go; `None`: this computer's rules ([`cmd::findfiles::Rules`]).
|
||||
/// Tests set it.
|
||||
pub search_rules: Option<cmd::findfiles::Rules>,
|
||||
/// Canvas feedback cached for the pending deferred preview ([`Session::overlays`]); cleared
|
||||
/// when the preview params change or the interaction ends.
|
||||
pub(crate) deferred_overlay_cache: Option<(String, Value, Vec<vectorcraft_tools::Overlay>)>,
|
||||
/// The walker threads a folder search starts; `None`: [`cmd::findfiles::threads`]. Tests set
|
||||
/// it.
|
||||
pub search_threads: Option<usize>,
|
||||
@@ -1489,6 +1496,7 @@ impl Session {
|
||||
font_search: None,
|
||||
link_search: None,
|
||||
search_rules: None,
|
||||
deferred_overlay_cache: None,
|
||||
search_threads: None,
|
||||
link_stamps: Default::default(),
|
||||
link_scan: None,
|
||||
@@ -1579,6 +1587,7 @@ impl Session {
|
||||
Self::refresh_text_bounds(&mut doc);
|
||||
// Guides from files saved before guides had layers go on a layer.
|
||||
doc.adopt_guides();
|
||||
cmd::dimension::conform(&mut doc);
|
||||
self.reset_tool_for_doc_switch();
|
||||
let mut st = DocState::new(doc, path);
|
||||
st.history.limit = self.prefs.history_states as usize;
|
||||
@@ -1596,6 +1605,7 @@ impl Session {
|
||||
doc.limit_depth();
|
||||
Self::refresh_text_bounds(&mut doc);
|
||||
doc.adopt_guides();
|
||||
cmd::dimension::conform(&mut doc);
|
||||
if self.active == Some(index) {
|
||||
// Pending tool work (typing, a drag) belongs to the content being thrown away.
|
||||
self.reset_tool_for_doc_switch();
|
||||
@@ -1941,12 +1951,23 @@ impl Session {
|
||||
|
||||
// ---------- interactions (live drags) ----------
|
||||
|
||||
pub(crate) fn clear_deferred_overlay_cache(&mut self) {
|
||||
self.deferred_overlay_cache = None;
|
||||
}
|
||||
|
||||
/// The interaction's latest preview command when the document is still its snapshot (deferred
|
||||
/// Real-time Drawing), regardless of the preference at commit or overlay time.
|
||||
pub(crate) fn unapplied_interaction_preview(&self) -> Option<(String, Value)> {
|
||||
self.active().and_then(|d| d.interaction.as_ref().filter(|it| std::sync::Arc::ptr_eq(&it.doc, &d.doc)).and_then(|it| it.preview.clone()))
|
||||
}
|
||||
|
||||
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
|
||||
// Typing in progress is kept first: a drag or a dialog's preview would otherwise start
|
||||
// from the snapshot taken before the typing, and drop it (#1881).
|
||||
if label != "Typing" && cmd::typing_in_progress(self) {
|
||||
cmd::settle_interaction(self)?;
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
let st = self.doc_mut()?;
|
||||
if st.interaction.is_some() {
|
||||
return Ok(());
|
||||
@@ -2000,6 +2021,7 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn commit_interaction(&mut self) -> Result<()> {
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.remember_pending_paint();
|
||||
let st = self.doc_mut()?;
|
||||
let Some(mut it) = st.interaction.take() else { return Ok(()) };
|
||||
@@ -2052,6 +2074,7 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn cancel_interaction(&mut self) -> Result<()> {
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.pending_paint = None;
|
||||
let guides_locked = self.menu.guides_locked;
|
||||
let st = self.doc_mut()?;
|
||||
@@ -2300,6 +2323,8 @@ mod tests_colormgmt;
|
||||
#[cfg(test)]
|
||||
mod tests_colorthemes;
|
||||
#[cfg(test)]
|
||||
mod tests_compoundpaint;
|
||||
#[cfg(test)]
|
||||
mod tests_containers;
|
||||
#[cfg(test)]
|
||||
mod tests_css;
|
||||
|
||||
@@ -825,6 +825,33 @@ fn shape_builder_click_on_a_whole_open_path_does_not_split_it() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before);
|
||||
}
|
||||
|
||||
/// A click on a stroke whose run would leave no more of the path than the cut tolerance (0.05 pt
|
||||
/// for a 100 pt path) does not split it: here the line's last 0.01 pt is all that would be left.
|
||||
/// The command refuses the click as outside every region, and the tool shows no scissors and no
|
||||
/// highlight there and runs no command on a click.
|
||||
#[test]
|
||||
fn shape_builder_click_on_a_stroke_does_not_split_off_all_but_a_speck() {
|
||||
let mut s = session();
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100.01, "y": 0}]})).unwrap();
|
||||
let p = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let undo_before = s.doc().unwrap().history.undo.len();
|
||||
let err = s.execute("shapeBuilder.merge", &json!({"points": [[50, 1]], "splitStroke": true})).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(err.contains("no region under the pointer"), "{err}");
|
||||
assert_eq!((layer_children(&s), shapes_of(&s, &[p])), (1, vec![(false, 3, 100.01)]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"values": {"clickStrokeSplitsPath": true}})).unwrap();
|
||||
let journal = s.journal.len();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 1.0), v).unwrap();
|
||||
assert!(s.overlays(v).is_empty(), "{:?}", s.overlays(v));
|
||||
assert_eq!(s.cursor(vectorcraft_geom::Point::new(50.0, 1.0), Mods::default(), v), vectorcraft_tools::Cursor::ShapeBuilder);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 1.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 1.0), v).unwrap();
|
||||
assert_eq!((s.journal.len(), layer_children(&s)), (journal, 1), "the click runs no command");
|
||||
}
|
||||
|
||||
/// The stroke a click splits ends at the points where other paths cross it as well as at the
|
||||
/// path's anchors: A's right side inside B, then a line piece inside a square. A click away from
|
||||
/// every stroke merges and an erase click deletes, as they do without the option.
|
||||
@@ -860,6 +887,46 @@ fn shape_builder_stroke_split_stops_at_crossings_and_anchors() {
|
||||
assert_eq!(lengths, vec![400.0, 40.0, 100.0], "the square, the line's two loose ends, the piece");
|
||||
}
|
||||
|
||||
/// The run a click splits off goes the way its path goes, so arrowheads and the other settings that
|
||||
/// follow a stroke's direction stay at the ends they were at: a line and a rectangle, each as drawn
|
||||
/// and reversed.
|
||||
#[test]
|
||||
fn shape_builder_stroke_split_keeps_the_path_direction() {
|
||||
let ends = |s: &Session, id: NodeId| {
|
||||
let (p, _) = outline(&node(s, id));
|
||||
let sp = &p.subpaths[0];
|
||||
(sp.anchors.first().unwrap().p, sp.anchors.last().unwrap().p)
|
||||
};
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
for reverse in [false, true] {
|
||||
let mut s = session();
|
||||
let (a, l) = square_and_line(&mut s);
|
||||
if reverse {
|
||||
s.execute("path.reverse", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap();
|
||||
}
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[51, 50]], "splitStroke": true})).unwrap();
|
||||
let split = NodeId(r["split"].as_u64().unwrap());
|
||||
let want = if reverse { (pt(50.0, 100.0), pt(50.0, 0.0)) } else { (pt(50.0, 0.0), pt(50.0, 100.0)) };
|
||||
assert_eq!(ends(&s, split), want, "the line, reversed: {reverse}");
|
||||
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
if reverse {
|
||||
s.execute("path.reverse", &json!({"ids": [a.0]})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let (p, _) = outline(&node(&s, a));
|
||||
let sp = &p.subpaths[0];
|
||||
let n = sp.anchors.len();
|
||||
// The rectangle's top side, from the anchor the path reaches it at.
|
||||
let want = (0..n).map(|k| (sp.anchors[k].p, sp.anchors[(k + 1) % n].p)).find(|(x, y)| x.y == 0.0 && y.y == 0.0).unwrap();
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[50, -1]], "splitStroke": true})).unwrap();
|
||||
let split = NodeId(r["split"].as_u64().unwrap());
|
||||
assert_eq!(ends(&s, split), want, "the rectangle, reversed: {reverse}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A split replaces only the path it splits: the two paths take its place in the stacking order and
|
||||
/// in its group, and the other selected objects stay as they are. A path in a Live Paint group does
|
||||
/// not split.
|
||||
@@ -932,6 +999,43 @@ fn shape_builder_stroke_split_with_swatches_paints_the_stroke() {
|
||||
assert_eq!(node(&s, out[0]).appearance.stroke_paint(), before, "the rest keeps its stroke");
|
||||
}
|
||||
|
||||
/// Gives `id` a red-to-blue linear gradient, fitted to its bounds, as its fill and its stroke, and
|
||||
/// returns that fill and stroke fixed where they fit `id` now.
|
||||
fn paint_with_gradients(s: &mut Session, id: NodeId) -> (Paint, Paint) {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
s.edit("t", |d, _| {
|
||||
let a = &mut d.node_mut(id).unwrap().appearance;
|
||||
a.set_fill(gradient.clone());
|
||||
a.set_stroke(gradient);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut n = node(s, id);
|
||||
n.pin_gradients();
|
||||
(n.appearance.fill_paint(), n.appearance.stroke_paint())
|
||||
}
|
||||
|
||||
/// The two paths a split leaves keep the gradients of the path they come from where they were on
|
||||
/// it: a gradient fitted to the rectangle's bounds is not fitted again to the side split off or to
|
||||
/// what is left.
|
||||
#[test]
|
||||
fn shape_builder_stroke_split_keeps_the_gradients_where_they_were() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let want = paint_with_gradients(&mut s, a);
|
||||
// The rectangle's left side.
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[-1, 50]], "splitStroke": true})).unwrap();
|
||||
let out = ids(&r);
|
||||
assert_eq!(node(&s, out[1]).geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 0.0, 100.0));
|
||||
for i in out {
|
||||
let n = node(&s, i);
|
||||
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), want, "{i:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A red even-odd compound path, square A (0..100) with the square H (25..75) inside it, selected.
|
||||
fn even_odd_ring(s: &mut Session) -> NodeId {
|
||||
let a = rect(s, 0.0, 0.0, 100.0, 100.0);
|
||||
@@ -989,6 +1093,43 @@ fn shape_builder_stroke_split_and_erase_keep_the_name_and_opacity_mask() {
|
||||
assert!(kept(&s, &out[..1]), "A opened where B crosses it");
|
||||
}
|
||||
|
||||
/// What is left of a path after an Alt-click or a merge, and the pieces of an open path that an
|
||||
/// Alt-click leaves, keep the path's gradients where they were on it: A without its region outside
|
||||
/// B, B without the regions merged into A, and the line without its piece inside the square.
|
||||
#[test]
|
||||
fn shape_builder_erase_and_merge_keep_the_gradients_where_they_were() {
|
||||
let mut s = session();
|
||||
let (a, b) = two(&mut s);
|
||||
let want = paint_with_gradients(&mut s, a);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50]], "erase": true})).unwrap();
|
||||
let out = ids(&r);
|
||||
assert_eq!(node(&s, out[0]).geometric_bounds().unwrap(), Rect::new(50.0, 0.0, 100.0, 100.0), "A inside B");
|
||||
assert_eq!((node(&s, out[0]).appearance.fill_paint(), node(&s, out[0]).appearance.stroke_paint()), want);
|
||||
|
||||
let mut s = session();
|
||||
let (a, b) = two(&mut s);
|
||||
let want = paint_with_gradients(&mut s, b);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [75, 50]]})).unwrap();
|
||||
let merged = NodeId(r["merged"].as_u64().unwrap());
|
||||
let rest = ids(&r).into_iter().find(|i| *i != merged).unwrap();
|
||||
assert_eq!(node(&s, rest).geometric_bounds().unwrap(), Rect::new(100.0, 0.0, 150.0, 100.0), "B outside A");
|
||||
assert_eq!((node(&s, rest).appearance.fill_paint(), node(&s, rest).appearance.stroke_paint()), want);
|
||||
|
||||
let mut s = session();
|
||||
let (a, l) = square_and_line(&mut s);
|
||||
let want = paint_with_gradients(&mut s, l);
|
||||
s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[51, 50]], "erase": true})).unwrap();
|
||||
let ends: Vec<NodeId> = ids(&r).into_iter().filter(|i| !outline(&node(&s, *i)).0.is_closed()).collect();
|
||||
assert_eq!(ends.len(), 2, "the line's two loose ends");
|
||||
for i in ends {
|
||||
let n = node(&s, i);
|
||||
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), want, "{i:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool with In Merge Mode, Clicking Stroke Splits the Path: over a stroke, the pointer shows
|
||||
/// scissors and the run a click splits is drawn in the highlight color (none with Highlight Stroke
|
||||
/// When Editable off), and a click splits it. Off, the same click leaves the rectangle as it was.
|
||||
|
||||
@@ -77,6 +77,12 @@ fn leaf_targets_expand_groups_and_stop_at_compound_paths() {
|
||||
s.execute("select.set", &json!({"ids": [c.0, d.0]})).unwrap();
|
||||
let comp = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
assert_eq!(leaf_targets(&s, &[comp]).unwrap(), vec![comp]);
|
||||
// A member stands for its compound path, listed once (#3692).
|
||||
let members: Vec<NodeId> = s.doc().unwrap().doc.node(comp).unwrap().children().into_iter().flatten().map(|m| m.id).collect();
|
||||
assert_eq!(members.len(), 2);
|
||||
assert_eq!(leaf_targets(&s, &[members[0]]).unwrap(), vec![comp]);
|
||||
assert_eq!(leaf_targets(&s, &[members[0], comp, members[1]]).unwrap(), vec![comp]);
|
||||
assert_eq!(leaf_targets(&s, &[members[1], members[0]]).unwrap(), vec![comp]);
|
||||
// `paint_targets` reads `ids`, then `id`, then the selection.
|
||||
assert_eq!(paint_targets(&s, &json!({"ids": [g.0]})).unwrap(), vec![a, b]);
|
||||
assert_eq!(paint_targets(&s, &json!({"id": comp.0})).unwrap(), vec![comp]);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Fill and stroke given to a path of a compound path paint the compound path (#3692): the
|
||||
//! compound holds the paint, so a member's own appearance is never drawn.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40}))["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A compound path of two black rectangles and a loose black rectangle → (compound, members, loose).
|
||||
fn compound() -> (Session, NodeId, Vec<NodeId>, NodeId) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 100}));
|
||||
let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 10.0));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
run(&mut s, "object.compoundPath.make", json!({}));
|
||||
let compound = s.doc().unwrap().selection.objects[0];
|
||||
let loose = rect(&mut s, 100.0);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#000000", "ids": [compound.0, loose.0]}));
|
||||
run(&mut s, "paint.setStroke", json!({"color": "#000000", "ids": [compound.0, loose.0]}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let members: Vec<NodeId> = doc.node(compound).unwrap().children().into_iter().flatten().map(|m| m.id).collect();
|
||||
assert_eq!(members.len(), 2);
|
||||
(s, compound, members, loose)
|
||||
}
|
||||
|
||||
/// The hex of `id`'s own top fill (`fill`) or stroke, `None` when it has none or it isn't solid.
|
||||
fn paint(s: &Session, id: NodeId, fill: bool) -> Option<String> {
|
||||
match s.doc().unwrap().doc.node(id).unwrap().appearance.paint_at(None, fill)? {
|
||||
Paint::Solid { color, .. } => Some(color.to_hex()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn solid(hex: &str) -> Option<String> {
|
||||
Some(hex.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_given_to_a_member_id_paints_its_compound() {
|
||||
let (mut s, compound, members, loose) = compound();
|
||||
let member_paint = paint(&s, members[0], true);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff00ff", "ids": [members[0].0, members[1].0, loose.0]}));
|
||||
assert_eq!(paint(&s, compound, true), solid("#ff00ff"), "the compound path takes the fill");
|
||||
assert_eq!(paint(&s, loose, true), solid("#ff00ff"));
|
||||
assert_eq!(paint(&s, members[0], true), member_paint, "the member's own appearance is left alone");
|
||||
assert_eq!(paint(&s, compound, false), solid("#000000"), "the stroke stays");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(paint(&s, compound, true), solid("#000000"), "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_given_to_a_selected_member_paints_its_compound() {
|
||||
let (mut s, compound, members, _) = compound();
|
||||
run(&mut s, "select.set", json!({"ids": [members[1].0]}));
|
||||
run(&mut s, "paint.setStroke", json!({"color": "#00ff00"}));
|
||||
assert_eq!(paint(&s, compound, false), solid("#00ff00"));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
assert_eq!(paint(&s, compound, true), solid("#0000ff"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_members_of_one_compound_are_one_target() {
|
||||
let (mut s, compound, members, _) = compound();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [compound.0]}));
|
||||
// Swapped once per id, the two members would swap the compound path back.
|
||||
run(&mut s, "paint.swap", json!({"ids": [members[0].0, members[1].0]}));
|
||||
assert_eq!(paint(&s, compound, true), solid("#000000"), "swapped once, not once per member");
|
||||
assert_eq!(paint(&s, compound, false), solid("#ff0000"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_with_a_compound_still_paints_the_compound_once() {
|
||||
let (mut s, compound, _, loose) = compound();
|
||||
run(&mut s, "select.set", json!({"ids": [compound.0, loose.0]}));
|
||||
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [group.0]}));
|
||||
run(&mut s, "paint.swap", json!({"ids": [group.0]}));
|
||||
assert_eq!(paint(&s, compound, true), solid("#000000"));
|
||||
assert_eq!(paint(&s, compound, false), solid("#ff0000"));
|
||||
assert_eq!(paint(&s, loose, false), solid("#ff0000"));
|
||||
}
|
||||
@@ -1071,3 +1071,25 @@ fn offset_path_that_leaves_nothing_says_so() {
|
||||
let e = s.execute("object.path.offsetPath", &json!({"offset": -20})).unwrap_err().to_string();
|
||||
assert!(e.contains("leaves nothing") && !e.contains("select paths"), "{e}");
|
||||
}
|
||||
|
||||
/// COLR glyphs become groups of their layers: real paths with their colours and gradients, the
|
||||
/// composite's blend mode kept, every node with an id of the document's.
|
||||
#[test]
|
||||
fn create_outlines_turns_colr_glyphs_into_layer_groups() {
|
||||
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font};
|
||||
vectorcraft_text::FontDb::global().add_font(colr_font(true).unwrap());
|
||||
let mut s = session();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": format!("{COLOUR_CHAR}F"), "size": 32, "font": colr_family(true)})).unwrap();
|
||||
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
|
||||
let g = node(&s, r[0]);
|
||||
let ch = g.children().unwrap();
|
||||
assert!(matches!(ch[0].kind, NodeKind::Group { .. }), "the glyph's group: {:?}", ch[0].kind_label());
|
||||
assert!(matches!(ch[1].kind, NodeKind::Path { .. } | NodeKind::Compound { .. }), "the `F` an outline");
|
||||
let mut nodes = vec![];
|
||||
ch[0].walk(&mut |n| nodes.push((n.id, n.blend, n.appearance.fill_paint())));
|
||||
assert!(nodes.iter().any(|(_, _, p)| matches!(p, vectorcraft_color::Paint::Gradient(_))), "its gradients");
|
||||
assert!(nodes.iter().any(|(_, b, _)| *b == vectorcraft_color::BlendMode::Multiply), "its multiply");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
assert!(nodes.iter().all(|(id, ..)| d.node(*id).is_some() && seen.insert(*id)), "ids of the document's, each once");
|
||||
}
|
||||
@@ -330,6 +330,53 @@ fn rough_frame_test_filter() {
|
||||
std::fs::write(std::path::Path::new(&dir).join("rough-frame-test-filter.wasm"), wat::parse_str(src).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
/// A filter keeps data with the document: it writes it with `documentData` in the same undo step as
|
||||
/// its objects (`null` removes it) and reads what it last wrote in `_context.documentData`, which
|
||||
/// no other filter is given. It is the document's foreign data, so the native file keeps it with
|
||||
/// no section of its own. More than the limit is refused.
|
||||
#[test]
|
||||
fn filters_keep_their_data_with_the_document() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0, "#ff0000");
|
||||
let pid = "test.engine.data";
|
||||
let returning = |out: Value| tpl::returning(&tpl::manifest(pid, "filter", "{}"), &out.to_string());
|
||||
let keep = |data: Value| json!({"objects": [{"id": id.0}], "documentData": data});
|
||||
let data = |s: &Session| s.doc().unwrap().doc.plugin_data(pid).cloned();
|
||||
let filter = |s: &mut Session, pid: &str| s.execute("plugin.run", &json!({"id": pid, "ids": [id.0]}));
|
||||
install_wat(&mut s, &returning(keep(json!({"pen": 2}))));
|
||||
filter(&mut s, pid).unwrap();
|
||||
assert_eq!(data(&s), Some(json!({"pen": 2})));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(data(&s), None, "one undo step with the objects");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
// Read back: these name the object only when they are given what they look for.
|
||||
let named = |name: &str| json!({"objects": [{"id": id.0, "name": name}]}).to_string();
|
||||
let when_given =
|
||||
|pid: &str, needle: &str, name: &str| tpl::when_given(&tpl::manifest(pid, "filter", "{}"), tpl::Given::Params, needle, &named(name));
|
||||
install_wat(&mut s, &when_given(pid, r#""documentData":{"pen":2}"#, "Pen 2"));
|
||||
filter(&mut s, pid).unwrap();
|
||||
assert_eq!(node(&s, id).name.as_deref(), Some("Pen 2"));
|
||||
// Another filter is given nothing: what a filter keeps is its own.
|
||||
let other = "test.engine.other";
|
||||
install_wat(&mut s, &when_given(other, r#""documentData":null"#, "Nothing kept"));
|
||||
filter(&mut s, other).unwrap();
|
||||
assert_eq!(node(&s, id).name.as_deref(), Some("Nothing kept"));
|
||||
// Saved with the document, among its foreign data.
|
||||
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(saved.plugin_data(pid), Some(&json!({"pen": 2})));
|
||||
assert_eq!(saved.unknown.get(vectorcraft_doc::plugin_data::PLUGIN_DATA), Some(&json!({pid: {"pen": 2}})));
|
||||
// Too much is refused, and the document stays as it was; null removes the data.
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let big = "x".repeat(vectorcraft_plugins::objects::MAX_DOCUMENT_DATA);
|
||||
install_wat(&mut s, &returning(keep(json!(big))));
|
||||
let e = filter(&mut s, pid).unwrap_err().to_string();
|
||||
assert!(e.contains("documentData"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
install_wat(&mut s, &returning(keep(Value::Null)));
|
||||
filter(&mut s, pid).unwrap();
|
||||
assert_eq!(data(&s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_management_commands() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Preferences: `prefs.get` / `prefs.set` / `prefs.reset` / `prefs.list`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use super::*;
|
||||
use crate::cmd::prefscmds::{PREF_CATEGORIES, PREF_GROUPS, PREF_SPECS, validate};
|
||||
@@ -1393,6 +1395,114 @@ fn highlight_alternate_glyphs_preference_is_off_by_default() {
|
||||
assert!(!s.prefs.highlight_alternate_glyphs);
|
||||
}
|
||||
|
||||
/// Preferences › Performance › Real-time Drawing and Editing (#394): off, the document isn't
|
||||
/// previewed while dragging but the pending shape still shows as a canvas overlay until commit.
|
||||
#[test]
|
||||
fn real_time_drawing_off_skips_tool_previews_until_commit() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
let paths = |s: &Session| {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.doc
|
||||
.layers
|
||||
.first()
|
||||
.and_then(|l| l.children())
|
||||
.map_or(0, |c| c.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).count())
|
||||
};
|
||||
let rev = s.doc().unwrap().revision;
|
||||
assert_eq!(paths(&s), 0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 150.0), v).unwrap();
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "no preview steps");
|
||||
assert_eq!(paths(&s), 0, "the rectangle isn't in the document yet");
|
||||
assert!(s.overlays(v).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. })), "the deferred rectangle shows as an outline");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap();
|
||||
assert!(s.doc().unwrap().revision > rev, "commit applies the shape");
|
||||
assert_eq!(paths(&s), 1);
|
||||
set_pref(&mut s, "realTimeDrawing", json!(true));
|
||||
let rev = s.doc().unwrap().revision;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 120.0), v).unwrap();
|
||||
assert!(s.doc().unwrap().revision > rev, "on again: previews run while dragging");
|
||||
}
|
||||
|
||||
/// Real-time Drawing turned on mid-drag still applies the deferred preview on commit.
|
||||
#[test]
|
||||
fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
let paths = |s: &Session| {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.doc
|
||||
.layers
|
||||
.first()
|
||||
.and_then(|l| l.children())
|
||||
.map_or(0, |c| c.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).count())
|
||||
};
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 150.0), v).unwrap();
|
||||
assert_eq!(paths(&s), 0);
|
||||
set_pref(&mut s, "realTimeDrawing", json!(true));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap();
|
||||
assert_eq!(paths(&s), 1, "the deferred rectangle is committed");
|
||||
}
|
||||
|
||||
/// Repeated overlay redraws with Real-time Drawing off reuse the cached deferred feedback.
|
||||
#[test]
|
||||
fn deferred_preview_overlays_are_cached_across_redraws() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 150.0), v).unwrap();
|
||||
let rev = s.doc().unwrap().revision;
|
||||
let count = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. })).count();
|
||||
let first = count(&mut s);
|
||||
assert!(first > 0);
|
||||
assert_eq!(s.doc().unwrap().revision, rev);
|
||||
let second = count(&mut s);
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "the preview command is not run again");
|
||||
}
|
||||
|
||||
/// A deferred commit that fails its preview cancels the interaction instead of leaving it open.
|
||||
#[test]
|
||||
fn deferred_commit_preview_failure_cancels_interaction() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.begin_interaction("Bad").unwrap();
|
||||
s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("no.such.command".into(), json!({})));
|
||||
s.apply_actions(vec![vectorcraft_tools::Action::Commit]).unwrap();
|
||||
assert!(s.doc().unwrap().interaction.is_none());
|
||||
}
|
||||
|
||||
/// A deferred commit applies preview warnings to the UI, as live previews do.
|
||||
#[test]
|
||||
fn deferred_commit_forwards_preview_warnings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap();
|
||||
let text = s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Hi"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect["id"], text["id"]]})).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.begin_interaction("Bloat").unwrap();
|
||||
let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0});
|
||||
s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p));
|
||||
let ui = s.apply_actions(vec![vectorcraft_tools::Action::Commit]).unwrap();
|
||||
assert!(ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))), "{ui:?}");
|
||||
}
|
||||
|
||||
/// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does
|
||||
/// not replace full-resolution pixels already in the document.
|
||||
#[test]
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Hosting the active tool: pointer/key events → actions → commands.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::Selection;
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::distort::perspective::widget::WidgetPlace;
|
||||
use vectorcraft_tools::draw2::FEEDBACK;
|
||||
use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
|
||||
|
||||
use crate::{EngineError, Prefs, Result, Session};
|
||||
@@ -236,6 +238,8 @@ impl Session {
|
||||
// wins instead of pixels quietly rounding every drag to whole points (#1816).
|
||||
snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid,
|
||||
snap_to_point: view.snap_to_point,
|
||||
snap_tangent: self.prefs.snap_tangent,
|
||||
snap_perpendicular: self.prefs.snap_perpendicular,
|
||||
snap_to_glyph: view.snap_to_glyph && view.smart_guides && !view.snap_to_grid,
|
||||
corner_widgets: view.corner_widgets,
|
||||
fill_active: self.fill_active,
|
||||
@@ -450,11 +454,15 @@ impl Session {
|
||||
v.extend(self.with_tool_cx(view, |_, cx| g.overlays(cx)));
|
||||
self.ruler_guide = Some(g);
|
||||
}
|
||||
let deferred_preview = self.unapplied_interaction_preview();
|
||||
if let Some(d) = self.active() {
|
||||
let w = self.prefs.perspective_widget;
|
||||
let place = w.show.then_some(WidgetPlace { screen: view.screen.as_ref(), corner: w.position });
|
||||
v.splice(0..0, vectorcraft_tools::distort::perspective::grid_overlays_in(&d.doc, 1.0 / view.zoom.max(1e-9), place));
|
||||
}
|
||||
if let Some((cmd, p)) = deferred_preview {
|
||||
v.extend(self.deferred_preview_overlays_from_command(&cmd, &p));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -562,19 +570,49 @@ impl Session {
|
||||
for a in acts {
|
||||
match a {
|
||||
Action::Begin(label) => self.begin_interaction(&label)?,
|
||||
Action::Preview(cmd, p) => match self.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
Action::Preview(cmd, p) => {
|
||||
// Performance › Real-time Drawing and Editing (#394): off, remember the latest
|
||||
// params and apply them once on Commit instead of every move.
|
||||
if !self.prefs.real_time_drawing {
|
||||
self.clear_deferred_overlay_cache();
|
||||
let st = self.doc_mut()?;
|
||||
if let Some(it) = &mut st.interaction {
|
||||
it.preview = Some((cmd, p));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(e) => log::warn!("preview {cmd}: {e}"),
|
||||
},
|
||||
self.clear_deferred_overlay_cache();
|
||||
match self.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("preview {cmd}: {e}"),
|
||||
}
|
||||
}
|
||||
// The drag is over: the dabs of a Liquify stroke have no further use.
|
||||
Action::Commit => {
|
||||
self.liquify_stroke = None;
|
||||
let deferred = self.unapplied_interaction_preview();
|
||||
if let Some((cmd, p)) = deferred {
|
||||
match self.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("preview {cmd}: {e}");
|
||||
self.cancel_interaction()?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.commit_interaction()?
|
||||
}
|
||||
Action::Cancel => {
|
||||
@@ -598,4 +636,50 @@ impl Session {
|
||||
}
|
||||
Ok(ui)
|
||||
}
|
||||
|
||||
/// Canvas feedback while Real-time Drawing is off: run the pending preview command once, take
|
||||
/// outlines from the objects it touched, then put the document back at the interaction snapshot.
|
||||
fn deferred_preview_overlays_from_command(&mut self, cmd: &str, p: &Value) -> Vec<Overlay> {
|
||||
if self.deferred_overlay_cache.as_ref().is_some_and(|(c, params, _)| c == cmd && params == p) {
|
||||
return self.deferred_overlay_cache.as_ref().map(|(_, _, o)| o.clone()).unwrap_or_default();
|
||||
}
|
||||
let (snapshot, selection, revision, paint, interaction_fields) = {
|
||||
let Some(st) = self.active() else { return vec![] };
|
||||
let Some(it) = st.interaction.as_ref() else { return vec![] };
|
||||
if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) {
|
||||
return vec![];
|
||||
}
|
||||
let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone());
|
||||
(st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields)
|
||||
};
|
||||
let overlays = if self.preview(cmd, p).is_ok() {
|
||||
self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
if let Ok(st) = self.doc_mut() {
|
||||
st.doc = snapshot;
|
||||
st.selection = selection;
|
||||
st.revision = revision;
|
||||
if let Some(it) = &mut st.interaction {
|
||||
it.preview = interaction_fields.0;
|
||||
it.copies = interaction_fields.1;
|
||||
it.perspective_again = interaction_fields.2;
|
||||
}
|
||||
}
|
||||
self.pending_paint = paint;
|
||||
self.deferred_overlay_cache = Some((cmd.to_string(), p.clone(), overlays.clone()));
|
||||
overlays
|
||||
}
|
||||
}
|
||||
|
||||
fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec<Overlay> {
|
||||
selection
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|&id| {
|
||||
let n = doc.node(id)?;
|
||||
vectorcraft_render::drawn_outline(doc, n).map(|(path, _)| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -452,3 +452,72 @@ fn both_points_snap_onto_anchors_with_a_visible_indicator() {
|
||||
run(&mut s, "object.scale", json!({"sx":200,"sy":100}));
|
||||
assert_eq!(text(&s, id), "144.00 pt", "linked to both anchors");
|
||||
}
|
||||
|
||||
/// The page content streams of exported PDF `v`, inflated.
|
||||
fn pdf_content(v: &Value) -> String {
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let mut out = String::new();
|
||||
let mut rest = &bytes[..];
|
||||
while let Some(at) = rest.windows(7).position(|w| w == b"stream\n" || w == b"stream\r") {
|
||||
let body = &rest[at + 7..];
|
||||
let body = body.strip_prefix(b"\n").unwrap_or(body);
|
||||
let end = body.windows(9).position(|w| w == b"endstream").unwrap_or(body.len());
|
||||
let mut raw = Vec::new();
|
||||
if std::io::Read::read_to_end(&mut flate2::read::ZlibDecoder::new(&body[..end]), &mut raw).is_ok() {
|
||||
out.push_str(&String::from_utf8_lossy(&raw));
|
||||
}
|
||||
rest = &body[(end + 9).min(body.len())..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// #3233: in a CMYK document a dimension's black lines and label print on the black plate only
|
||||
/// (`0 0 0 1 K`), not as a four-ink rich black; other colours convert to CMYK; RGB documents keep
|
||||
/// RGB.
|
||||
#[test]
|
||||
fn dimension_colours_follow_the_document_colour_model() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width":600,"height":500,"colorMode":"cmyk"}));
|
||||
let line = edge(&mut s);
|
||||
run(&mut s, "object.hide", json!({"ids":[line]}));
|
||||
let id = dim(&mut s, line);
|
||||
let colours = |s: &Session, id: u64| {
|
||||
let mut v = Vec::new();
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().walk(&mut |n| {
|
||||
v.extend([n.appearance.fill_paint(), n.appearance.stroke_paint()].iter().filter_map(|p| p.color()));
|
||||
});
|
||||
v
|
||||
};
|
||||
let black = colours(&s, id);
|
||||
assert!(!black.is_empty() && black.iter().all(|c| *c == vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)), "{black:?}");
|
||||
let pdf = pdf_content(&run(&mut s, "document.exportPdf", json!({"preset":"PDF/X-4:2010"})));
|
||||
// PDF/X-4 paints in the output intent's CMYK space: `/c0 CS 0 0 0 1 SCN` strokes, `scn` fills.
|
||||
let operands = |op: &str| pdf.match_indices(op).map(|(i, _)| pdf[i.saturating_sub(7)..i].to_string()).collect::<Vec<_>>();
|
||||
let (strokes, fills) = (operands(" SCN"), operands(" scn"));
|
||||
assert!(!strokes.is_empty() && !fills.is_empty(), "{pdf}");
|
||||
assert!(strokes.iter().chain(&fills).all(|v| v == "0 0 0 1"), "K-only colours: {strokes:?} {fills:?}");
|
||||
run(&mut s, "dimension.update", json!({"ids":[id],"options":{"lineColor":[255,0,0]}}));
|
||||
let red = colours(&s, id);
|
||||
assert!(red.iter().any(|c| matches!(c, vectorcraft_color::Color::Cmyk { m, y, .. } if *m > 0.5 && *y > 0.5)), "{red:?}");
|
||||
assert!(red.iter().all(|c| matches!(c, vectorcraft_color::Color::Cmyk { .. })), "{red:?}");
|
||||
// RGB documents are unchanged.
|
||||
let mut s = session();
|
||||
let line = edge(&mut s);
|
||||
let id = dim(&mut s, line);
|
||||
assert!(colours(&s, id).iter().all(|c| *c == vectorcraft_color::Color::rgb8(0, 0, 0)));
|
||||
// Document Color Mode redraws dimensions in the new mode: K-only black in CMYK, RGB black back
|
||||
// in RGB (not a profile conversion of the old art).
|
||||
let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"}));
|
||||
let after = colours(&s, id);
|
||||
assert!(!after.is_empty() && after.iter().all(|c| *c == k), "{after:?}");
|
||||
run(&mut s, "file.documentColorMode", json!({"mode":"rgb"}));
|
||||
assert!(colours(&s, id).iter().all(|c| *c == vectorcraft_color::Color::rgb8(0, 0, 0)), "{:?}", colours(&s, id));
|
||||
// A CMYK file saved with RGB dimension art (before dimensions followed the colour mode) opens
|
||||
// with its dimensions redrawn in CMYK.
|
||||
let mut old = (*s.doc().unwrap().doc).clone();
|
||||
old.color_mode = vectorcraft_doc::ColorMode::Cmyk;
|
||||
s.add_document(old, None);
|
||||
let opened = colours(&s, id);
|
||||
assert!(!opened.is_empty() && opened.iter().all(|c| *c == k), "{opened:?}");
|
||||
}
|
||||
@@ -104,6 +104,23 @@ fn the_exporter_is_given_the_native_file_s_json() {
|
||||
assert!(image.get("blob").is_some() && image.get("data").is_none(), "{image}");
|
||||
}
|
||||
|
||||
/// What filter plug-ins keep with the document reaches an exporter with the rest of the document:
|
||||
/// a plotter's exporter finds the pens a setup filter kept (`document.unknown.pluginData`, by
|
||||
/// plug-in id).
|
||||
#[test]
|
||||
fn an_exporter_finds_what_filters_keep_with_the_document() {
|
||||
let mut s = session();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let pens = json!({"pens": [{"slot": 1, "width": 0.3}, {"slot": 2, "width": 0.5}]});
|
||||
let setup = json!({"objects": [], "documentData": pens});
|
||||
install(&mut s, &tpl::returning(&tpl::manifest("test.setup", "filter", "{}"), &setup.to_string()));
|
||||
s.execute("plugin.run", &json!({"id": "test.setup"})).unwrap();
|
||||
install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.pens", r#"["tsd"]"#, "{}"), Echo::Input));
|
||||
let r = s.execute("document.export", &json!({"format": "plugin.test.pens"})).unwrap();
|
||||
let doc: Value = serde_json::from_slice(&exported(&r)).unwrap();
|
||||
assert_eq!(doc["document"]["unknown"][vectorcraft_doc::plugin_data::PLUGIN_DATA], json!({"test.setup": pens}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exporter_is_given_its_parameters_and_the_file_it_writes() {
|
||||
let dir = tmp_dir("params");
|
||||
|
||||
@@ -1293,6 +1293,10 @@ impl<'a> Writer<'a> {
|
||||
if let Some((image, to_text)) = g.placed_image() {
|
||||
self.image(Some(&image.blob), image.width, image.height, t.xf * to_text);
|
||||
}
|
||||
// COLR glyphs: their layers, as art.
|
||||
if let Some(art) = g.placed_colour(t.xf) {
|
||||
self.node(&art, false);
|
||||
}
|
||||
}
|
||||
self.line("U");
|
||||
}
|
||||
|
||||
@@ -591,6 +591,10 @@ impl<'a> Scene<'a> {
|
||||
let key = format!("\u{0}glyph\u{0}{}", image.blob.content_key());
|
||||
self.image(&key, Some(&image.blob), image.width, image.height, to_text);
|
||||
}
|
||||
// COLR glyphs: their layers, as art (in text space, as the images).
|
||||
if let Some(art) = g.placed_colour(Affine::IDENTITY) {
|
||||
self.node(&art, true);
|
||||
}
|
||||
}
|
||||
if bp.elements().is_empty() {
|
||||
continue;
|
||||
|
||||
@@ -518,3 +518,20 @@ fn colour_bitmap_glyphs_are_images() {
|
||||
// origin (2 px), in text space.
|
||||
assert!(ps.contains("[32 0 0 32 4 -24] cm"), "{ps}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colr_glyphs_are_vector_art() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font};
|
||||
vectorcraft_text::FontDb::global().add_font(colr_font(false).unwrap());
|
||||
let d = doc_with(|d| {
|
||||
let fill = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0));
|
||||
let st = CharStyle { font_family: colr_family(false).into(), size: 32.0, fill, ..CharStyle::default() };
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 100.0), &COLOUR_CHAR.to_string(), st))))]
|
||||
});
|
||||
let ps = text(&export(&d, &opts(&d), None, None).unwrap());
|
||||
checked_page(&ps);
|
||||
assert!(!ps.contains("/Width"), "no image: {ps}");
|
||||
assert!(ps.contains("1 0 0 rg"), "the red layer: {ps}");
|
||||
assert!(ps.contains("0 0 1 rg"), "the foreground layer in the fill: {ps}");
|
||||
}
|
||||
@@ -93,7 +93,8 @@ fn write_with(doc: &Document, o: LegacyAiOptions) -> LegacyAiOutput {
|
||||
/// in their first stop's color.
|
||||
fn as_printed(doc: &Document, o: &LegacyAiOptions) -> Document {
|
||||
// A run's glyphs, laid out, as one path with the run's fill (the renderer draws no type), and
|
||||
// its colour bitmap glyphs as images (their pixels added to `images`).
|
||||
// its colour bitmap glyphs as images (their pixels added to `images`), its COLR glyphs as their
|
||||
// layers.
|
||||
fn outlined(t: &vectorcraft_doc::TextObject, images: &mut std::collections::BTreeMap<String, ImageBlob>) -> Node {
|
||||
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let mut nodes: Vec<Arc<Node>> = t
|
||||
@@ -116,6 +117,8 @@ fn as_printed(doc: &Document, o: &LegacyAiOptions) -> Document {
|
||||
let im = ImageObject { key, width: image.width, height: image.height, xf: t.xf * to_text, link: None, placement: Default::default() };
|
||||
nodes.push(Arc::new(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im)))));
|
||||
}
|
||||
// COLR glyphs: their layers.
|
||||
nodes.extend(layout.glyphs.iter().filter_map(|g| g.placed_colour(t.xf)).map(Arc::new));
|
||||
Node::group(vectorcraft_doc::NodeId(0), nodes)
|
||||
}
|
||||
fn plain(nodes: &mut Vec<Arc<Node>>, o: &LegacyAiOptions, images: &mut std::collections::BTreeMap<String, ImageBlob>) {
|
||||
@@ -1175,3 +1178,20 @@ fn colour_bitmap_glyphs_of_outlined_type_are_images() {
|
||||
assert_eq!(images.len(), 1, "{text}");
|
||||
assert!(images[0][2].ends_with(" ] 0 0 16 16 16 16 8 3 0 0 0 0 XI"), "{:?}", images[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colr_glyphs_of_outlined_type_are_vector_art() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font};
|
||||
vectorcraft_text::FontDb::global().add_font(colr_font(false).unwrap());
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let st = CharStyle { font_family: colr_family(false).into(), size: 32.0, ..CharStyle::default() };
|
||||
// Cyrillic, which 8-bit text can't hold: the type is written as outlines.
|
||||
let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), &format!("{COLOUR_CHAR}\u{416}"), st);
|
||||
let l = doc.layers[0].id;
|
||||
let id = doc.alloc_id();
|
||||
doc.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
|
||||
let text = String::from_utf8(write(&doc).bytes).unwrap();
|
||||
assert!(rasters(&text).is_empty(), "no images: {text}");
|
||||
assert!(text.contains("1 0 0 Xa"), "the red layer: {text}");
|
||||
}
|
||||
@@ -937,9 +937,11 @@ mod tests {
|
||||
#[test]
|
||||
fn divide_open_paths_retains_the_existing_segment_cap() {
|
||||
let mut inputs = vec![Shape::new(rect(0.0, 0.0, 100.0, 100.0), FillRule::NonZero, 7)];
|
||||
inputs.extend((0..4093).map(|_| Shape::new(shapes::line(Point::new(-10.0, 50.0), Point::new(110.0, 50.0)), FillRule::NonZero, 99)));
|
||||
// The square's four sides and one line past the cap.
|
||||
let n = crate::SHAPE_BUILDER_MAX_SEGMENTS - 3;
|
||||
inputs.extend((0..n).map(|_| Shape::new(shapes::line(Point::new(-10.0, 50.0), Point::new(110.0, 50.0)), FillRule::NonZero, 99)));
|
||||
let faces = pathfinder(PathfinderOp::Divide, &inputs);
|
||||
assert_eq!(faces.len(), 1, "4097 segments fall back to filled areas");
|
||||
assert_eq!(faces.len(), 1, "a segment past the cap falls back to filled areas");
|
||||
assert_eq!(faces[0].key, 7);
|
||||
assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
+189
-45
@@ -94,9 +94,65 @@ fn mid(segs: &[Seg]) -> Option<Point> {
|
||||
segs.get(segs.len() / 2).map(|s| s.c.eval(0.5))
|
||||
}
|
||||
|
||||
/// Rectangles looked up by a point inside them, when there are too many to test one by one for
|
||||
/// every point (the map asks once per edge and once per hole, so a scan of them all made it
|
||||
/// quadratic in the input, #937). Rectangles narrow in x are sorted by their left edge, so the
|
||||
/// ones that can hold a point are one short run of them; those wide in x but narrow in y (a hatch
|
||||
/// of long horizontal lines) are sorted by their top edge the same way; the few wide both ways (a
|
||||
/// long diagonal across the art) are scanned. "Narrow" is up to twice the side of a cell holding
|
||||
/// one rectangle on average, so a run holds about the rectangles of one row or column of cells.
|
||||
struct RectIndex<T> {
|
||||
by_x: Vec<(kurbo::Rect, T)>,
|
||||
max_width: f64,
|
||||
by_y: Vec<(kurbo::Rect, T)>,
|
||||
max_height: f64,
|
||||
wide: Vec<(kurbo::Rect, T)>,
|
||||
}
|
||||
|
||||
impl<T> RectIndex<T> {
|
||||
fn new(items: Vec<(kurbo::Rect, T)>) -> Self {
|
||||
let n = items.len().max(1) as f64;
|
||||
let all = items.iter().map(|(r, _)| *r).reduce(|a, b| a.union(b));
|
||||
let cell = all
|
||||
.map(|a| {
|
||||
let side = (a.area() / n).sqrt();
|
||||
if side > 0.0 { 2.0 * side } else { 2.0 * a.width().max(a.height()) / n }
|
||||
})
|
||||
.filter(|c| c.is_finite())
|
||||
.unwrap_or(0.0)
|
||||
.max(1e-9);
|
||||
let (mut by_x, mut by_y, mut wide) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for it in items {
|
||||
if it.0.width() <= cell {
|
||||
by_x.push(it);
|
||||
} else if it.0.height() <= cell {
|
||||
by_y.push(it);
|
||||
} else {
|
||||
// A NaN extent fails both tests above, so a non-finite rectangle is never in a sorted
|
||||
// run along that axis; `contains` rejects it wherever it lands.
|
||||
wide.push(it);
|
||||
}
|
||||
}
|
||||
by_x.sort_by(|a, b| a.0.x0.total_cmp(&b.0.x0));
|
||||
by_y.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0));
|
||||
let max_width = by_x.iter().map(|(r, _)| r.width()).fold(0.0, f64::max);
|
||||
let max_height = by_y.iter().map(|(r, _)| r.height()).fold(0.0, f64::max);
|
||||
Self { by_x, max_width, by_y, max_height, wide }
|
||||
}
|
||||
|
||||
/// The items whose rectangle, grown by `tol`, holds `p`.
|
||||
fn at(&self, p: Point, tol: f64) -> impl Iterator<Item = &T> {
|
||||
let lo = self.by_x.partition_point(|(r, _)| r.x0 < p.x - tol - self.max_width);
|
||||
let run_x = self.by_x.get(lo..).unwrap_or_default().iter().take_while(move |(r, _)| r.x0 <= p.x + tol);
|
||||
let lo = self.by_y.partition_point(|(r, _)| r.y0 < p.y - tol - self.max_height);
|
||||
let run_y = self.by_y.get(lo..).unwrap_or_default().iter().take_while(move |(r, _)| r.y0 <= p.y + tol);
|
||||
run_x.chain(run_y).chain(&self.wide).filter(move |(r, _)| r.inflate(tol, tol).contains(p)).map(|(_, t)| t)
|
||||
}
|
||||
}
|
||||
|
||||
/// The inputs' segments (in the sweep's frame), to tell which inputs an edge lies on.
|
||||
struct Outlines {
|
||||
segs: Vec<(kurbo::Rect, PathSeg, usize)>,
|
||||
segs: RectIndex<(PathSeg, usize)>,
|
||||
tol: f64,
|
||||
}
|
||||
|
||||
@@ -105,18 +161,18 @@ impl Outlines {
|
||||
// A zero-length segment (a point) is the source of no edge, even one running through it.
|
||||
let segs = inputs
|
||||
.iter()
|
||||
.flat_map(|(bp, i)| bp.segments().map(move |s| (s.bounding_box(), s, *i)))
|
||||
.flat_map(|(bp, i)| bp.segments().map(move |s| (s.bounding_box(), (s, *i))))
|
||||
.filter(|(r, ..)| r.width() > 0.0 || r.height() > 0.0)
|
||||
.collect();
|
||||
// The sweep moves points by a few `eps` at most.
|
||||
Self { segs, tol: 16.0 * eps }
|
||||
Self { segs: RectIndex::new(segs), tol: 16.0 * eps }
|
||||
}
|
||||
|
||||
/// The front-most input whose outline passes through `p`.
|
||||
fn source_at(&self, p: Point) -> Option<usize> {
|
||||
use kurbo::ParamCurveNearest;
|
||||
let tol = self.tol;
|
||||
self.segs.iter().filter(|(r, s, _)| r.inflate(tol, tol).contains(p) && s.nearest(p, 1e-9).distance_sq <= tol * tol).map(|(_, _, i)| *i).max()
|
||||
self.segs.at(p, tol).filter(|(s, _)| s.nearest(p, 1e-9).distance_sq <= tol * tol).map(|(_, i)| *i).max()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,12 +226,24 @@ fn twin(h: usize) -> usize {
|
||||
|
||||
/// The segments of half-edge `h`, in its direction.
|
||||
fn half_segs(edges: &[Edge], h: usize) -> Vec<Seg> {
|
||||
let Some(e) = edges.get(h / 2) else { return Vec::new() };
|
||||
if h.is_multiple_of(2) {
|
||||
e.segs.clone()
|
||||
} else {
|
||||
e.segs.iter().rev().map(|s| Seg { c: CubicBez::new(s.c.p3, s.c.p2, s.c.p1, s.c.p0), line: s.line }).collect()
|
||||
}
|
||||
half_seg_iter(edges, h).collect()
|
||||
}
|
||||
|
||||
/// The segments of half-edge `h` in its direction, without copying the edge first (an edge can
|
||||
/// hold thousands of segments, and the angle it leaves a vertex at needs the first few).
|
||||
fn half_seg_iter(edges: &[Edge], h: usize) -> impl Iterator<Item = Seg> + '_ {
|
||||
let segs = edges.get(h / 2).map(|e| e.segs.as_slice()).unwrap_or_default();
|
||||
let forward = h.is_multiple_of(2);
|
||||
(0..segs.len()).filter_map(move |k| {
|
||||
let s = segs.get(if forward { k } else { segs.len() - 1 - k })?;
|
||||
Some(if forward { *s } else { Seg { c: CubicBez::new(s.c.p3, s.c.p2, s.c.p1, s.c.p0), line: s.line } })
|
||||
})
|
||||
}
|
||||
|
||||
/// Where half-edge `h` ends (the vertex at the other end of its edge).
|
||||
fn far_end(edges: &[Edge], h: usize) -> Option<Point> {
|
||||
let e = edges.get(h / 2)?;
|
||||
if h.is_multiple_of(2) { e.segs.last().map(|s| s.c.p3) } else { e.segs.first().map(|s| s.c.p0) }
|
||||
}
|
||||
|
||||
/// The vertex half-edge `h` leaves from.
|
||||
@@ -188,32 +256,33 @@ fn origin(edges: &[Edge], h: usize) -> Option<usize> {
|
||||
/// Edges that only meet at `v` cross a circle around it in the order they leave `v` in, however
|
||||
/// they start out (tangent curves, or the sweep's short straight stubs at a vertex).
|
||||
fn leaving_angle(edges: &[Edge], h: usize, v: Point, r: f64) -> f64 {
|
||||
let segs = half_segs(edges, h);
|
||||
let mut bp = BezPath::new();
|
||||
for (k, s) in segs.iter().enumerate() {
|
||||
if k == 0 {
|
||||
bp.move_to(s.c.p0);
|
||||
}
|
||||
bp.curve_to(s.c.p1, s.c.p2, s.c.p3);
|
||||
}
|
||||
let mut prev = segs.first().map_or(v, |s| s.c.p0);
|
||||
let first = half_seg_iter(edges, h).next();
|
||||
let mut prev = first.map_or(v, |s| s.c.p0);
|
||||
let mut hit: Option<Point> = None;
|
||||
kurbo::flatten(bp.iter(), (r * 1e-4).max(1e-12), |el| {
|
||||
if let (None, kurbo::PathEl::LineTo(p)) = (hit, el) {
|
||||
if p.distance(v) >= r {
|
||||
// The point on prev → p at distance r (prev is closer).
|
||||
let (d, f) = (p - prev, prev - v);
|
||||
let (a, b, c) = (d.hypot2(), 2.0 * f.dot(d), f.hypot2() - r * r);
|
||||
let t = if a > 0.0 { ((-b + (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a)).clamp(0.0, 1.0) } else { 1.0 };
|
||||
hit = Some(prev + d * t);
|
||||
// One segment at a time, stopping at the first that gets r away: an edge can run on for
|
||||
// thousands of segments (a traced outline between two crossings), all of which flattening
|
||||
// the whole edge to this tolerance would visit, at every vertex.
|
||||
for s in half_seg_iter(edges, h) {
|
||||
let path = [kurbo::PathEl::MoveTo(s.c.p0), kurbo::PathEl::CurveTo(s.c.p1, s.c.p2, s.c.p3)];
|
||||
kurbo::flatten(path, (r * 1e-4).max(1e-12), |el| {
|
||||
if let (None, kurbo::PathEl::LineTo(p)) = (hit, el) {
|
||||
if p.distance(v) >= r {
|
||||
// The point on prev → p at distance r (prev is closer).
|
||||
let (d, f) = (p - prev, prev - v);
|
||||
let (a, b, c) = (d.hypot2(), 2.0 * f.dot(d), f.hypot2() - r * r);
|
||||
let t = if a > 0.0 { ((-b + (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a)).clamp(0.0, 1.0) } else { 1.0 };
|
||||
hit = Some(prev + d * t);
|
||||
}
|
||||
prev = p;
|
||||
}
|
||||
prev = p;
|
||||
});
|
||||
if hit.is_some() {
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
// An edge too short to reach r (it can't, r is at most half of every chord) leaves along its
|
||||
// tangent.
|
||||
let far =
|
||||
hit.unwrap_or_else(|| segs.first().map_or(v, |s| [s.c.p1, s.c.p2, s.c.p3].into_iter().find(|p| p.distance(s.c.p0) > 0.0).unwrap_or(s.c.p3)));
|
||||
let far = hit.unwrap_or_else(|| first.map_or(v, |s| [s.c.p1, s.c.p2, s.c.p3].into_iter().find(|p| p.distance(s.c.p0) > 0.0).unwrap_or(s.c.p3)));
|
||||
(far - v).atan2()
|
||||
}
|
||||
|
||||
@@ -581,9 +650,11 @@ pub fn find_gaps(shapes: &[Shape], max_gap: f64) -> Vec<[Point; 2]> {
|
||||
}
|
||||
|
||||
/// Most segments the Shape Builder sweeps into its planar map (open paths as edges, the gaps closed
|
||||
/// paths enclose, outline edges): the map costs far more than the filled areas' arrangement, so past
|
||||
/// this only the filled areas count.
|
||||
pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 4096;
|
||||
/// paths enclose, outline edges); past this only the filled areas count. The map costs about what
|
||||
/// the filled areas' arrangement does (both near linear in the input; the cap was 4096 while
|
||||
/// finding each edge's source scanned every segment, #937), so this only bounds the time a hover
|
||||
/// can take on art far past what a drawing holds.
|
||||
pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536;
|
||||
|
||||
/// The Shape Builder's arrangement: see [`shape_builder`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -864,8 +935,10 @@ pub(crate) struct Map {
|
||||
edges: Vec<Edge>,
|
||||
around: Vec<Vec<usize>>,
|
||||
slot_of: Vec<usize>,
|
||||
/// Bounded faces: their cycle of half-edges, path and area.
|
||||
/// Bounded faces: their cycle of half-edges, path and area; and, by their bounds, which can
|
||||
/// hold a point, so finding the face around one tests only those.
|
||||
faces: Vec<(Vec<usize>, BezPath, f64)>,
|
||||
face_index: RectIndex<usize>,
|
||||
/// Outer boundaries of connected pieces, and the face each one is a hole in.
|
||||
holes: Vec<(Vec<usize>, BezPath)>,
|
||||
face_holes: Vec<Vec<usize>>,
|
||||
@@ -1020,7 +1093,7 @@ pub(crate) fn map(shapes: &[Shape]) -> Option<Map> {
|
||||
for (v, list) in around.iter_mut().enumerate() {
|
||||
let Some(&at) = points.get(v) else { continue };
|
||||
// Half the shortest chord of the edges here: every one of them gets that far from it.
|
||||
let r = 0.5 * list.iter().filter_map(|&h| half_segs(&edges, h).last().map(|s| s.c.p3.distance(at))).fold(f64::INFINITY, f64::min);
|
||||
let r = 0.5 * list.iter().filter_map(|&h| far_end(&edges, h).map(|p| p.distance(at))).fold(f64::INFINITY, f64::min);
|
||||
let mut keyed: Vec<(f64, usize)> = list.iter().map(|&h| (leaving_angle(&edges, h, at, r), h)).collect();
|
||||
keyed.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
*list = keyed.into_iter().map(|(_, h)| h).collect();
|
||||
@@ -1081,14 +1154,15 @@ pub(crate) fn map(shapes: &[Shape]) -> Option<Map> {
|
||||
}
|
||||
|
||||
// Each hole goes in the smallest face of another piece around it.
|
||||
let face_index = RectIndex::new(faces.iter().enumerate().map(|(i, (_, bp, _))| (bp.bounding_box(), i)).collect());
|
||||
let mut face_holes: Vec<Vec<usize>> = vec![Vec::new(); faces.len()];
|
||||
for (k, (cycle, _)) in holes.iter().enumerate() {
|
||||
let Some(p) = cycle.first().and_then(|&h| origin(&edges, h)).and_then(|v| points.get(v)).copied() else { continue };
|
||||
let own = piece_of(cycle);
|
||||
let around_it = faces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (fc, bp, _))| piece_of(fc) != own && bp.bounding_box().contains(p) && bp.winding(p) != 0)
|
||||
let around_it = face_index
|
||||
.at(p, 0.0)
|
||||
.filter_map(|&i| faces.get(i).map(|f| (i, f)))
|
||||
.filter(|(_, (fc, bp, _))| piece_of(fc) != own && bp.winding(p) != 0)
|
||||
.min_by(|a, b| a.1.2.total_cmp(&b.1.2))
|
||||
.map(|(i, _)| i);
|
||||
if let Some(list) = around_it.and_then(|i| face_holes.get_mut(i)) {
|
||||
@@ -1100,7 +1174,7 @@ pub(crate) fn map(shapes: &[Shape]) -> Option<Map> {
|
||||
let snap = 2.0 * eps;
|
||||
let mut anchors: Vec<Point> = shapes.iter().flat_map(|s| s.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect();
|
||||
anchors.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
|
||||
Some(Map { edges, around, slot_of, faces, holes, face_holes, tidy, anchors, snap })
|
||||
Some(Map { edges, around, slot_of, faces, face_index, holes, face_holes, tidy, anchors, snap })
|
||||
}
|
||||
|
||||
impl Map {
|
||||
@@ -1123,10 +1197,10 @@ impl Map {
|
||||
let q = SHEAR * p;
|
||||
// The smallest face around it: faces of a piece inside a hole lie within the face around.
|
||||
let (i, _) = self
|
||||
.faces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, bp, _))| bp.bounding_box().contains(q) && bp.winding(q) != 0)
|
||||
.face_index
|
||||
.at(q, 0.0)
|
||||
.filter_map(|&i| self.faces.get(i).map(|f| (i, f)))
|
||||
.filter(|(_, (_, bp, _))| bp.winding(q) != 0)
|
||||
.min_by(|a, b| a.1.2.total_cmp(&b.1.2))?;
|
||||
*picked.get_mut(i)? = true;
|
||||
}
|
||||
@@ -1796,6 +1870,76 @@ mod tests {
|
||||
assert!(shape_builder(&s, false).lines.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_traced_outline_of_many_segments_is_cut_by_lines() {
|
||||
// #937: art traced to thousands of segments was past the old cap (4096), so lines stopped
|
||||
// cutting it and the Shape Builder offered the whole shapes. A blob of 20 000 segments
|
||||
// crossed by two long lines (far wider than any of its segments: the index of the
|
||||
// outlines keeps those apart) splits into four regions, each line in four pieces.
|
||||
let n = 20_000;
|
||||
let blob: Vec<Point> = (0..n)
|
||||
.map(|k| {
|
||||
let t = k as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let r = 100.0 + 5.0 * (t * 37.0).sin();
|
||||
Point::new(r * t.cos(), r * t.sin())
|
||||
})
|
||||
.collect();
|
||||
let s = [
|
||||
Shape::new(PathData::single(SubPath::polyline(&blob, true)), FillRule::NonZero, 0),
|
||||
line((-150.0, 0.0), (150.0, 3.0), 1),
|
||||
line((0.0, -150.0), (3.0, 150.0), 2),
|
||||
];
|
||||
let BuilderArrangement { regions, lines, .. } = shape_builder(&s, false);
|
||||
assert_eq!(regions.len(), 4, "{}", regions.len());
|
||||
assert!(regions.iter().all(|r| r.sources == [0]));
|
||||
let whole = crate::area(&s[0].path, FillRule::NonZero);
|
||||
assert!((regions.iter().map(area).sum::<f64>() - whole).abs() < 1e-6 * whole);
|
||||
assert_eq!(lines.iter().filter(|l| l.key == 1).count(), 4, "cut twice by the blob and once by the other line");
|
||||
assert_eq!(lines.iter().filter(|l| l.key == 2).count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hatch_of_parallel_lines_is_cut_line_by_line() {
|
||||
// Hundreds of long horizontal lines over a square, all alike in x (the weak axis of an index
|
||||
// by x alone), and one vertical line: every strip is cut in two.
|
||||
let n: u32 = 300;
|
||||
let mut s = vec![rect(0.0, 0.0, 100.0, 100.0, 0)];
|
||||
for k in 1..n {
|
||||
let y = 100.0 * f64::from(k) / f64::from(n);
|
||||
s.push(line((-10.0, y), (110.0, y), u64::from(k)));
|
||||
}
|
||||
s.push(line((50.0, -10.0), (50.0, 110.0), u64::from(n)));
|
||||
let BuilderArrangement { regions, lines, .. } = shape_builder(&s, false);
|
||||
assert_eq!(regions.len(), 2 * n as usize, "{}", regions.len());
|
||||
assert!(regions.iter().all(|r| r.sources == [0]));
|
||||
assert!((regions.iter().map(area).sum::<f64>() - 10000.0).abs() < 1e-6);
|
||||
// Each horizontal line: a loose end outside, two pieces inside, a loose end outside.
|
||||
assert_eq!(lines.iter().filter(|l| l.key == 1).count(), 4);
|
||||
// The vertical line: cut by the square's sides and every hatch line.
|
||||
assert_eq!(lines.iter().filter(|l| l.key == u64::from(n)).count(), n as usize + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_index_finds_every_rectangle_holding_a_point() {
|
||||
// Narrow in x, narrow in y only, and wide both ways: each lookup matches a scan of them all.
|
||||
let mut items = vec![(kurbo::Rect::new(0.0, 0.0, 100.0, 100.0), 0usize)];
|
||||
for k in 1..50 {
|
||||
let a = f64::from(k as u32) * 2.0;
|
||||
items.push((kurbo::Rect::new(a, 0.0, a + 1.0, 100.0), k));
|
||||
items.push((kurbo::Rect::new(0.0, a, 100.0, a + 1.0), 100 + k));
|
||||
}
|
||||
items.push((kurbo::Rect::new(f64::NAN, 0.0, 1.0, 1.0), 999));
|
||||
let index = RectIndex::new(items.clone());
|
||||
for p in [Point::new(4.5, 6.5), Point::new(50.0, 50.0), Point::new(-1.0, 3.0), Point::new(99.5, 0.5)] {
|
||||
let mut got: Vec<usize> = index.at(p, 0.1).copied().collect();
|
||||
got.sort_unstable();
|
||||
let mut want: Vec<usize> = items.iter().filter(|(r, _)| r.inflate(0.1, 0.1).contains(p)).map(|(_, k)| *k).collect();
|
||||
want.sort_unstable();
|
||||
assert_eq!(got, want, "{p:?}");
|
||||
}
|
||||
assert_eq!(RectIndex::<usize>::new(Vec::new()).at(Point::ZERO, 1.0).count(), 0);
|
||||
}
|
||||
|
||||
fn poly(pts: &[(f64, f64)], closed: bool) -> SubPath {
|
||||
SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), closed)
|
||||
}
|
||||
|
||||
@@ -1605,6 +1605,10 @@ impl Exporter<'_> {
|
||||
s.push_transform(&text_space);
|
||||
for g in images.iter().filter_map(|&gi| layout.glyphs.get(gi)) {
|
||||
self.glyph_image(s, g);
|
||||
// COLR glyphs: their layers, as art.
|
||||
if let Some(art) = g.placed_colour(Affine::IDENTITY) {
|
||||
self.node(s, &art, page, true);
|
||||
}
|
||||
}
|
||||
s.pop();
|
||||
// Characters with neither fill nor stroke (a scanned page's recognized text), or whose
|
||||
@@ -1683,21 +1687,22 @@ impl Exporter<'_> {
|
||||
/// text space; `text` is the plain text, whose characters the glyphs stand for, which makes
|
||||
/// the text selectable and searchable) → the outlines of the glyphs left to draw as paths:
|
||||
/// those of fonts that can't be embedded, and missing glyphs. Glyphs sharing a font, a frame
|
||||
/// (size, scale, rotation) and a baseline are written together. Colour bitmap glyphs (emoji),
|
||||
/// with `images`, are written as text too, which draws their images; the indices of those it
|
||||
/// can't write are returned with the outlines.
|
||||
/// (size, scale, rotation) and a baseline are written together. Colour glyphs (bitmap emoji,
|
||||
/// COLR), with `images`, are written as text too, which draws their images or layers; the
|
||||
/// indices of those it can't write are returned with the outlines.
|
||||
fn glyph_text(&mut self, s: &mut Surface, layout: &TextLayout, run: usize, text: &str, fill: &Paint, images: bool) -> (BezPath, Vec<usize>) {
|
||||
let (mut rest, mut unwritten) = (BezPath::new(), vec![]);
|
||||
let mut line: Option<GlyphLine> = None;
|
||||
for (gi, g) in layout.glyphs.iter().enumerate().filter(|(_, g)| g.run == run) {
|
||||
if g.image.is_some() && !images {
|
||||
let coloured = g.image.is_some() || g.colour.is_some();
|
||||
if coloured && !images {
|
||||
continue;
|
||||
}
|
||||
let range = g.byte..g.byte + g.len;
|
||||
let ch = text.get(range.clone()).and_then(|t| t.chars().next());
|
||||
// Spaces are written too (text extraction needs them); control characters and soft
|
||||
// hyphens draw nothing.
|
||||
let blank = g.outline.elements().is_empty() && g.image.is_none();
|
||||
let blank = g.outline.elements().is_empty() && !coloured;
|
||||
if blank && !ch.is_some_and(|c| c.is_whitespace() && !c.is_control()) {
|
||||
continue;
|
||||
}
|
||||
@@ -1709,7 +1714,7 @@ impl Exporter<'_> {
|
||||
let det = g.xf.determinant();
|
||||
let Some((font, upem)) = font.filter(|(_, upem)| det.is_finite() && det.abs() > 1e-9 && (1e-3..=1e5).contains(&(upem * sy))) else {
|
||||
rest.extend(g.outline.iter());
|
||||
if g.image.is_some() {
|
||||
if coloured {
|
||||
unwritten.push(gi);
|
||||
}
|
||||
continue;
|
||||
|
||||
@@ -1628,7 +1628,7 @@ impl<'p> Builder<'p> {
|
||||
return n.clone();
|
||||
}
|
||||
let data = o.font_data();
|
||||
let name = self.fonts.get(&key).map(|(n, _)| n.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone()));
|
||||
let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone()));
|
||||
let (weight, italic) = data.as_ref().map_or((None, false), |d| (d.weight, d.is_italic));
|
||||
// A subset's six-letter tag.
|
||||
let ps = name.as_deref().map(|n| match n.split_once('+') {
|
||||
@@ -1710,13 +1710,12 @@ impl<'p> Builder<'p> {
|
||||
return false;
|
||||
}
|
||||
let width = o.advance_width().filter(|w| w.is_finite());
|
||||
// Set vertically (WMode 1): no horizontal advance; its em box is a full em wide.
|
||||
// Set vertically (WMode 1): no horizontal advance.
|
||||
let upright = width.is_some_and(|w| w.abs() <= 1.0);
|
||||
let top = m * kurbo::Point::new(f64::from(width.filter(|w| *w > 1.0).unwrap_or(1000.0)) * 0.5, 880.0);
|
||||
let mut info = self.font_name(key, o);
|
||||
// A font the file doesn't carry is drawn with a stand-in: its glyphs can't tell which
|
||||
// style of the installed family it is, so the name decides.
|
||||
let embedded = self.fonts.get(&key).is_none_or(|(_, e)| *e);
|
||||
let embedded = self.fonts.get(&key).is_none_or(|f| f.embedded);
|
||||
if let Some(face) = &info.face
|
||||
&& embedded
|
||||
{
|
||||
@@ -1772,8 +1771,17 @@ impl<'p> Builder<'p> {
|
||||
stroke,
|
||||
};
|
||||
let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0);
|
||||
let place = |line: &mut TextLine| {
|
||||
if upright { line.push_upright(&look, at, opacity, Upright { top }, &text) } else { line.push(&look, at, opacity, advance, &text) }
|
||||
// A glyph set vertically is drawn from its origin, which the file puts the position
|
||||
// vector's vx (from the font's `W2`, else half its width from `W` or `DW`) to the left of
|
||||
// the column's centre (ISO 32000-1 §9.7.4.3); vertical type centres each glyph on the
|
||||
// column. Half an em only for a full-width glyph (#722).
|
||||
let top = upright.then(|| {
|
||||
let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph));
|
||||
m * kurbo::Point::new(vx, 880.0)
|
||||
});
|
||||
let place = |line: &mut TextLine| match top {
|
||||
Some(top) => line.push_upright(&look, at, opacity, Upright { top }, &text),
|
||||
None => line.push(&look, at, opacity, advance, &text),
|
||||
};
|
||||
self.flush_glyphs();
|
||||
// A stroke over the glyph just filled (fill and stroke rendering).
|
||||
|
||||
@@ -14,10 +14,10 @@ use std::sync::Arc;
|
||||
|
||||
use kurbo::{Point, Rect, Shape};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::{AppearanceItem, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{AppearanceItem, CharStyle, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use crate::import_text::LineFacts;
|
||||
use crate::import_text::{LineFacts, median};
|
||||
|
||||
/// Rebuild the type among `nodes` (and in their groups) from what its lines tell (`lines`).
|
||||
pub(crate) fn rebuild(nodes: &mut Vec<Arc<Node>>, lines: &HashMap<NodeId, LineFacts>) {
|
||||
@@ -148,79 +148,108 @@ fn block(nodes: &[Arc<Node>], lines: &HashMap<NodeId, LineFacts>) -> (usize, Opt
|
||||
(count, (space > -size * 0.01).then_some(Block { leading, space: space.max(0.0), ys }))
|
||||
}
|
||||
|
||||
/// How far a line's characters' tracking may stray (thousandths of an em) and still be one
|
||||
/// value: placing each glyph where the file put it (#722) tracks characters a little apart where
|
||||
/// the file's widths are rounded, or it moved a glyph a hair (`TJ`).
|
||||
const EVEN_TRACKING: f64 = 10.0;
|
||||
|
||||
/// A line's spacing: the tracking after its letters, and how much more its spaces take (word
|
||||
/// spacing, `Tw`; `None` when it has none). `None` when its letters are tracked apart (set by
|
||||
/// hand), or its spaces more than `slack` apart.
|
||||
fn line_spacing(t: &TextObject, slack: f64) -> Option<(f64, Option<f64>)> {
|
||||
// The tracking of the runs with characters that are spaces (`true`) or that aren't.
|
||||
let tracking = |space: bool| -> Vec<f64> {
|
||||
t.runs.iter().filter(|r| r.text.chars().any(|c| c.is_whitespace() == space)).map(|r| r.style.tracking).collect()
|
||||
};
|
||||
let letters = tracking(false);
|
||||
let one = median(letters.clone())?;
|
||||
letters.iter().all(|x| (x - one).abs() <= EVEN_TRACKING).then_some(())?;
|
||||
let spaces = tracking(true);
|
||||
let word = match median(spaces.clone()) {
|
||||
Some(s) => {
|
||||
spaces.iter().all(|x| (x - s).abs() <= slack).then_some(())?;
|
||||
Some(s - one)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Some((one, word))
|
||||
}
|
||||
|
||||
/// The one word spacing (thousandths of an em past the letters' tracking) of lines spaced
|
||||
/// `words` (`None`: no spaces): 0 for lines without.
|
||||
fn one_word_spacing(words: &[Option<f64>]) -> Option<f64> {
|
||||
let w: Vec<f64> = words.iter().flatten().copied().collect();
|
||||
let Some(one) = median(w.clone()) else { return Some(0.0) };
|
||||
w.iter().all(|x| (x - one).abs() <= EVEN_TRACKING).then_some(if one.abs() <= EVEN_TRACKING { 0.0 } else { one })
|
||||
}
|
||||
|
||||
/// Lines `nodes` of block `b` as one area type object, aligned left or justified, when laying it
|
||||
/// out breaks its lines where the file does.
|
||||
fn area_type(nodes: &[Arc<Node>], lines: &HashMap<NodeId, LineFacts>, b: &Block) -> Option<TextObject> {
|
||||
let texts: Vec<(&TextObject, &LineFacts)> = nodes.iter().map(|n| line(n, lines)).collect::<Option<_>>()?;
|
||||
let (first, _) = texts.first()?;
|
||||
let size = first.first_style().size;
|
||||
// A line's tracking: one for all its runs, or (`spaces` false) one for its runs other than
|
||||
// lone spaces.
|
||||
let shared = |t: &TextObject, spaces: bool| {
|
||||
let mut all = t.runs.iter().filter(|r| spaces || r.text != " ").map(|r| r.style.tracking);
|
||||
let one = all.next()?;
|
||||
all.all(|x| x == one).then_some(one)
|
||||
};
|
||||
// As justified type, a wrapped line's tracking leaves out its spaces when each space is a run
|
||||
// of its own, tracked within a fiftieth of an em of the line's first space.
|
||||
let spread = |t: &TextObject| {
|
||||
let tracking = shared(t, false)?;
|
||||
let mut spaces = t.runs.iter().filter(|r| r.text == " ").map(|r| r.style.tracking);
|
||||
let alike =
|
||||
spaces.next().is_some_and(|s| spaces.all(|x| (x - s).abs() <= 20.0)) && !t.runs.iter().any(|r| r.text != " " && r.text.contains(' '));
|
||||
(alike || shared(t, true).is_some()).then_some(tracking)
|
||||
};
|
||||
let trackings: Option<Vec<f64>> = texts.iter().map(|(t, _)| shared(t, true)).collect();
|
||||
let justified: Option<Vec<f64>> = texts.iter().map(|(t, f)| if f.wraps { spread(t) } else { shared(t, true) }).collect();
|
||||
let median = |mut v: Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(v.len() / 2).copied()
|
||||
};
|
||||
// Each line's tracking and word spacing. A justified line spaces its words out (word spacing,
|
||||
// `Tw`), which justification does again (#722); word spacing the same on every line is the
|
||||
// type's own.
|
||||
// A wrapped line's spaces may each be tracked apart, within a fiftieth of an em of each other.
|
||||
let spacings: Vec<(f64, Option<f64>)> =
|
||||
texts.iter().map(|(t, f)| line_spacing(t, if f.wraps { 20.0 } else { EVEN_TRACKING })).collect::<Option<_>>()?;
|
||||
let trackings: Vec<f64> = spacings.iter().map(|(t, _)| *t).collect();
|
||||
let words: Vec<Option<f64>> = spacings.iter().map(|(_, w)| *w).collect();
|
||||
let wrapped: Vec<f64> = texts.iter().filter(|(_, f)| f.wraps).map(|(_, f)| f.length).collect();
|
||||
let longest = |v: &[f64]| v.iter().copied().fold(0.0, f64::max);
|
||||
let mut tries = vec![];
|
||||
// Wrapped lines all as long: justified (a paragraph's last line aligned left), tracked as the
|
||||
// lines that end paragraphs are (the others are spaced out).
|
||||
// Wrapped lines all as long: justified (a paragraph's last line aligned left), tracked and
|
||||
// word spaced as the lines that end paragraphs are (the others are spaced out).
|
||||
let full = longest(&wrapped);
|
||||
let ends: Vec<usize> = texts.iter().enumerate().filter(|(_, (_, f))| !f.wraps).map(|(i, _)| i).collect();
|
||||
let end_words: Vec<Option<f64>> = ends.iter().filter_map(|i| words.get(*i).copied()).collect();
|
||||
if wrapped.len() >= 2
|
||||
&& wrapped.iter().all(|l| (full - l).abs() <= size * 0.02)
|
||||
&& let Some(justified) = justified
|
||||
&& let Some(word) = one_word_spacing(&end_words)
|
||||
{
|
||||
let ends: Vec<f64> = texts.iter().zip(&justified).filter(|((_, f), _)| !f.wraps).map(|(_, t)| *t).collect();
|
||||
let tracking = median(ends).or_else(|| justified.iter().copied().reduce(f64::min))?;
|
||||
tries.push((Justify::JustifyLeft, full, tracking));
|
||||
let tracking =
|
||||
median(ends.iter().filter_map(|i| trackings.get(*i).copied()).collect()).or_else(|| trackings.iter().copied().reduce(f64::min))?;
|
||||
tries.push((Justify::JustifyLeft, full, tracking, word));
|
||||
}
|
||||
let all: Vec<f64> = texts.iter().map(|(_, f)| f.length).collect();
|
||||
if let Some(trackings) = trackings {
|
||||
tries.push((Justify::Left, longest(&all) + size * 0.02, median(trackings)?));
|
||||
// Every line spaced alike: aligned left.
|
||||
if let Some(word) = one_word_spacing(&words) {
|
||||
let all: Vec<f64> = texts.iter().map(|(_, f)| f.length).collect();
|
||||
tries.push((Justify::Left, longest(&all) + size * 0.02, median(trackings)?, word));
|
||||
}
|
||||
tries.into_iter().find_map(|(justify, width, tracking)| laid_out(&texts, b, justify, width, tracking))
|
||||
tries.into_iter().find_map(|(justify, width, tracking, word)| laid_out(&texts, b, justify, width, tracking, word))
|
||||
}
|
||||
|
||||
/// The area type of lines `texts` (block `b`): `width` wide, aligned `justify`, its characters
|
||||
/// tracked `tracking`; `None` when it doesn't lay out as the lines did.
|
||||
fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, width: f64, tracking: f64) -> Option<TextObject> {
|
||||
/// tracked `tracking` and its spaces `word` more; `None` when it doesn't lay out as the lines did.
|
||||
fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, width: f64, tracking: f64, word: f64) -> Option<TextObject> {
|
||||
let (first, _) = texts.first()?;
|
||||
let size = first.first_style().size;
|
||||
// Leading as set, unless it is Auto's (120% of the size).
|
||||
let explicit =
|
||||
(b.leading - size * 1.2).abs() > size * 1e-3 || texts.iter().any(|(t, _)| t.runs.iter().any(|r| (r.style.size - size).abs() > 1e-9));
|
||||
let mut runs: Vec<TextRun> = vec![];
|
||||
let mut push = |text: &str, style: CharStyle| match runs.last_mut() {
|
||||
Some(last) if last.style == style => last.text.push_str(text),
|
||||
_ => runs.push(TextRun { text: text.to_string(), style, inline: None }),
|
||||
};
|
||||
for (k, (t, f)) in texts.iter().enumerate() {
|
||||
let mut style = CharStyle::default();
|
||||
for r in &t.runs {
|
||||
let mut style = r.style.clone();
|
||||
style.tracking = tracking;
|
||||
style = r.style.clone();
|
||||
style.tracking = if r.text.trim().is_empty() { tracking + word } else { tracking };
|
||||
style.leading = explicit.then_some((b.leading * 1000.0).round() / 1000.0);
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.style == style => last.text.push_str(&r.text),
|
||||
_ => runs.push(TextRun { text: r.text.clone(), style, inline: None }),
|
||||
}
|
||||
push(&r.text, style.clone());
|
||||
}
|
||||
// A wrapped line's space, or the end of a paragraph.
|
||||
if k + 1 < texts.len()
|
||||
&& let Some(last) = runs.last_mut()
|
||||
{
|
||||
last.text.push(if f.wraps { ' ' } else { '\n' });
|
||||
if k + 1 < texts.len() {
|
||||
if f.wraps {
|
||||
style.tracking = tracking + word;
|
||||
push(" ", style);
|
||||
} else {
|
||||
push("\n", style);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut t = (*first).clone();
|
||||
|
||||
@@ -20,7 +20,7 @@ use craft_pdf::interpret::CacheKey;
|
||||
use craft_pdf::syntax::Pdf;
|
||||
use craft_pdf::syntax::content::TypedIter;
|
||||
use craft_pdf::syntax::content::ops::TypedInstruction;
|
||||
use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object, ObjectIdentifier, dict_or_stream};
|
||||
use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object, ObjectIdentifier, Stream, dict_or_stream};
|
||||
use craft_pdf::syntax::page::{Page, Resources};
|
||||
|
||||
use crate::PdfError;
|
||||
@@ -617,7 +617,10 @@ impl Walker<'_, '_> {
|
||||
if let Some(f) = res.fonts.get::<Dict<'_>>(key.as_ref())
|
||||
&& let Some(name) = f.get::<Name<'_>>(b"BaseFont")
|
||||
{
|
||||
self.fonts.entry(f.cache_key()).or_insert_with(|| (String::from_utf8_lossy(name.as_ref()).into_owned(), embeds_glyphs(&f)));
|
||||
self.fonts.entry(f.cache_key()).or_insert_with(|| {
|
||||
let embedded = embeds_glyphs(&f);
|
||||
FontNote { name: String::from_utf8_lossy(name.as_ref()).into_owned(), embedded, vertical: vertical_metrics(&f, embedded) }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -841,9 +844,153 @@ impl Walker<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of a document by cache key: base font name, and whether the file carries the glyphs
|
||||
/// ([`embeds_glyphs`]).
|
||||
pub(crate) type FontNames = HashMap<u128, (String, bool)>;
|
||||
/// The fonts of a document by cache key.
|
||||
pub(crate) type FontNames = HashMap<u128, FontNote>;
|
||||
|
||||
/// What a document says of one of its fonts.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FontNote {
|
||||
/// Its base (PostScript) font name.
|
||||
pub name: String,
|
||||
/// The file carries its glyphs ([`embeds_glyphs`]).
|
||||
pub embedded: bool,
|
||||
/// A composite font written vertically: its descendant's metrics.
|
||||
pub vertical: Option<Vertical>,
|
||||
}
|
||||
|
||||
/// The most CIDs a vertical font's widths are read for (the most a CID-keyed font has).
|
||||
const MAX_CIDS: u32 = 65_536;
|
||||
|
||||
/// A vertical composite font's metrics (ISO 32000-1 §9.7.4.3), in glyph space (1000 units an em):
|
||||
/// where each glyph's position vector puts the column's centre.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Vertical {
|
||||
/// The default width (`DW`, w0).
|
||||
default: f64,
|
||||
/// Widths by CID (`W`).
|
||||
widths: HashMap<u32, f64>,
|
||||
/// The position vector's x by CID (`W2`'s vx).
|
||||
vx: HashMap<u32, f64>,
|
||||
/// The CID of each glyph: `None` when they can't be told (a CID-keyed CFF font's charset
|
||||
/// decides, or a font the file doesn't carry is drawn with a stand-in's glyphs).
|
||||
cids: Option<Cids>,
|
||||
}
|
||||
|
||||
/// How glyph ids map back to CIDs.
|
||||
#[derive(Debug)]
|
||||
enum Cids {
|
||||
/// The same (`CIDToGIDMap` `/Identity`, or none).
|
||||
Identity,
|
||||
/// The first CID of each glyph a `CIDToGIDMap` stream maps.
|
||||
Map(HashMap<u32, u32>),
|
||||
}
|
||||
|
||||
impl Vertical {
|
||||
/// How far right of glyph `gid`'s origin (glyph space) the column's centre is: the position
|
||||
/// vector's vx from `W2`, else half the glyph's width (w0 from `W`, or `DW`).
|
||||
pub fn centre(&self, gid: u32) -> f64 {
|
||||
let cid = match &self.cids {
|
||||
Some(Cids::Identity) => Some(gid),
|
||||
Some(Cids::Map(m)) => m.get(&gid).copied(),
|
||||
None => None,
|
||||
};
|
||||
let w0 = |cid: Option<u32>| cid.and_then(|c| self.widths.get(&c)).copied().unwrap_or(self.default) * 0.5;
|
||||
cid.and_then(|c| self.vx.get(&c)).copied().unwrap_or_else(|| w0(cid))
|
||||
}
|
||||
}
|
||||
|
||||
/// The vertical metrics of font `f` when it is a composite font written vertically (its CMap's
|
||||
/// writing mode is 1), from its descendant CIDFont. `embedded`: the file carries its glyphs.
|
||||
pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option<Vertical> {
|
||||
if f.get::<Name<'_>>(b"Subtype")?.as_ref() != b"Type0" {
|
||||
return None;
|
||||
}
|
||||
let vertical = match f.get::<Name<'_>>(b"Encoding") {
|
||||
Some(n) => n.as_ref().ends_with(b"-V"),
|
||||
None => f.get::<Stream<'_>>(b"Encoding").is_some_and(|s| s.dict().get::<i32>(b"WMode") == Some(1)),
|
||||
};
|
||||
if !vertical {
|
||||
return None;
|
||||
}
|
||||
let d = f.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next())?;
|
||||
let finite = |v: f64| v.is_finite() && v.abs() < 1e5;
|
||||
let default = d.get::<f64>(b"DW").filter(|w| finite(*w)).unwrap_or(1000.0);
|
||||
let mut widths = HashMap::new();
|
||||
if let Some(w) = d.get::<Array<'_>>(b"W") {
|
||||
cid_ranges(&w, 1, |cid, v| {
|
||||
if let [w0] = v {
|
||||
widths.insert(cid, *w0);
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut vx = HashMap::new();
|
||||
if let Some(w2) = d.get::<Array<'_>>(b"W2") {
|
||||
cid_ranges(&w2, 3, |cid, v| {
|
||||
if let [_, x, _] = v {
|
||||
vx.insert(cid, *x);
|
||||
}
|
||||
});
|
||||
}
|
||||
widths.retain(|_, w| finite(*w));
|
||||
vx.retain(|_, x| finite(*x));
|
||||
let true_type = d.get::<Name<'_>>(b"Subtype").is_some_and(|s| s.as_ref() == b"CIDFontType2");
|
||||
let cids = if !embedded || !true_type {
|
||||
None
|
||||
} else if let Some(s) = d.get::<Stream<'_>>(b"CIDToGIDMap") {
|
||||
// Two bytes a CID, the glyph it maps to.
|
||||
let data = s.decoded().ok()?;
|
||||
let mut m = HashMap::new();
|
||||
for (cid, g) in (0..MAX_CIDS).zip(data.as_chunks::<2>().0) {
|
||||
m.entry(u32::from(u16::from_be_bytes(*g))).or_insert(cid);
|
||||
}
|
||||
Some(Cids::Map(m))
|
||||
} else {
|
||||
Some(Cids::Identity)
|
||||
};
|
||||
Some(Vertical { default, widths, vx, cids })
|
||||
}
|
||||
|
||||
/// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]`
|
||||
/// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the
|
||||
/// range. At most [`MAX_CIDS`] CIDs are read.
|
||||
fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
|
||||
let mut it = a.flex_iter();
|
||||
let mut read = 0;
|
||||
loop {
|
||||
if let Some((first, list)) = it.next::<(u32, Array<'_>)>() {
|
||||
let values: Vec<f64> = list.iter::<f64>().collect();
|
||||
for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) {
|
||||
read += 1;
|
||||
if read > MAX_CIDS {
|
||||
return;
|
||||
}
|
||||
each(cid, v);
|
||||
}
|
||||
} else if per == 1
|
||||
&& let Some((first, last, w)) = it.next::<(u32, u32, f64)>()
|
||||
{
|
||||
for cid in first..=last.min(first.saturating_add(MAX_CIDS)) {
|
||||
read += 1;
|
||||
if read > MAX_CIDS {
|
||||
return;
|
||||
}
|
||||
each(cid, &[w]);
|
||||
}
|
||||
} else if per == 3
|
||||
&& let Some((first, last, w, x, y)) = it.next::<(u32, u32, f64, f64, f64)>()
|
||||
{
|
||||
for cid in first..=last.min(first.saturating_add(MAX_CIDS)) {
|
||||
read += 1;
|
||||
if read > MAX_CIDS {
|
||||
return;
|
||||
}
|
||||
each(cid, &[w, x, y]);
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether font `f` carries its own glyphs: a font program in its descriptor (a composite font's in
|
||||
/// its descendant's), or a Type 3 font's glyph procedures. A font that doesn't is drawn with a
|
||||
|
||||
+296
-74
@@ -1,6 +1,8 @@
|
||||
//! Text as editable point type: glyphs drawn one after another on the same baseline make one
|
||||
//! point text object of their Unicode text, a run per font, size and paint (a gap wider than a
|
||||
//! fifth of the smaller size beside it reads as a space). Fonts are named from the file's base font name (its
|
||||
//! fifth of the smaller size beside it reads as a space; a glyph the file raised or lowered off the
|
||||
//! baseline, text rise, is baseline shift). Each glyph stays where the file drew it: the kerning
|
||||
//! and tracking the type takes put it there (#722). Fonts are named from the file's base font name (its
|
||||
//! subset prefix dropped, the family matched against the fonts available); a font that isn't
|
||||
//! available keeps its name, and the text shows in the fallback font until it is.
|
||||
//!
|
||||
@@ -161,7 +163,13 @@ pub(crate) struct TextLine {
|
||||
last_size: f64,
|
||||
/// Each glyph's baseline origin, then where the last one ends.
|
||||
baseline: Vec<Point>,
|
||||
runs: Vec<(Look, String)>,
|
||||
/// Runs of glyphs drawn alike: their look, how far the file raised them off the line's
|
||||
/// baseline (points, up; text rise, `Ts`), their text.
|
||||
runs: Vec<(Look, f64, String)>,
|
||||
/// Where the file put each character of the runs' text, in order: the first character of each
|
||||
/// glyph has its glyph's [`Slot`]; a space read from a gap and the other characters of a
|
||||
/// glyph of several have none.
|
||||
slots: Vec<Option<Slot>>,
|
||||
/// The first glyph was set vertically ([`Upright`]).
|
||||
upright: Option<Upright>,
|
||||
/// The glyphs make a column (vertical type), each below the last.
|
||||
@@ -179,13 +187,19 @@ pub(crate) struct TextLine {
|
||||
/// A space the file drew after a glyph that isn't one, until the next glyph comes: its byte
|
||||
/// offset, and the gap before it plus its advance (points).
|
||||
drawn_space: Option<(usize, f64)>,
|
||||
/// Each glyph's advance in the file's font (points), with [`Self::baseline`].
|
||||
advances: Vec<f64>,
|
||||
/// The strokes of its glyphs' outlines drawn between them, one per glyph with ink so far
|
||||
/// (written right after the line).
|
||||
pub held: Vec<Node>,
|
||||
}
|
||||
|
||||
/// Where the file put a glyph: the glyph's index in the line, and its advance in the file's font
|
||||
/// (points) when it shows one character (`None` for a ligature's several).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Slot {
|
||||
glyph: usize,
|
||||
advance: Option<f64>,
|
||||
}
|
||||
|
||||
/// What a finished line of type tells beyond its text object (see [`crate::import_lines`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LineFacts {
|
||||
@@ -213,13 +227,13 @@ impl TextLine {
|
||||
last_size: at.size,
|
||||
baseline: vec![],
|
||||
runs: vec![],
|
||||
slots: vec![],
|
||||
upright: None,
|
||||
column: false,
|
||||
ink: vec![],
|
||||
gaps: vec![],
|
||||
drawn_spaces: vec![],
|
||||
drawn_space: None,
|
||||
advances: vec![],
|
||||
held: vec![],
|
||||
}
|
||||
}
|
||||
@@ -235,8 +249,8 @@ impl TextLine {
|
||||
pub fn push_upright(&mut self, look: &Look, at: Placement, opacity: f32, upright: Upright, text: &str) -> bool {
|
||||
let down = -self.at.up();
|
||||
let size = self.at.size.max(at.size);
|
||||
let Some((last, run)) = self.runs.last_mut() else {
|
||||
self.runs.push((look.clone(), text.to_string()));
|
||||
let Some((last, _, run)) = self.runs.last_mut() else {
|
||||
self.runs.push((look.clone(), 0.0, text.to_string()));
|
||||
(self.upright, self.next, self.last) = (Some(upright), at.origin + down * at.size, at.origin);
|
||||
return true;
|
||||
};
|
||||
@@ -264,7 +278,7 @@ impl TextLine {
|
||||
if last.takes(look) {
|
||||
run.push_str(text);
|
||||
} else {
|
||||
self.runs.push((look.clone(), text.to_string()));
|
||||
self.runs.push((look.clone(), 0.0, text.to_string()));
|
||||
}
|
||||
self.next = at.origin + down * at.size;
|
||||
self.last = at.origin;
|
||||
@@ -278,17 +292,33 @@ impl TextLine {
|
||||
if self.column || self.upright.is_some() {
|
||||
return false;
|
||||
}
|
||||
let bytes: usize = self.runs.iter().map(|(_, t)| t.len()).sum();
|
||||
if let Some((last, run)) = self.runs.last_mut() {
|
||||
let bytes: usize = self.runs.iter().map(|(_, _, t)| t.len()).sum();
|
||||
let glyph = self.baseline.len();
|
||||
let curved = self.curved();
|
||||
let mut shift = 0.0;
|
||||
if let Some((last, last_shift, run)) = self.runs.last_mut() {
|
||||
let size = self.at.size.max(at.size);
|
||||
let gap = (at.origin - self.next).dot(self.last_dir);
|
||||
// How far the glyph sits above the line's baseline. The file raises a superscript or
|
||||
// lowers a subscript (text rise, `Ts`) with the glyphs turned exactly as the rest of
|
||||
// the line (`level`): it stays on the line, shifted off its baseline. Up to half an em
|
||||
// when it follows on from the glyph before (no wider gap than a space reads from):
|
||||
// further apart, it is type of its own (the next cell of a table's row, its baseline a
|
||||
// little higher).
|
||||
let above = (at.origin - self.at.origin).dot(self.at.up());
|
||||
let level = at.dir.dot(self.at.dir) > 1.0 - 1e-9 && !curved;
|
||||
let on_line = opacity == self.opacity
|
||||
&& at.dir.dot(self.at.dir) > 0.9995
|
||||
&& (at.slant - self.at.slant).abs() < 1e-3
|
||||
&& (at.origin - self.at.origin).dot(self.at.up()).abs() < size * 0.15
|
||||
&& (above.abs() < size * 0.15 || (level && above.abs() < size * 0.5 && gap <= size * 0.2))
|
||||
// Proportional widths close CJK marks up by up to half an em.
|
||||
&& gap > -size * 0.6
|
||||
&& gap < size * 3.0;
|
||||
// Within a hair of the baseline (rounding in the file) is on it; a glyph turned a
|
||||
// little (type on a path) sits on the curve, not shifted off it.
|
||||
if on_line && level && above.abs() > size * 0.01 {
|
||||
shift = above;
|
||||
}
|
||||
// Or on a curve: turned a little from the glyph before it, and starting about where
|
||||
// that one ends.
|
||||
let on_curve = !on_line
|
||||
@@ -312,14 +342,17 @@ impl TextLine {
|
||||
self.drawn_spaces.push((b, before + gap));
|
||||
}
|
||||
}
|
||||
if last.takes(look) {
|
||||
if last.takes(look) && (*last_shift - shift).abs() < 1e-3 {
|
||||
run.push_str(text);
|
||||
} else {
|
||||
self.runs.push((look.clone(), text.to_string()));
|
||||
self.runs.push((look.clone(), shift, text.to_string()));
|
||||
}
|
||||
} else {
|
||||
self.runs.push((look.clone(), text.to_string()));
|
||||
self.runs.push((look.clone(), 0.0, text.to_string()));
|
||||
}
|
||||
let one = text.chars().count() == 1;
|
||||
self.slots.push(Some(Slot { glyph, advance: one.then_some(advance) }));
|
||||
self.slots.extend(text.chars().skip(1).map(|_| None));
|
||||
self.next = at.origin + at.dir * advance;
|
||||
if !text.trim().is_empty() {
|
||||
self.visible = self.next;
|
||||
@@ -328,7 +361,6 @@ impl TextLine {
|
||||
self.last_dir = at.dir;
|
||||
self.last_size = at.size;
|
||||
self.baseline.push(at.origin);
|
||||
self.advances.push(advance);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -365,7 +397,7 @@ impl TextLine {
|
||||
/// and stroke rendering), which `overprint`s or not: the run is stroked. `false`: it isn't
|
||||
/// that glyph.
|
||||
pub fn stroke_last(&mut self, font: u128, at: Placement, stroke: (Paint, f64), overprint: bool) -> bool {
|
||||
let Some((look, _)) = self.runs.last_mut().filter(|(l, _)| l.font == font && (at.origin - self.last).hypot() < self.at.size * 1e-3) else {
|
||||
let Some((look, ..)) = self.runs.last_mut().filter(|(l, ..)| l.font == font && (at.origin - self.last).hypot() < self.at.size * 1e-3) else {
|
||||
return false;
|
||||
};
|
||||
(look.stroke, look.overprint_stroke) = (Some(stroke), overprint);
|
||||
@@ -377,15 +409,46 @@ impl TextLine {
|
||||
let mut facts = LineFacts { ink: std::mem::take(&mut self.ink), ..LineFacts::default() };
|
||||
// Turned along a curve: type on a path through the glyphs.
|
||||
let path = if self.curved() { self.baseline_path() } else { None };
|
||||
facts.wraps = path.is_none() && self.upright.is_none() && self.runs.last().is_some_and(|(_, t)| t.ends_with(' '));
|
||||
if let Some((_, last)) = self.runs.last_mut() {
|
||||
facts.wraps = path.is_none() && self.upright.is_none() && self.runs.last().is_some_and(|(.., t)| t.ends_with(' '));
|
||||
if let Some((.., last)) = self.runs.last_mut() {
|
||||
last.truncate(last.trim_end().len());
|
||||
}
|
||||
self.runs.retain(|(_, t)| !t.is_empty());
|
||||
if self.runs.iter().all(|(_, t)| t.trim().is_empty()) {
|
||||
self.runs.retain(|(.., t)| !t.is_empty());
|
||||
if self.runs.iter().all(|(.., t)| t.trim().is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let mut runs = self.runs.into_iter().map(|(look, text)| TextRun { text, style: look.style(), inline: None });
|
||||
// The spaces trimmed off the end have no place either.
|
||||
let chars: usize = self.runs.iter().map(|(.., t)| t.chars().count()).sum();
|
||||
self.slots.truncate(chars);
|
||||
// The baseline most of the characters sit on is the line's: the others are shifted off it
|
||||
// (a line starting with a raised footnote mark keeps the baseline of its text).
|
||||
let mut on: Vec<(f64, usize)> = vec![];
|
||||
for (_, shift, text) in &self.runs {
|
||||
let n = text.chars().count();
|
||||
match on.iter_mut().find(|(s, _)| (s - shift).abs() < 1e-3) {
|
||||
Some((_, count)) => *count += n,
|
||||
None => on.push((*shift, n)),
|
||||
}
|
||||
}
|
||||
// A tie keeps the first glyph's ("m²" sits on the m's baseline).
|
||||
let base = on.iter().fold(None::<(f64, usize)>, |best, &(s, n)| if best.is_none_or(|(_, b)| n > b) { Some((s, n)) } else { best });
|
||||
let base = base.map_or(0.0, |(s, _)| s);
|
||||
if path.is_some() {
|
||||
// Type on a path sits on its curve: no glyph is shifted off it.
|
||||
for (_, shift, _) in &mut self.runs {
|
||||
*shift = 0.0;
|
||||
}
|
||||
} else if base != 0.0 {
|
||||
// Up the slant the type leans by (a sheared text matrix), as the file raises it.
|
||||
self.at.origin += (self.at.up() + self.at.dir * self.at.slant) * base;
|
||||
for (_, shift, _) in &mut self.runs {
|
||||
*shift -= base;
|
||||
}
|
||||
}
|
||||
let mut runs = self.runs.into_iter().map(|(look, shift, text)| {
|
||||
let style = CharStyle { baseline_shift: round(shift), ..look.style() };
|
||||
TextRun { text, style, inline: None }
|
||||
});
|
||||
let first = runs.next()?;
|
||||
let mut t = TextObject::point(Point::ORIGIN, &first.text, first.style);
|
||||
t.runs.extend(runs);
|
||||
@@ -409,15 +472,21 @@ impl TextLine {
|
||||
// After the earlier spaces, at the end of the run before it (the run it follows).
|
||||
let at = gap.at + spaces.len();
|
||||
let mut offset = 0;
|
||||
let Some(run) = t.runs.iter_mut().find(|run| {
|
||||
let Some(i) = t.runs.iter().position(|run| {
|
||||
offset += run.text.len();
|
||||
at <= offset
|
||||
}) else {
|
||||
break;
|
||||
};
|
||||
// The characters before it, in the runs before and in its own.
|
||||
let earlier: usize = t.runs.iter().take(i).map(|r| r.text.chars().count()).sum();
|
||||
let Some(run) = t.runs.get_mut(i) else { break };
|
||||
let at = at - (offset - run.text.len());
|
||||
if !run.text.is_char_boundary(at) {
|
||||
continue;
|
||||
let Some(head) = run.text.get(..at) else { continue };
|
||||
// A space read from a gap has no slot of its own.
|
||||
let char_at = earlier + head.chars().count();
|
||||
if char_at <= self.slots.len() {
|
||||
self.slots.insert(char_at, None);
|
||||
}
|
||||
run.text.insert(at, ' ');
|
||||
spaces.push((gap.at, gap.width, gap.on_line));
|
||||
@@ -433,19 +502,20 @@ impl TextLine {
|
||||
// The glyphs' tops lean along the baseline (+x), up being -y in the type's own space.
|
||||
t.xf = Affine::translate(self.at.origin.to_vec2()) * Affine::rotate(angle) * Affine::skew(-self.at.slant, 0.0);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Glyphs spaced each their own way (character tightening, optical kerning) keep their
|
||||
// place: each character its own tracking.
|
||||
let own = (self.upright.is_none() && t.para.direction.is_none())
|
||||
.then(|| own_spacing(&t, &self.baseline, &self.advances, path.as_ref(), self.at.dir, self.at.size))
|
||||
.flatten();
|
||||
if let Some(own) = &own {
|
||||
t.runs = tracked_each(std::mem::take(&mut t.runs), own, self.at.size);
|
||||
}
|
||||
// Each glyph where the file put it (#722): the kerning (the font's, or none) and tracking
|
||||
// (one value for the line, or each character its own) that place them there.
|
||||
let placed = (self.upright.is_none() && t.para.direction.is_none())
|
||||
.then(|| place_each(&t, &self.slots, &self.baseline, path.as_ref(), self.at, self.at.size))
|
||||
.flatten()
|
||||
.map(|(runs, laid)| {
|
||||
t.runs = runs;
|
||||
laid.bounds
|
||||
});
|
||||
if let Some(path) = path {
|
||||
// Evenly spaced type keeps its length along the path: the path runs through the
|
||||
// glyphs' origins, one curve each, to the end of the last glyph, and tracking makes up
|
||||
// the difference from the advances.
|
||||
if own.is_none() {
|
||||
if placed.is_none() {
|
||||
let length: f64 = path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum();
|
||||
let laid = vectorcraft_text::layout(db, &t);
|
||||
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
|
||||
@@ -479,12 +549,17 @@ impl TextLine {
|
||||
if !t.vertical {
|
||||
facts.length = length;
|
||||
}
|
||||
// Placed glyph by glyph: laid out so already.
|
||||
if let Some(bounds) = placed {
|
||||
t.cached_bounds = Some(bounds);
|
||||
return Some((t, self.opacity, facts));
|
||||
}
|
||||
let laid = vectorcraft_text::layout(db, &t);
|
||||
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
|
||||
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let size = self.at.size;
|
||||
let mut bounds = laid.bounds;
|
||||
if own.is_none() && chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
|
||||
if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
|
||||
// The spaces read from gaps or drawn between glyphs keep their own place only in text
|
||||
// left in the file's order.
|
||||
let total: usize = t.runs.iter().map(|r| r.text.len()).sum();
|
||||
@@ -499,59 +574,206 @@ impl TextLine {
|
||||
}
|
||||
}
|
||||
|
||||
/// The space each glyph of `t` (laid out untracked) leaves after its advance to put the next one
|
||||
/// where the file did (points; the last glyph's is the one before it), when that varies by more
|
||||
/// than a fiftieth of an em: one tracking value can't place them. Glyph origins are `baseline`,
|
||||
/// measured along `path` (type on a path: one curve per glyph) or along `dir`. None when the
|
||||
/// glyphs can't be matched to the characters one to one (spaces, ligatures), or when the font
|
||||
/// laid out isn't the file's (its advances differ from `advances`): spacing measured against a
|
||||
/// stand-in's widths would keep the stand-in's differences once the font is installed.
|
||||
fn own_spacing(t: &TextObject, baseline: &[Point], advances: &[f64], path: Option<&BezPath>, dir: Vec2, size: f64) -> Option<Vec<f64>> {
|
||||
let text: String = t.runs.iter().map(|r| r.text.as_str()).collect();
|
||||
let chars = text.chars().count();
|
||||
if chars < 3 || text.contains(' ') || baseline.len() != chars || advances.len() != chars {
|
||||
return None;
|
||||
/// Where along the line (points) layout `laid` puts each character at a byte offset of `chars`
|
||||
/// (in order), and its advance: `None` for one inside another's cluster. Text in the file's order
|
||||
/// (left to right).
|
||||
fn pens(laid: &TextLayout, chars: &[usize]) -> Vec<Option<(f64, f64)>> {
|
||||
let mut at = vec![None; chars.len()];
|
||||
let mut pen = 0.0;
|
||||
for g in &laid.glyphs {
|
||||
if let Some(slot) = chars.binary_search(&g.byte).ok().and_then(|i| at.get_mut(i)) {
|
||||
slot.get_or_insert((pen, g.advance));
|
||||
}
|
||||
pen += g.advance;
|
||||
}
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let advs: Vec<f64> = laid.glyphs.iter().map(|g| g.advance).collect();
|
||||
if advs.len() != chars || advs.iter().zip(advances).any(|(a, b)| (a - b).abs() > size * 0.01) {
|
||||
return None;
|
||||
}
|
||||
let dist: Vec<f64> = match path {
|
||||
Some(bp) => bp.segments().take(chars - 1).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).collect(),
|
||||
None => baseline.windows(2).map(|w| (w[1] - w[0]).dot(dir)).collect(),
|
||||
};
|
||||
if dist.len() != chars - 1 {
|
||||
return None;
|
||||
}
|
||||
let mut extra: Vec<f64> = dist.iter().zip(&advs).map(|(d, a)| d - a).collect();
|
||||
let mean = extra.iter().sum::<f64>() / extra.len() as f64;
|
||||
if extra.iter().all(|e| (e - mean).abs() <= size * 0.02) {
|
||||
return None;
|
||||
}
|
||||
extra.push(*extra.last()?);
|
||||
Some(extra)
|
||||
at
|
||||
}
|
||||
|
||||
/// `runs` with each character's tracking from `own` (points, one per character), characters with
|
||||
/// the same tracking kept in one run.
|
||||
fn tracked_each(runs: Vec<TextRun>, own: &[f64], size: f64) -> Vec<TextRun> {
|
||||
let em = |pts: f64| (pts / size * 1000.0).clamp(-1000.0, 1000.0).round();
|
||||
let mut out: Vec<TextRun> = vec![];
|
||||
/// `t`'s runs with kerning `kern` and each character's tracking from `own` (points, one per
|
||||
/// character, in thousandths of each run's em), characters alike kept in one run.
|
||||
fn restyled(t: &TextObject, kern: Option<f64>, own: &[f64]) -> Vec<TextRun> {
|
||||
let mut out: Vec<TextRun> = Vec::with_capacity(t.runs.len());
|
||||
// The run of `t` the last character came from.
|
||||
let mut from = None;
|
||||
let mut k = 0;
|
||||
for r in runs {
|
||||
for (i, r) in t.runs.iter().enumerate() {
|
||||
let size = r.style.size.max(1e-3);
|
||||
for c in r.text.chars() {
|
||||
let style = CharStyle { tracking: own.get(k).map_or(0.0, |e| em(*e)), ..r.style.clone() };
|
||||
let tracking = own.get(k).map_or(0.0, |e| (e / size * 1000.0).clamp(-1000.0, 10000.0));
|
||||
k += 1;
|
||||
// Hundredths of a thousandth of an em: no drift along a line, no noise in the panels.
|
||||
let tracking = (tracking * 100.0).round() / 100.0;
|
||||
match out.last_mut() {
|
||||
Some(last) if last.style == style && last.inline == r.inline => last.text.push(c),
|
||||
_ => out.push(TextRun { text: c.to_string(), style, inline: r.inline.clone() }),
|
||||
Some(last) if from == Some(i) && last.style.tracking == tracking => last.text.push(c),
|
||||
last => {
|
||||
let style = CharStyle { tracking, kerning: kern, ..r.style.clone() };
|
||||
match last {
|
||||
Some(last) if last.style == style && last.inline == r.inline => last.text.push(c),
|
||||
_ => out.push(TextRun { text: c.to_string(), style, inline: r.inline.clone() }),
|
||||
}
|
||||
}
|
||||
}
|
||||
from = Some(i);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The runs of `t` that put its glyphs where the file did (#722), and their layout: with the
|
||||
/// font's kerning or none, whichever the file's spacing follows, and tracking that is the same
|
||||
/// after every character when the file spaced them evenly, else each character's own (word
|
||||
/// spacing, `TJ` adjustments, character tightening, spaces read from gaps).
|
||||
///
|
||||
/// The file put the glyph of each character with a [`Slot`] at `baseline` (one origin per glyph),
|
||||
/// measured along `path` (type on a path: one curve per glyph) or along `line`'s baseline from its
|
||||
/// origin, where a character shifted off it by its baseline shift draws that shift times `line`'s
|
||||
/// slant further along (the type's skew leans it so, as the file's text rise did). `None` when the
|
||||
/// font laid out isn't the file's (its advances differ from the file's): spacing measured against
|
||||
/// a stand-in's widths would keep the stand-in's differences once the font is installed; or when
|
||||
/// the glyphs can't be placed so (the layout joins characters the file drew apart).
|
||||
fn place_each(
|
||||
t: &TextObject,
|
||||
slots: &[Option<Slot>],
|
||||
baseline: &[Point],
|
||||
path: Option<&BezPath>,
|
||||
line: Placement,
|
||||
size: f64,
|
||||
) -> Option<(Vec<TextRun>, TextLayout)> {
|
||||
let chars: Vec<usize> = t
|
||||
.runs
|
||||
.iter()
|
||||
.scan(0, |off, r| {
|
||||
let base = *off;
|
||||
*off += r.text.len();
|
||||
Some(r.text.char_indices().map(move |(i, _)| base + i).collect::<Vec<_>>())
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
if chars.len() < 2 || chars.len() != slots.len() || t.runs.iter().any(|r| r.inline.is_some()) {
|
||||
return None;
|
||||
}
|
||||
// How far along the line the file put each glyph.
|
||||
let along: Vec<f64> = match path {
|
||||
Some(bp) => std::iter::once(0.0)
|
||||
.chain(bp.segments().scan(0.0, |d, seg| {
|
||||
*d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3);
|
||||
Some(*d)
|
||||
}))
|
||||
.take(baseline.len())
|
||||
.collect(),
|
||||
None => baseline.iter().map(|p| (*p - line.origin).dot(line.dir)).collect(),
|
||||
};
|
||||
// Each character's baseline shift, which the type's slant draws `slant` times as far along.
|
||||
let shifts: Vec<f64> = t.runs.iter().flat_map(|r| r.text.chars().map(move |_| r.style.baseline_shift)).collect();
|
||||
let slant = if path.is_some() { 0.0 } else { line.slant };
|
||||
// Each character's target: where the file put it, if it put it anywhere.
|
||||
let target: Vec<Option<(f64, Option<f64>)>> =
|
||||
slots.iter().zip(&shifts).map(|(s, shift)| s.and_then(|s| Some((*along.get(s.glyph)? - slant * shift, s.advance)))).collect();
|
||||
if target.first().is_none_or(Option::is_none) || target.iter().flatten().any(|(d, _)| !d.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// The spacing each character takes after it, laid out with `pens`: whatever puts the next one
|
||||
// the file placed where it did. Characters between two the file placed (a space read from a
|
||||
// gap, the rest of a ligature) take the line's spacing, the last of them the rest.
|
||||
let spacing = |pens: &[Option<(f64, f64)>]| -> Option<Vec<f64>> {
|
||||
// How far each character the file placed is from where the layout puts it.
|
||||
let placed: Vec<(usize, f64)> =
|
||||
target.iter().zip(pens).enumerate().filter_map(|(i, (t, p))| Some((i, t.as_ref()?.0 - p.as_ref()?.0))).collect();
|
||||
let steps: Vec<f64> = placed.windows(2).filter(|w| w[1].0 == w[0].0 + 1).map(|w| w[1].1 - w[0].1).collect();
|
||||
let line = median(steps).unwrap_or(0.0);
|
||||
let mut own = vec![line; chars.len()];
|
||||
for w in placed.windows(2) {
|
||||
let ((a, da), (b, db)) = (w[0], w[1]);
|
||||
*own.get_mut(b.checked_sub(1)?)? = db - da - line * (b - a - 1) as f64;
|
||||
}
|
||||
// After the last character the file placed, spacing changes nothing: the line's.
|
||||
let last = placed.last()?.0;
|
||||
let tail = if last > 0 { own.get(last - 1).copied().unwrap_or(line) } else { line };
|
||||
for e in own.get_mut(last..).into_iter().flatten() {
|
||||
*e = tail;
|
||||
}
|
||||
Some(own)
|
||||
};
|
||||
// Evenly spaced: one tracking value for the line. (A file rounds its widths to thousandths of
|
||||
// an em: a hair either way is even.)
|
||||
let even = |own: &[f64]| {
|
||||
let line = median(own.to_vec())?;
|
||||
own.iter().all(|e| (e - line).abs() <= size * 0.002).then(|| vec![line; own.len()])
|
||||
};
|
||||
let changes = |own: &[f64]| own.windows(2).filter(|w| (w[1] - w[0]).abs() > size * 1e-4).count();
|
||||
// The type as it is: untracked, with the font's kerning.
|
||||
let auto = vectorcraft_text::layout(db, t);
|
||||
// Each glyph's own advance (the font's, unkerned) tells whether the layout's font is the
|
||||
// file's, whether the font kerned any of the line's pairs, and where the glyphs go unkerned
|
||||
// (the same glyphs, each on its own advance: no layout needed to tell).
|
||||
let mut faces: Vec<std::sync::Arc<vectorcraft_text::FontFace>> = vec![];
|
||||
let mut unkerned_pens = vec![None; chars.len()];
|
||||
let mut pen = 0.0;
|
||||
let mut kerned_any = false;
|
||||
for g in &auto.glyphs {
|
||||
let face = match faces.iter().find(|f| f.id() == g.font_id) {
|
||||
Some(f) => f.clone(),
|
||||
None => {
|
||||
let f = db.face_by_id(g.font_id)?;
|
||||
faces.push(f.clone());
|
||||
f
|
||||
}
|
||||
};
|
||||
let style = &t.runs.get(g.run)?.style;
|
||||
let own = face.advance(g.gid) * style.size / face.units_per_em().max(1e-9) * style.h_scale / 100.0;
|
||||
kerned_any |= (own - g.advance).abs() > size * 1e-6;
|
||||
if let Some(slot) = chars.binary_search(&g.byte).ok().and_then(|i| unkerned_pens.get_mut(i)) {
|
||||
slot.get_or_insert((pen, own));
|
||||
}
|
||||
pen += own;
|
||||
}
|
||||
let same_font = unkerned_pens.iter().zip(&target).all(|(n, t)| match t {
|
||||
Some((_, Some(adv))) => n.is_some_and(|(_, a): (f64, f64)| (a - adv).abs() <= size * 0.01),
|
||||
_ => true,
|
||||
});
|
||||
if !same_font {
|
||||
return None;
|
||||
}
|
||||
// The font's kerning when the file followed it (or there is none to follow), else none.
|
||||
let kerned = spacing(&pens(&auto, &chars))?;
|
||||
let (kern, own) = match even(&kerned) {
|
||||
Some(own) => (None, own),
|
||||
// Without kerning the line lays out the same.
|
||||
None if !kerned_any => (None, kerned),
|
||||
None => {
|
||||
let unkerned = spacing(&unkerned_pens)?;
|
||||
match even(&unkerned) {
|
||||
Some(own) => (Some(0.0), own),
|
||||
None if changes(&unkerned) < changes(&kerned) => (Some(0.0), unkerned),
|
||||
None => (None, kerned),
|
||||
}
|
||||
}
|
||||
};
|
||||
let runs = restyled(t, kern, &own);
|
||||
// As the type is: laid out so already.
|
||||
if kern.is_none() && runs.iter().all(|r| r.style.tracking == 0.0) {
|
||||
return Some((runs, auto));
|
||||
}
|
||||
// Laid out so, are they where the file put them? (A ligature the layout forms where the file
|
||||
// drew two glyphs moves those after it.)
|
||||
let mut probe = t.clone();
|
||||
probe.runs = runs;
|
||||
let check = vectorcraft_text::layout(db, &probe);
|
||||
let got = pens(&check, &chars);
|
||||
let ok = got.iter().zip(&target).all(|(g, t)| match t {
|
||||
Some((d, _)) => g.is_some_and(|(p, _)| (p - d).abs() <= size * 0.02),
|
||||
None => true,
|
||||
});
|
||||
ok.then_some((probe.runs, check))
|
||||
}
|
||||
|
||||
/// The middle value of `v` (the upper one of an even count).
|
||||
pub(crate) fn median(mut v: Vec<f64>) -> Option<f64> {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(v.len() / 2).copied()
|
||||
}
|
||||
|
||||
/// The tracking (thousandths of an em) that sets a line of `chars` characters, laid out untracked
|
||||
/// as `laid`, `extra` points longer, as the file set it: the same after every character, except
|
||||
/// the spaces read from gaps or drawn between glyphs (`gaps`: byte offset, gap in points) where
|
||||
|
||||
@@ -307,6 +307,8 @@ mod tests_stroke;
|
||||
#[cfg(test)]
|
||||
mod tests_strokeout;
|
||||
#[cfg(test)]
|
||||
mod tests_text_placement;
|
||||
#[cfg(test)]
|
||||
mod tests_textstroke;
|
||||
#[cfg(test)]
|
||||
mod tests_webview;
|
||||
|
||||
@@ -1068,3 +1068,35 @@ fn dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill() {
|
||||
assert_ne!(export_with(true, false), export_with(false, false), "the fill's pixels carry the noise");
|
||||
assert_eq!(export_with(true, true), export_with(false, true), "a stroke has no dither");
|
||||
}
|
||||
|
||||
/// COLR glyphs in the PDF: as real text, in their font's Type 3 glyphs (the foreground layer in
|
||||
/// the fill); outlined, as vector art, a sweep glyph as an image.
|
||||
#[test]
|
||||
fn colr_glyphs_export_as_vector_art() {
|
||||
use vectorcraft_text::test_fonts::{COLOUR_CHAR, COLR_SWEEP_CHAR, colr_family, colr_font};
|
||||
for v1 in [false, true] {
|
||||
vectorcraft_text::FontDb::global().add_font(colr_font(v1).unwrap());
|
||||
}
|
||||
let page = |v1: bool, ch: char, outline_text: bool| {
|
||||
let mut d = doc(300.0, 100.0);
|
||||
let fill = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let st = CharStyle { font_family: colr_family(v1).into(), size: 24.0, fill, ..CharStyle::default() };
|
||||
add(&mut d, Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 50.0), &ch.to_string(), st)))));
|
||||
let mut o = PdfOptions::uncompressed();
|
||||
o.settings.advanced.outline_text = outline_text;
|
||||
import_with_report(&export(&d, &o).unwrap(), &ImportOptions::default()).unwrap().document
|
||||
};
|
||||
let fills = |d: &Document| -> Vec<Paint> { leaves(d).iter().map(|n| n.appearance.fill_paint()).collect() };
|
||||
let near =
|
||||
|p: &Paint, rgb: [f32; 3]| matches!(p, Paint::Solid { color, .. } if color.to_rgb().iter().zip(rgb).all(|(a, b)| (a - b).abs() < 0.02));
|
||||
for outline_text in [false, true] {
|
||||
let v0 = fills(&page(false, COLOUR_CHAR, outline_text));
|
||||
assert!(v0.iter().any(|p| near(p, [1.0, 0.0, 0.0])), "the red layer (outlined {outline_text}): {v0:?}");
|
||||
assert!(v0.iter().any(|p| near(p, [0.0, 0.0, 1.0])), "the foreground layer in the fill (outlined {outline_text}): {v0:?}");
|
||||
}
|
||||
let v1 = page(true, COLOUR_CHAR, true);
|
||||
assert!(!leaves(&v1).iter().any(|n| matches!(n.kind, NodeKind::Image(_))), "vector art");
|
||||
assert!(fills(&v1).iter().any(|p| matches!(p, Paint::Gradient(_))), "with its gradients");
|
||||
let sweep = page(true, COLR_SWEEP_CHAR, true);
|
||||
assert!(leaves(&sweep).iter().any(|n| matches!(n.kind, NodeKind::Image(_))), "a sweep glyph is an image");
|
||||
}
|
||||
@@ -384,7 +384,8 @@ fn fonts_are_noted_past_font_resources_the_reader_cannot_parse() {
|
||||
let mut fonts = crate::import_scan::FontNames::new();
|
||||
let mut ocgs = crate::import_scan::Ocgs::read(&pdf);
|
||||
crate::import_scan::scan_page(&pdf.pages()[0], &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()).unwrap();
|
||||
assert_eq!(fonts.into_values().collect::<Vec<_>>(), [("Helvetica".to_string(), false)], "{junk}");
|
||||
let noted: Vec<_> = fonts.into_values().map(|f| (f.name, f.embedded)).collect();
|
||||
assert_eq!(noted, [("Helvetica".to_string(), false)], "{junk}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,599 @@
|
||||
//! #722: type from a PDF lands where the file draws it. Each file here is written from scratch
|
||||
//! from the PDF specification (ISO 32000-1 §9, "Text": the text state, text-positioning and
|
||||
//! text-showing operators, Type 0, Type 3 and TrueType fonts, vertical writing), with Source Sans 3
|
||||
//! from this repo's assets embedded as its font program. What the file draws (its glyphs opened as
|
||||
//! outlines) and what the type it opens as draws must match contour by contour.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, Rect, Shape};
|
||||
use vectorcraft_doc::{Document, NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
use vectorcraft_text::{FontDb, FontFace};
|
||||
|
||||
use crate::tests_import_fidelity::stream;
|
||||
use crate::*;
|
||||
|
||||
const SOURCE_SANS: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
|
||||
fn sans() -> Arc<FontFace> {
|
||||
FontDb::global().find_postscript("SourceSans3-Regular").expect("Source Sans 3 is built in")
|
||||
}
|
||||
|
||||
/// Source Sans 3's advance of `c`, in thousandths of an em (as a PDF's widths give it).
|
||||
fn width(c: char) -> f64 {
|
||||
let face = sans();
|
||||
(face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em()).round()
|
||||
}
|
||||
|
||||
/// The font program of Source Sans 3 Regular as a stream (ASCII hex).
|
||||
fn font_file() -> String {
|
||||
let hex: String = SOURCE_SANS.iter().map(|b| format!("{b:02X}")).collect::<String>() + ">";
|
||||
stream(&format!("/Length1 {} /Filter /ASCIIHexDecode", SOURCE_SANS.len()), &hex)
|
||||
}
|
||||
|
||||
/// A font descriptor for the font program in object `file`.
|
||||
fn descriptor(file: usize) -> String {
|
||||
format!(
|
||||
"<< /Type /FontDescriptor /FontName /SourceSans3-Regular /Flags 32 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 1024 /Descent -400 /CapHeight 660 /StemV 80 /FontFile2 {file} 0 R >>"
|
||||
)
|
||||
}
|
||||
|
||||
/// A simple TrueType font (WinAnsi, Source Sans 3's widths) described by object `desc`.
|
||||
fn simple(desc: usize) -> String {
|
||||
let widths: Vec<String> = (32u8..=126).map(|c| width(c as char).to_string()).collect();
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /TrueType /BaseFont /SourceSans3-Regular /FirstChar 32 /LastChar 126 /Widths [{}] /FontDescriptor {desc} 0 R /Encoding /WinAnsiEncoding >>",
|
||||
widths.join(" ")
|
||||
)
|
||||
}
|
||||
|
||||
/// The characters the Type 0 fonts map: printable ASCII, and symbols that stand upright in
|
||||
/// vertical type and are narrower than an em.
|
||||
fn cid_chars() -> impl Iterator<Item = char> {
|
||||
(32u8..=126).map(char::from).chain("§±×".chars())
|
||||
}
|
||||
|
||||
/// `text` as a string of Source Sans 3's glyph ids, two bytes each (Identity-H or Identity-V,
|
||||
/// CIDToGIDMap Identity).
|
||||
fn gids(text: &str) -> String {
|
||||
let face = sans();
|
||||
let hex: String = text.chars().map(|c| format!("{:04X}", face.glyph_for(c))).collect();
|
||||
format!("<{hex}>")
|
||||
}
|
||||
|
||||
/// A ToUnicode map of Source Sans 3's glyph ids for [`cid_chars`].
|
||||
fn to_unicode() -> String {
|
||||
let face = sans();
|
||||
let rows: Vec<String> = cid_chars().map(|c| format!("<{:04X}> <{:04X}>", face.glyph_for(c), c as u32)).collect();
|
||||
let data = format!(
|
||||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Test-UCS def /CMapType 2 def 1 begincodespacerange <0000> <FFFF> endcodespacerange {} beginbfchar\n{}\nendbfchar endcmap CMapName currentdict /CMap defineresource pop end end",
|
||||
rows.len(),
|
||||
rows.join("\n")
|
||||
);
|
||||
stream("", &data)
|
||||
}
|
||||
|
||||
/// A CID-keyed TrueType font (the descendant of the Type 0 fonts) of Source Sans 3 with its
|
||||
/// widths (/W), described by object `desc`.
|
||||
fn cid_font(desc: usize) -> String {
|
||||
let face = sans();
|
||||
let w: Vec<String> = cid_chars().map(|c| format!("{} [{}]", face.glyph_for(c), width(c))).collect();
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /SourceSans3-Regular /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {desc} 0 R /CIDToGIDMap /Identity /DW 1000 /W [{}] >>",
|
||||
w.join(" ")
|
||||
)
|
||||
}
|
||||
|
||||
/// [`cid_font`] with vertical metrics (/W2: each glyph's position vector half its width across,
|
||||
/// 880 up) and no /W (every width the default, an em).
|
||||
fn cid_font_w2(desc: usize) -> String {
|
||||
let face = sans();
|
||||
let w2: Vec<String> = cid_chars().map(|c| format!("{} [-1000 {} 880]", face.glyph_for(c), width(c) / 2.0)).collect();
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /SourceSans3-Regular /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {desc} 0 R /CIDToGIDMap /Identity /DW 1000 /DW2 [880 -1000] /W2 [{}] >>",
|
||||
w2.join(" ")
|
||||
)
|
||||
}
|
||||
|
||||
/// A Type 3 font (object `first`, its glyph procedures the two after it) whose glyph space is
|
||||
/// 1/`upm` of text space (FontMatrix [1/upm 0 0 1/upm 0 0]): `a` is half an em wide and draws a box
|
||||
/// 0.4 em wide, `b` an em wide with a box of 0.9 em; both boxes are 0.7 em tall on the baseline.
|
||||
fn type3(first: usize, upm: f64) -> Vec<String> {
|
||||
let s = 1.0 / upm;
|
||||
let (h, w) = (upm * 0.5, upm);
|
||||
let a = stream("", &format!("{h} 0 d0 0 0 {} {} re f", h * 0.8, upm * 0.7));
|
||||
let b = stream("", &format!("{w} 0 d0 0 0 {} {} re f", w * 0.9, upm * 0.7));
|
||||
let font = format!(
|
||||
"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 {w} {w}] /FontMatrix [{s} 0 0 {s} 0 0] /CharProcs << /a {} 0 R /b {} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [{h} {w}] /Resources << >> >>",
|
||||
first + 1,
|
||||
first + 2
|
||||
);
|
||||
vec![font, a, b]
|
||||
}
|
||||
|
||||
/// A 300 × 200 pt page drawing `content`, plus `entries` in the page dictionary, with fonts:
|
||||
/// - `/F1`: Source Sans 3, embedded, a simple TrueType font;
|
||||
/// - `/F4`: Source Sans 3 as a Type 0 font, Identity-H (two-byte glyph ids, see [`gids`]);
|
||||
/// - `/F5`: the same, Identity-V (vertical writing);
|
||||
/// - `/F6`: the same with vertical metrics (/W2) and no widths (/W), Identity-V;
|
||||
/// - `/T3`, `/T30`: Type 3 fonts of 1000 and of 100 units an em;
|
||||
/// - `/HV`: Helvetica, not embedded.
|
||||
fn page(content: &str, entries: &str) -> Vec<u8> {
|
||||
sized_page(300.0, 200.0, content, entries)
|
||||
}
|
||||
|
||||
/// [`page`], `w` × `h` pt.
|
||||
fn sized_page(w: f64, h: f64, content: &str, entries: &str) -> Vec<u8> {
|
||||
let n = first_extra(1);
|
||||
let type0 = |enc: &str, cid: usize| {
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /SourceSans3-Regular /Encoding /{enc} /DescendantFonts [{cid} 0 R] /ToUnicode {} 0 R >>",
|
||||
n + 4
|
||||
)
|
||||
};
|
||||
let mut objs = vec![
|
||||
font_file(), // n
|
||||
descriptor(n), // n + 1
|
||||
simple(n + 1), // n + 2: F1
|
||||
cid_font(n + 1), // n + 3
|
||||
to_unicode(), // n + 4
|
||||
type0("Identity-H", n + 3), // n + 5: F4
|
||||
type0("Identity-V", n + 3), // n + 6: F5
|
||||
cid_font_w2(n + 1), // n + 7
|
||||
type0("Identity-V", n + 7), // n + 8: F6
|
||||
];
|
||||
let t3 = n + objs.len();
|
||||
objs.extend(type3(t3, 1000.0));
|
||||
objs.extend(type3(t3 + 3, 100.0));
|
||||
let refs: Vec<&str> = objs.iter().map(String::as_str).collect();
|
||||
let resources = format!(
|
||||
"/Font << /F1 {} 0 R /F4 {} 0 R /F5 {} 0 R /F6 {} 0 R /T3 {t3} 0 R /T30 {} 0 R /HV << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >>",
|
||||
n + 2,
|
||||
n + 5,
|
||||
n + 6,
|
||||
n + 8,
|
||||
t3 + 3
|
||||
);
|
||||
pdf_with(&[PdfPage { resources, entries: entries.into(), ..PdfPage::new(w, h, content) }], &refs, None)
|
||||
}
|
||||
|
||||
fn open_as(bytes: &[u8], text_as: TextAs) -> Document {
|
||||
import_with_report(bytes, &ImportOptions { text_as, ..Default::default() }).unwrap().document
|
||||
}
|
||||
|
||||
fn texts(d: &Document) -> Vec<TextObject> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
v.push((**t).clone());
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
fn plain(d: &Document) -> Vec<String> {
|
||||
texts(d).iter().map(TextObject::plain_text).collect()
|
||||
}
|
||||
|
||||
/// The largest difference between two boxes' edges.
|
||||
fn off(a: Rect, b: Rect) -> f64 {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
|
||||
}
|
||||
|
||||
/// The bounds of each contour of `bp` (each subpath).
|
||||
fn contours_of(bp: &BezPath, out: &mut Vec<Rect>) {
|
||||
let mut cur = BezPath::new();
|
||||
for el in bp.elements() {
|
||||
if matches!(el, PathEl::MoveTo(_)) && cur.elements().len() > 1 {
|
||||
out.push(std::mem::take(&mut cur).bounding_box());
|
||||
}
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
cur = BezPath::new();
|
||||
}
|
||||
cur.push(*el);
|
||||
}
|
||||
if cur.elements().len() > 1 {
|
||||
out.push(cur.bounding_box());
|
||||
}
|
||||
}
|
||||
|
||||
/// The contours `d` draws: its paths' and its type's glyphs', in document space.
|
||||
fn contours(d: &Document) -> Vec<Rect> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => contours_of(&path.to_bezpath(), &mut out),
|
||||
NodeKind::Text(t) => {
|
||||
for g in vectorcraft_text::layout(FontDb::global(), t).glyphs {
|
||||
contours_of(&(t.xf * g.outline), &mut out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// How far (points) the glyphs of the type `bytes` opens as are from where the file draws them:
|
||||
/// the furthest any contour the file draws is from the nearest one the type draws, or the other
|
||||
/// way round.
|
||||
fn displacement(bytes: &[u8]) -> f64 {
|
||||
let drawn = contours(&open_as(bytes, TextAs::Outlines));
|
||||
let typed = contours(&open_as(bytes, TextAs::Text));
|
||||
assert!(!drawn.is_empty() && !typed.is_empty(), "the file draws glyphs");
|
||||
let worst = |a: &[Rect], b: &[Rect]| a.iter().map(|r| b.iter().map(|s| off(*r, *s)).fold(f64::INFINITY, f64::min)).fold(0.0, f64::max);
|
||||
worst(&drawn, &typed).max(worst(&typed, &drawn))
|
||||
}
|
||||
|
||||
/// The type `content` opens as lands where the file draws it, as `want` (its objects' text).
|
||||
#[track_caller]
|
||||
fn lands(content: &str, entries: &str, want: &[&str]) {
|
||||
let bytes = page(content, entries);
|
||||
assert_eq!(plain(&open_as(&bytes, TextAs::Text)), want, "{content}");
|
||||
let d = displacement(&bytes);
|
||||
assert!(d < 0.02, "{content}: glyphs {d:.3} pt from where the file draws them");
|
||||
}
|
||||
|
||||
/// Three lines wrapped in a frame (each wrapped line ends in a space).
|
||||
const PARAGRAPH: &str = "(The quick brown fox ) Tj T* (jumps over the lazy ) Tj T* (dog and runs away.) Tj";
|
||||
const PARAGRAPH_TEXT: &str = "The quick brown fox jumps over the lazy dog and runs away.";
|
||||
|
||||
/// The text-positioning operators and the text matrix under any CTM: lines start where the file
|
||||
/// starts them, the glyphs of each where it draws them.
|
||||
#[test]
|
||||
fn text_positioning_and_the_ctm_put_type_where_the_file_draws_it() {
|
||||
let lines = ["Line one", "Line two", "Line three"];
|
||||
for (content, entries, want) in [
|
||||
("BT /F1 24 Tf 20 50 Td (Hello World) Tj ET", "", &["Hello World"][..]),
|
||||
("BT /F1 1 Tf 24 0 0 24 20 50 Tm (Hello World) Tj ET", "", &["Hello World"]),
|
||||
("q 2 0 0 2 10 10 cm BT /F1 12 Tf 10 20 Td (Hello World) Tj ET Q", "", &["Hello World"]),
|
||||
// A y-down CTM with a text matrix that turns the type upright again.
|
||||
("q 1 0 0 -1 0 200 cm BT /F1 12 Tf 1 0 0 -1 20 50 Tm (Hello World) Tj ET Q", "", &["Hello World"]),
|
||||
("BT /F1 12 Tf 14 TL 20 150 Td (Line one) Tj T* (Line two) Tj T* (Line three) Tj ET", "", &lines),
|
||||
("BT /F1 12 Tf 20 150 Td (Line one) Tj 0 -16 TD (Line two) Tj T* (Line three) Tj ET", "", &lines),
|
||||
// ' moves to the next line; " also sets word and character spacing.
|
||||
("BT /F1 12 Tf 14 TL 20 150 Td (Line one) Tj (Line two) ' 2 1 (Line three) \" ET", "", &lines),
|
||||
("BT /F1 18 Tf 0.866 0.5 -0.5 0.866 40 40 Tm (Turned line) Tj ET", "", &["Turned line"]),
|
||||
("BT /F1 1 Tf 30 0 0 15 20 50 Tm (Squashed) Tj ET", "", &["Squashed"]),
|
||||
("q 1 0 0 0.5 0 0 cm BT /F1 20 Tf 20 100 Td (Squashed) Tj ET Q", "", &["Squashed"]),
|
||||
("BT /F1 24 Tf 60 80 Td (Cropped) Tj ET", "/CropBox [40 30 260 180]", &["Cropped"]),
|
||||
("BT /F1 24 Tf 20 50 Td (Turned page) Tj ET", "/Rotate 90", &["Turned page"]),
|
||||
] {
|
||||
lands(content, entries, want);
|
||||
}
|
||||
}
|
||||
|
||||
/// Horizontal scaling, character and word spacing, and `TJ`'s adjustments: each glyph keeps the
|
||||
/// place the file gave it (they used to be evened out over the line, and laid out with the font's
|
||||
/// kerning where the file had none, so the glyphs between the ends slid).
|
||||
#[test]
|
||||
fn spacing_and_scaling_keep_each_glyph_where_the_file_put_it() {
|
||||
for (content, want) in [
|
||||
("BT /F1 20 Tf 50 Tz 20 50 Td (Narrow type) Tj ET", "Narrow type"),
|
||||
("BT /F1 20 Tf 150 Tz 20 50 Td (Wide type) Tj ET", "Wide type"),
|
||||
("BT /F1 16 Tf 2 Tc 20 50 Td (Spaced out) Tj ET", "Spaced out"),
|
||||
("BT /F1 16 Tf -0.8 Tc 20 50 Td (Tight type here) Tj ET", "Tight type here"),
|
||||
("BT /F1 16 Tf 6 Tw 20 50 Td (Word space here) Tj ET", "Word space here"),
|
||||
("BT /F1 16 Tf 1.5 Tc 80 Tz 20 50 Td (Spaced and narrow) Tj ET", "Spaced and narrow"),
|
||||
("BT /F1 16 Tf 20 50 Td [(A) 120 (V) -80 (A) 300 (Tower)] TJ ET", "AVATower"),
|
||||
("BT /F1 16 Tf 20 50 Td (AVATAR WAVE) Tj ET", "AVATAR WAVE"),
|
||||
] {
|
||||
lands(content, "", &[want]);
|
||||
}
|
||||
// Two-byte codes of a Type 0 font alike (word spacing applies only to single-byte code 32,
|
||||
// ISO 32000-1 §9.3.3: none here).
|
||||
for content in ["BT /F4 24 Tf 70 Tz 3 Ts 20 50 Td <> Tj ET", "BT /F4 24 Tf 9 Tw 2 Tc 20 50 Td <> Tj ET"] {
|
||||
lands(&content.replace("<>", &gids("Hello World")), "", &["Hello World"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Word spacing stays on the spaces, as tracking of their own; evenly spaced letters keep one
|
||||
/// tracking value for the line, and a file that didn't kern opens with kerning off.
|
||||
#[test]
|
||||
fn word_spacing_is_tracking_on_the_spaces_and_unkerned_type_opens_unkerned() {
|
||||
let d = open_as(&page("BT /F1 16 Tf 6 Tw 20 50 Td (Word space here) Tj ET", ""), TextAs::Text);
|
||||
let t = texts(&d);
|
||||
let letters: Vec<f64> = t[0].runs.iter().filter(|r| r.text != " ").map(|r| r.style.tracking).collect();
|
||||
let spaces: Vec<f64> = t[0].runs.iter().filter(|r| r.text == " ").map(|r| r.style.tracking).collect();
|
||||
assert_eq!(spaces.len(), 2, "{:?}", t[0].runs);
|
||||
for s in &spaces {
|
||||
assert!((s - 375.0).abs() < 0.5, "6 pt at 16 pt is 375/1000 em: {spaces:?}");
|
||||
}
|
||||
assert!(letters.iter().all(|l| l.abs() < 0.5), "the letters as the font spaces them: {letters:?}");
|
||||
// "AV", "VA", "WA" kern in Source Sans 3; this file set them on their widths alone.
|
||||
let d = open_as(&page("BT /F1 16 Tf 20 50 Td (AVATAR WAVE) Tj ET", ""), TextAs::Text);
|
||||
let t = texts(&d);
|
||||
assert_eq!(t[0].runs.len(), 1, "{:?}", t[0].runs);
|
||||
assert_eq!(t[0].runs[0].style.kerning, Some(0.0), "kerning off, as the file set it");
|
||||
assert!(t[0].runs[0].style.tracking.abs() < 0.5);
|
||||
}
|
||||
|
||||
/// Type the font's kerning spaced (as editors write it) keeps the font's kerning.
|
||||
#[test]
|
||||
fn kerned_type_keeps_the_fonts_kerning() {
|
||||
let bytes = crate::tests_live_text::text_pdf(&[(20.0, 50.0, 24.0, "AVATAR WAVE")], false);
|
||||
let d = open_as(&bytes, TextAs::Text);
|
||||
let t = texts(&d);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert!(t[0].runs.iter().all(|r| r.style.kerning.is_none()), "{:?}", t[0].runs);
|
||||
assert!(displacement(&bytes) < 0.02);
|
||||
}
|
||||
|
||||
/// Text rise (`Ts`): a superscript or subscript stays in its line as baseline shift (it used to be
|
||||
/// pulled onto the baseline within 0.15 em of it, or split off as an object of its own), and a line
|
||||
/// that starts raised keeps the baseline of the rest of its text.
|
||||
#[test]
|
||||
fn raised_and_lowered_characters_stay_in_their_line_shifted_off_its_baseline() {
|
||||
for (content, want) in [
|
||||
("BT /F1 12 Tf 20 50 Td 5 Ts (Raised line) Tj ET", "Raised line"),
|
||||
("BT /F1 12 Tf 20 50 Td (E = mc) Tj 5 Ts (2) Tj 0 Ts ( here) Tj ET", "E = mc2 here"),
|
||||
("BT /F1 12 Tf 20 50 Td (H) Tj -3 Ts (2) Tj 0 Ts (O water) Tj ET", "H2O water"),
|
||||
("BT /F1 12 Tf 20 50 Td (H) Tj 1.5 Ts (2) Tj 0 Ts (O water) Tj ET", "H2O water"),
|
||||
("BT /F1 12 Tf 20 50 Td (CO) Tj -1.2 Ts /F1 8 Tf (2) Tj 0 Ts /F1 12 Tf ( gas) Tj ET", "CO2 gas"),
|
||||
("BT /F1 12 Tf 20 50 Td 1.5 Ts (1) Tj 0 Ts (Footnote text) Tj ET", "1Footnote text"),
|
||||
] {
|
||||
lands(content, "", &[want]);
|
||||
}
|
||||
// Under a sheared text matrix (slanted type) text rise moves a glyph along the slant, as the
|
||||
// type's slant draws its baseline shift: the shifted glyphs land where the file draws them.
|
||||
for (content, want) in [
|
||||
("BT /F1 12 Tf 1 0 0.2 1 20 50 Tm (E = mc) Tj 5 Ts (2) Tj ET", "E = mc2"),
|
||||
("BT /F1 12 Tf 1 0 0.2 1 20 50 Tm (E = mc) Tj 5 Ts (2) Tj 0 Ts ( here) Tj ET", "E = mc2 here"),
|
||||
("BT /F1 12 Tf 1 0 -0.3 1 20 50 Tm (H) Tj -3 Ts (2) Tj 0 Ts (O water) Tj ET", "H2O water"),
|
||||
("BT /F1 12 Tf 1 0 0.2 1 20 50 Tm 1.5 Ts (1) Tj 0 Ts (Footnote text) Tj ET", "1Footnote text"),
|
||||
("BT /F1 12 Tf 1 0 0.2 1 20 50 Tm 4 Ts (Raised) Tj ET", "Raised"),
|
||||
] {
|
||||
lands(content, "", &[want]);
|
||||
}
|
||||
let t = texts(&open_as(&page("BT /F1 12 Tf 20 50 Td 1.5 Ts (1) Tj 0 Ts (Footnote text) Tj ET", ""), TextAs::Text));
|
||||
let origin = t[0].xf * Point::ZERO;
|
||||
assert!((origin.y - 150.0).abs() < 1e-6, "on the text's baseline, not the mark's: {origin:?}");
|
||||
assert_eq!(t[0].runs[0].text, "1");
|
||||
assert!((t[0].runs[0].style.baseline_shift - 1.5).abs() < 1e-6, "{:?}", t[0].runs[0].style.baseline_shift);
|
||||
assert!(t[0].runs[1..].iter().all(|r| r.style.baseline_shift == 0.0));
|
||||
}
|
||||
|
||||
/// Lines wrapped in a frame (area type, as an editor writes it: each line placed with `T*` or `Td`)
|
||||
/// come back as one area type object whose glyphs are where the lines' were: aligned left, or
|
||||
/// justified with word spacing (`Tw`) on each wrapped line.
|
||||
#[test]
|
||||
fn text_boxes_open_where_their_lines_were() {
|
||||
for content in [
|
||||
format!("BT /F1 12 Tf 14 TL 20 150 Td {PARAGRAPH} ET"),
|
||||
format!("BT /F1 12 Tf 14 TL 4 Ts 80 Tz 20 150 Td {PARAGRAPH} ET"),
|
||||
format!("q 1.5 0 0 1.5 5 5 cm BT /F1 8 Tf 10 TL 10 90 Td {PARAGRAPH} ET Q"),
|
||||
format!("BT /F1 12 Tf 14 TL 0.866 0.5 -0.5 0.866 40 40 Tm {PARAGRAPH} ET"),
|
||||
] {
|
||||
let t = texts(&open_as(&page(&content, ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1, "{content}: one text box");
|
||||
assert!(matches!(t[0].kind, TextKind::Area { .. }), "{content}");
|
||||
lands(&content, "", &[PARAGRAPH_TEXT]);
|
||||
}
|
||||
// Justified: every wrapped line spaced out to the frame's width with word spacing.
|
||||
let lines = ["The quick brown fox ", "jumps over the lazy ", "dog and runs away."];
|
||||
let (size, frame) = (12.0, 110.0);
|
||||
let mut content = format!("BT /F1 {size} Tf 20 170 Td ");
|
||||
for (i, l) in lines.iter().enumerate() {
|
||||
let natural = l.trim_end().chars().map(width).sum::<f64>() * size / 1000.0;
|
||||
let spaces = l.trim_end().matches(' ').count() as f64;
|
||||
let tw = if i + 1 < lines.len() { (frame - natural) / spaces } else { 0.0 };
|
||||
if i > 0 {
|
||||
content += "0 -14.4 Td ";
|
||||
}
|
||||
content += &format!("{tw:.4} Tw ({l}) Tj ");
|
||||
}
|
||||
content += "ET";
|
||||
let t = texts(&open_as(&page(&content, ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1, "one text box: {:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
|
||||
assert_eq!(t[0].para.justify, vectorcraft_doc::Justify::JustifyLeft);
|
||||
lands(&content, "", &[PARAGRAPH_TEXT]);
|
||||
}
|
||||
|
||||
/// Vertical writing (Identity-V): the file puts each glyph's origin half its width (/W) left of
|
||||
/// the column (ISO 32000-1 §9.7.4.3); glyphs narrower than an em stay centred on it.
|
||||
#[test]
|
||||
fn vertical_glyphs_narrower_than_an_em_stay_on_their_column() {
|
||||
lands(&format!("BT /F5 24 Tf 150 180 Td {} Tj ET", gids("§±×")), "", &["§±×"]);
|
||||
}
|
||||
|
||||
/// Type 3 glyphs (drawn by their procedures, kept as outlines) are scaled by the font's matrix:
|
||||
/// the same boxes at 1000 and at 100 units an em.
|
||||
#[test]
|
||||
fn type3_glyphs_follow_the_font_matrix() {
|
||||
for font in ["T3", "T30"] {
|
||||
let d = open_as(&page(&format!("BT /{font} 20 Tf 20 50 Td (ab) Tj ET"), ""), TextAs::Text);
|
||||
assert!(texts(&d).is_empty(), "Type 3 text keeps its outlines");
|
||||
let mut boxes = contours(&d);
|
||||
boxes.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
// `a` at x 20 (0.4 em = 8 pt wide), `b` after its half-em advance; 0.7 em = 14 pt tall,
|
||||
// standing on the baseline at y 150 (200 - 50).
|
||||
let want = [Rect::new(20.0, 136.0, 28.0, 150.0), Rect::new(30.0, 136.0, 48.0, 150.0)];
|
||||
assert_eq!(boxes.len(), 2, "{font}: {boxes:?}");
|
||||
for (b, w) in boxes.iter().zip(want) {
|
||||
assert!(off(*b, w) < 1e-3, "{font}: {b:?} vs {w:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font that isn't embedded or installed is set in a stand-in: the line still starts where
|
||||
/// the file starts it, on its baseline, and is as long as the file's.
|
||||
#[test]
|
||||
fn type_in_a_stand_in_font_still_starts_where_the_file_starts_it() {
|
||||
let t = texts(&open_as(&page("BT /HV 12 Tf 6 Tw 20 50 Td 5 Ts (Raised word line) Tj ET", ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1);
|
||||
assert_eq!(t[0].plain_text(), "Raised word line");
|
||||
let origin = t[0].xf * Point::ZERO;
|
||||
assert!((origin.x - 20.0).abs() < 1e-6 && (origin.y - 145.0).abs() < 1e-6, "{origin:?}");
|
||||
}
|
||||
|
||||
/// Type on a gentle arc: each glyph turned a little from the one before, the first few within a
|
||||
/// hair of the first's direction. They sit on the curve; none is shifted off it as well (which
|
||||
/// moved them off the curve by the shift twice over).
|
||||
#[test]
|
||||
fn type_on_a_gentle_arc_sits_on_its_curve_unshifted() {
|
||||
let text = "Gentle arc of type here";
|
||||
let (size, r) = (12.0, 450.0);
|
||||
let (cx, cy) = (150.0, -300.0);
|
||||
let mut phi = 100f64.to_radians();
|
||||
let mut content = format!("BT /F1 {size} Tf ");
|
||||
for c in text.chars() {
|
||||
let a = phi - std::f64::consts::FRAC_PI_2;
|
||||
let (x, y) = (cx + r * phi.cos(), cy + r * phi.sin());
|
||||
let esc = if c == ' ' { " ".to_string() } else { c.to_string() };
|
||||
content += &format!("{:.6} {:.6} {:.6} {:.6} {x:.4} {y:.4} Tm ({esc}) Tj ", a.cos(), a.sin(), -a.sin(), a.cos());
|
||||
phi -= width(c) * size / 1000.0 / r;
|
||||
}
|
||||
content += "ET";
|
||||
let t = texts(&open_as(&page(&content, ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1, "{:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
|
||||
assert_eq!(t[0].plain_text(), text);
|
||||
assert!(matches!(t[0].kind, TextKind::OnPath { .. }), "type on a path");
|
||||
assert!(t[0].runs.iter().all(|r| r.style.baseline_shift == 0.0), "{:?}", t[0].runs);
|
||||
let d = displacement(&page(&content, ""));
|
||||
assert!(d < 0.05, "glyphs {d:.3} pt off the curve");
|
||||
}
|
||||
|
||||
/// A line with as many raised characters as level ones keeps the baseline of its first glyph:
|
||||
/// "m²" sits on the m's baseline, the 2 shifted up.
|
||||
#[test]
|
||||
fn a_tie_keeps_the_first_glyphs_baseline() {
|
||||
let content = "BT /F1 12 Tf 20 50 Td (m) Tj 5 Ts (2) Tj ET";
|
||||
lands(content, "", &["m2"]);
|
||||
let t = texts(&open_as(&page(content, ""), TextAs::Text));
|
||||
let origin = t[0].xf * Point::ZERO;
|
||||
assert!((origin.y - 150.0).abs() < 1e-6, "on the m's baseline: {origin:?}");
|
||||
assert_eq!(t[0].runs.len(), 2, "{:?}", t[0].runs);
|
||||
assert_eq!(t[0].runs[0].style.baseline_shift, 0.0);
|
||||
assert!((t[0].runs[1].style.baseline_shift - 5.0).abs() < 1e-6, "{:?}", t[0].runs[1].style);
|
||||
}
|
||||
|
||||
/// The cells of a table's row whose baselines differ a little (a third of an em) stay objects of
|
||||
/// their own: only a character that follows on from the one before is raised in its line.
|
||||
#[test]
|
||||
fn table_cells_a_little_apart_stay_apart() {
|
||||
for content in [
|
||||
"BT /F1 12 Tf 20 50 Td (Cell one) Tj 60 3.6 Td (Cell two) Tj ET",
|
||||
"BT /F1 12 Tf 20 50 Td (Cell one) Tj 60 -3.6 Td (Cell two) Tj ET",
|
||||
"BT /F1 12 Tf 20 50 Td (Cell one) Tj 3.6 Ts 60 0 Td (Cell two) Tj ET",
|
||||
] {
|
||||
lands(content, "", &["Cell one", "Cell two"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertical writing with the font's own vertical metrics (/W2): each glyph's position vector puts
|
||||
/// the column's centre where the font says (ISO 32000-1 §9.7.4.3), not half the default width.
|
||||
#[test]
|
||||
fn vertical_type_takes_the_fonts_position_vectors() {
|
||||
lands(&format!("BT /F6 24 Tf 150 180 Td {} Tj ET", gids("§±×")), "", &["§±×"]);
|
||||
}
|
||||
|
||||
/// A vertical font's metrics as the file gives them: /W2 first, then half the width from /W, then
|
||||
/// half /DW; glyphs mapped back to their CIDs through a /CIDToGIDMap stream; a CFF font's glyphs
|
||||
/// (whose charset maps them) take /DW's.
|
||||
#[test]
|
||||
fn vertical_font_metrics_are_read_from_w2_w_and_dw() {
|
||||
use craft_pdf::syntax::Pdf;
|
||||
use craft_pdf::syntax::object::{Dict, ObjectIdentifier};
|
||||
let n = first_extra(1);
|
||||
// CID → glyph: 10 → 5, 20 → 6, 30 → 7, 31 → 9, 40 → 8 (others 0).
|
||||
let mut map = [0u16; 41];
|
||||
for (cid, gid) in [(10, 5), (20, 6), (30, 7), (31, 9), (40, 8)] {
|
||||
map[cid] = gid;
|
||||
}
|
||||
let hex: String = map.iter().map(|g| format!("{g:04X}")).collect::<String>() + ">";
|
||||
let descendant = |subtype: &str, gid_map: &str| {
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /{subtype} /BaseFont /Test /DW 900 /W [10 20 600 30 [400 500]] /W2 [10 [-1000 222 880] 40 41 -1000 333 880] {gid_map} >>"
|
||||
)
|
||||
};
|
||||
let type0 = |enc: &str, d: usize| format!("<< /Type /Font /Subtype /Type0 /BaseFont /Test /Encoding /{enc} /DescendantFonts [{d} 0 R] >>");
|
||||
let objs = [
|
||||
stream("/Filter /ASCIIHexDecode", &hex), // n
|
||||
descendant("CIDFontType2", &format!("/CIDToGIDMap {n} 0 R")), // n + 1
|
||||
type0("Identity-V", n + 1), // n + 2
|
||||
descendant("CIDFontType2", ""), // n + 3
|
||||
type0("Identity-V", n + 3), // n + 4
|
||||
descendant("CIDFontType0", ""), // n + 5
|
||||
type0("Identity-V", n + 5), // n + 6
|
||||
type0("Identity-H", n + 3), // n + 7
|
||||
];
|
||||
let refs: Vec<&str> = objs.iter().map(String::as_str).collect();
|
||||
let bytes = pdf_with(&[PdfPage::new(100.0, 100.0, "")], &refs, None);
|
||||
let pdf = Pdf::new(Arc::new(bytes)).unwrap();
|
||||
let font = |k: usize| pdf.xref().get::<Dict<'_>>(ObjectIdentifier::new((n + k) as i32, 0)).unwrap();
|
||||
let mapped = crate::import_scan::vertical_metrics(&font(2), true).expect("vertical");
|
||||
for (gid, want) in [(5, 222.0), (6, 300.0), (7, 200.0), (9, 250.0), (8, 333.0), (100, 450.0)] {
|
||||
assert_eq!(mapped.centre(gid), want, "glyph {gid}");
|
||||
}
|
||||
// CIDToGIDMap /Identity: glyph ids are CIDs.
|
||||
let identity = crate::import_scan::vertical_metrics(&font(4), true).expect("vertical");
|
||||
for (gid, want) in [(10, 222.0), (15, 300.0), (31, 250.0), (41, 333.0), (42, 450.0)] {
|
||||
assert_eq!(identity.centre(gid), want, "glyph {gid}");
|
||||
}
|
||||
// A font the file doesn't carry, or a CFF one: its glyphs can't be told by CID.
|
||||
let stand_in = crate::import_scan::vertical_metrics(&font(4), false).expect("vertical");
|
||||
let cff = crate::import_scan::vertical_metrics(&font(6), true).expect("vertical");
|
||||
assert_eq!((stand_in.centre(10), cff.centre(10)), (450.0, 450.0));
|
||||
assert!(crate::import_scan::vertical_metrics(&font(7), true).is_none(), "horizontal");
|
||||
}
|
||||
|
||||
/// Area type whose lines the file spaced a hair unevenly (`TJ` adjustments of a few thousandths
|
||||
/// of an em) still comes back as one text box.
|
||||
#[test]
|
||||
fn text_boxes_with_a_hair_of_uneven_spacing_still_open_as_one() {
|
||||
let content =
|
||||
"BT /F1 12 Tf 14 TL 20 150 Td [(The qu) -4 (ick brown fox )] TJ T* [(jumps o) 5 (ver the) -3 ( lazy )] TJ T* (dog and runs away.) Tj ET";
|
||||
let t = texts(&open_as(&page(content, ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1, "one text box: {:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
|
||||
assert!(matches!(t[0].kind, TextKind::Area { .. }));
|
||||
assert_eq!(t[0].plain_text(), PARAGRAPH_TEXT);
|
||||
assert!(displacement(&page(content, "")) < 0.1);
|
||||
}
|
||||
|
||||
/// Word spacing the same on every line of a text box, its last line too, is the type's: it comes
|
||||
/// back as one text box, aligned left, its spaces tracked apart.
|
||||
#[test]
|
||||
fn text_boxes_word_spaced_throughout_open_as_one() {
|
||||
let content = format!("BT /F1 12 Tf 14 TL 2 Tw 20 150 Td {PARAGRAPH} ET");
|
||||
let t = texts(&open_as(&page(&content, ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1, "one text box: {:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
|
||||
assert!(matches!(t[0].kind, TextKind::Area { .. }));
|
||||
assert_eq!(t[0].para.justify, vectorcraft_doc::Justify::Left);
|
||||
let spaces: Vec<f64> = t[0].runs.iter().filter(|r| r.text.trim().is_empty()).map(|r| r.style.tracking).collect();
|
||||
assert!(!spaces.is_empty() && spaces.iter().all(|s| (s - 2.0 / 12.0 * 1000.0).abs() < 1.0), "{:?}", t[0].runs);
|
||||
lands(&content, "", &[PARAGRAPH_TEXT]);
|
||||
}
|
||||
|
||||
/// A text-heavy page: `columns` columns of `rows` lines of 10 pt type, alternately plain lines and
|
||||
/// paragraphs wrapped in a frame (left aligned, and justified with word spacing).
|
||||
fn text_heavy(columns: usize, rows: usize) -> Vec<u8> {
|
||||
const WORDS: [&str; 12] = ["Gather", "the", "quick", "brown", "fox", "over", "lazy", "dogs", "while", "AVATAR", "waves", "kerning"];
|
||||
let mut content = String::new();
|
||||
for c in 0..columns {
|
||||
let x = 20.0 + c as f64 * 200.0;
|
||||
content += &format!("BT /F1 10 Tf 12 TL {x} {} Td ", 40.0 + rows as f64 * 12.0);
|
||||
for r in 0..rows {
|
||||
let words: Vec<&str> = (0..6).map(|k| WORDS[(c * 7 + r * 5 + k) % WORDS.len()]).collect();
|
||||
let wrapped = c % 2 == 1 && r % 6 != 5;
|
||||
let tw = if c % 4 == 3 && wrapped { 1.5 } else { 0.0 };
|
||||
content += &format!("{tw} Tw ({}{}) Tj T* ", words.join(" "), if wrapped { " " } else { "" });
|
||||
}
|
||||
content += "ET ";
|
||||
}
|
||||
sized_page(40.0 + columns as f64 * 200.0, 80.0 + rows as f64 * 12.0, &content, "")
|
||||
}
|
||||
|
||||
/// How long a text-heavy file takes to open as type (run by hand: `-- --ignored --nocapture`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn perf_text_heavy_open() {
|
||||
let bytes = text_heavy(20, 200);
|
||||
for _ in 0..2 {
|
||||
let start = std::time::Instant::now();
|
||||
let d = open_as(&bytes, TextAs::Text);
|
||||
let took = start.elapsed();
|
||||
let n = texts(&d).len();
|
||||
let start = std::time::Instant::now();
|
||||
let _ = open_as(&bytes, TextAs::Outlines);
|
||||
println!("4000 lines: {n} text objects in {took:?} (as outlines: {:?})", start.elapsed());
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,8 @@ pub const MAX_STROKE_WIDTH: f64 = 1000.0;
|
||||
pub const MITER_LIMIT: std::ops::RangeInclusive<f64> = 1.0..=500.0;
|
||||
/// Longest effect id a plug-in may return, in bytes.
|
||||
pub const MAX_EFFECT_ID: usize = 128;
|
||||
/// Largest data a plug-in may keep with a document (`documentData`), in bytes of JSON.
|
||||
pub const MAX_DOCUMENT_DATA: usize = 1 << 20;
|
||||
|
||||
/// One object returned by a plug-in. `None` fields keep the object's value (new objects take the
|
||||
/// defaults: a path, non-zero rule, no fills or strokes, full opacity).
|
||||
@@ -373,11 +375,45 @@ fn decode_effect(v: &Value, at: &str) -> Result<Effect> {
|
||||
Ok(Effect { id: id.to_string(), params, visible })
|
||||
}
|
||||
|
||||
/// Parses a plug-in's output: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in
|
||||
/// declined (the message reaches the user).
|
||||
/// What a filter returned: its objects, and what it keeps with the document.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Output {
|
||||
pub objects: Vec<OutObject>,
|
||||
/// `documentData`, as `Document::set_plugin_data` takes it: `None` when the output has none
|
||||
/// (what the plug-in keeps stays as it is), `Some(None)` for `null` (it forgets it), else what
|
||||
/// it keeps from now on, at most [`MAX_DOCUMENT_DATA`] bytes of JSON.
|
||||
pub document_data: Option<Option<Value>>,
|
||||
}
|
||||
|
||||
/// Parses a filter's output: `{"objects": [...], "documentData"?: …}`, or `{"error": "message"}`
|
||||
/// when the plug-in declined (the message reaches the user).
|
||||
pub fn decode_output(bytes: &[u8]) -> Result<Output> {
|
||||
let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
let objects = decode_objects(&v)?;
|
||||
let document_data = match v.get_mut("documentData").map(Value::take) {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(data) => {
|
||||
let size = serde_json::to_vec(&data).map_or(usize::MAX, |b| b.len());
|
||||
if size > MAX_DOCUMENT_DATA {
|
||||
return Err(Error::Output(format!("`documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA})")));
|
||||
}
|
||||
Some(Some(data))
|
||||
}
|
||||
};
|
||||
Ok(Output { objects, document_data })
|
||||
}
|
||||
|
||||
/// Parses a plug-in's objects: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in
|
||||
/// declined (the message reaches the user). A live effect's other keys don't matter.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Vec<OutObject>> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
if let Some(e) = declined(&v) {
|
||||
decode_objects(&v)
|
||||
}
|
||||
|
||||
/// The objects of output `v`, or its decline.
|
||||
fn decode_objects(v: &Value) -> Result<Vec<OutObject>> {
|
||||
if let Some(e) = declined(v) {
|
||||
return Err(e);
|
||||
}
|
||||
let objects = v.get("objects").and_then(Value::as_array).ok_or_else(|| Error::Output("expected {\"objects\": [...]}".into()))?;
|
||||
|
||||
@@ -269,3 +269,25 @@ fn bad_stroke_styles_and_effect_records_are_refused() {
|
||||
assert!(decode_json(json!({"objects": [{"id": a, "effects": bad}]})).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
|
||||
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
|
||||
#[test]
|
||||
fn document_data_is_kept_forgotten_or_refused() {
|
||||
let out = |data: Option<Value>| {
|
||||
let mut v = json!({"objects": []});
|
||||
if let Some(data) = data {
|
||||
v["documentData"] = data;
|
||||
}
|
||||
decode_output(v.to_string().as_bytes()).map(|o| o.document_data)
|
||||
};
|
||||
assert_eq!(out(None).unwrap(), None);
|
||||
assert_eq!(out(Some(Value::Null)).unwrap(), Some(None));
|
||||
assert_eq!(out(Some(json!({"pens": 2}))).unwrap(), Some(Some(json!({"pens": 2}))));
|
||||
// A string's quotes count: this one is the limit exactly, and one more byte refuses it.
|
||||
let at = json!("x".repeat(MAX_DOCUMENT_DATA - 2));
|
||||
assert_eq!(out(Some(at.clone())).unwrap(), Some(Some(at)));
|
||||
assert!(matches!(out(Some(json!("x".repeat(MAX_DOCUMENT_DATA - 1)))), Err(Error::Output(_))));
|
||||
// A decline is still a decline.
|
||||
assert!(matches!(decode_output(br#"{"error": "No pens.", "documentData": 1}"#), Err(Error::Failed(_))));
|
||||
}
|
||||
@@ -1821,6 +1821,10 @@ impl Renderer {
|
||||
b.apply_affine(t.xf * *to_text);
|
||||
self.hairline(ctx, f, &b, [0, 0, 0, 255]);
|
||||
}
|
||||
// COLR glyphs: their layers' outlines.
|
||||
for (_, art) in &g.colours {
|
||||
self.draw_colour_glyph(ctx, f, art, t.xf);
|
||||
}
|
||||
self.draw_inlines(ctx, f, t, g);
|
||||
return;
|
||||
}
|
||||
@@ -1867,6 +1871,9 @@ impl Renderer {
|
||||
overprint(ctx, false);
|
||||
self.draw_glyph_image(ctx, f, image, t.xf * *to_text);
|
||||
}
|
||||
for (_, art) in g.colours.iter().filter(|(r, _)| *r == i) {
|
||||
self.draw_colour_glyph(ctx, f, art, t.xf);
|
||||
}
|
||||
let path = g.run(i);
|
||||
let path = path.as_ref();
|
||||
if path.elements().is_empty() {
|
||||
@@ -1923,6 +1930,15 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw COLR glyph `art` (its layers in text space) through `xf` (text space → document), as
|
||||
/// art: kept between frames as symbol art is ([`Self::placed_art`]).
|
||||
fn draw_colour_glyph(&mut self, ctx: &mut RenderContext, f: &Frame, art: &Arc<Node>, xf: Affine) {
|
||||
let (node, kept) = self.placed_art(art, xf, true, None);
|
||||
let outer = std::mem::replace(&mut self.made_again, !kept);
|
||||
self.draw_node(ctx, f, &node, true);
|
||||
self.made_again = outer;
|
||||
}
|
||||
|
||||
/// Draw colour bitmap glyph `image` through `xf` (its pixels → document space), its pixels
|
||||
/// decoded once and kept with the images' pixels.
|
||||
fn draw_glyph_image(&mut self, ctx: &mut RenderContext, f: &Frame, image: &vectorcraft_text::GlyphImage, xf: Affine) {
|
||||
@@ -2233,14 +2249,17 @@ fn single_plain_fill(n: &Node) -> bool {
|
||||
matches!((painted.next(), painted.next()), (Some(AppearanceItem::Fill(f)), None) if f.blend == vectorcraft_color::BlendMode::Normal && f.opacity >= 1.0 && !matches!(f.paint, vectorcraft_color::Paint::Pattern { .. }))
|
||||
}
|
||||
|
||||
/// Number of visible painted fill/stroke items (opacity folding is exact only for one).
|
||||
/// Number of visible painted fill/stroke items (opacity folding is exact only for one). A dashed
|
||||
/// stroke is one paint: its dashes are outlined into one path and filled once, so overlapping
|
||||
/// dashes don't darken where they overlap. A dashed brush stroke isn't: its pieces are drawn one
|
||||
/// by one.
|
||||
fn painted_items(n: &Node) -> usize {
|
||||
n.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.visible && !f.paint.is_none() && matches!(f.paint, vectorcraft_color::Paint::Solid { .. }),
|
||||
AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && matches!(s.paint, vectorcraft_color::Paint::Solid { .. }) && s.dash.is_none(),
|
||||
AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && matches!(s.paint, vectorcraft_color::Paint::Solid { .. }) && (s.dash.is_none() || s.brush.is_none()),
|
||||
})
|
||||
.count()
|
||||
.max(if n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !matches!(f.paint, vectorcraft_color::Paint::Solid { .. } | vectorcraft_color::Paint::None)) || matches!(i, AppearanceItem::Stroke(s) if s.visible && !matches!(s.paint, vectorcraft_color::Paint::Solid { .. } | vectorcraft_color::Paint::None))) { 2 } else { 0 })
|
||||
@@ -2373,6 +2392,8 @@ struct TextGeom {
|
||||
inlines: Vec<vectorcraft_text::InlineGlyph>,
|
||||
/// Colour bitmap glyphs: (run, image, its pixels → text space), in text order.
|
||||
images: Vec<(usize, Arc<vectorcraft_text::GlyphImage>, Affine)>,
|
||||
/// COLR colour glyphs: (run, their layers placed in text space), in text order.
|
||||
colours: Vec<(usize, Arc<Node>)>,
|
||||
}
|
||||
|
||||
impl TextGeom {
|
||||
@@ -2422,6 +2443,7 @@ impl TextGeom {
|
||||
+ self.spans.len() * size_of::<(usize, usize, usize)>()
|
||||
+ self.inlines.len() * size_of::<vectorcraft_text::InlineGlyph>()
|
||||
+ self.images.len() * size_of::<(usize, Arc<vectorcraft_text::GlyphImage>, Affine)>()
|
||||
+ self.colours.iter().map(|(_, art)| lru::node_bytes(art)).sum::<usize>()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2502,12 +2524,15 @@ fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeom {
|
||||
.collect();
|
||||
let (mut substituted_fonts, mut substituted_glyphs, mut alternate_candidates) = (BezPath::new(), BezPath::new(), vec![]);
|
||||
let plain = t.plain_text();
|
||||
let mut images = vec![];
|
||||
let (mut images, mut colours) = (vec![], vec![]);
|
||||
for g in &layout.glyphs {
|
||||
push(&mut all, g.run, &g.outline);
|
||||
if let Some((image, xf)) = g.placed_image() {
|
||||
images.push((g.run, image.clone(), xf));
|
||||
}
|
||||
if let Some(art) = g.placed_colour(Affine::IDENTITY) {
|
||||
colours.push((g.run, Arc::new(art)));
|
||||
}
|
||||
let Some(&(missing, face)) = faces.get(g.run) else { continue };
|
||||
let Some(line) = layout.lines.get(g.line) else { continue };
|
||||
let mut cell = Rect::new(g.origin.x, g.origin.y - line.ascent, g.origin.x + g.advance, g.origin.y + line.descent).to_path(0.1);
|
||||
@@ -2547,6 +2572,7 @@ fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeom {
|
||||
alternate_glyphs: std::sync::OnceLock::new(),
|
||||
inlines: layout.inlines,
|
||||
images,
|
||||
colours,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2620,6 +2646,8 @@ mod tests_clip;
|
||||
#[cfg(test)]
|
||||
mod tests_cmykblend;
|
||||
#[cfg(test)]
|
||||
mod tests_colrglyphs;
|
||||
#[cfg(test)]
|
||||
mod tests_container;
|
||||
#[cfg(test)]
|
||||
mod tests_dither;
|
||||
|
||||
@@ -956,3 +956,37 @@ fn zero_length_subpaths_draw_dots_with_their_cap() {
|
||||
let butt = dots(vectorcraft_doc::LineCap::Butt);
|
||||
assert_eq!(butt.pixels.iter().filter(|&&p| p != 255).count(), 0, "a butt cap draws no dot");
|
||||
}
|
||||
|
||||
/// #2788: a dashed solid stroke is one paint, so its object opacity folds into its colour instead
|
||||
/// of compositing a viewport-wide layer; the result matches the layered one, overlapping dashes
|
||||
/// included.
|
||||
#[test]
|
||||
fn dashed_stroke_opacity_folds_into_its_colour() {
|
||||
let dashed = |d: &mut Document, object: f32, stroke: f32| {
|
||||
let mut n = rect_node(d, Rect::new(20.0, 20.0, 80.0, 60.0), Paint::None, Paint::solid(Color::rgb(0.2, 0.4, 0.9)), 6.0);
|
||||
let st = n.appearance.stroke_mut().unwrap();
|
||||
st.dash = Some(vectorcraft_doc::Dash { pattern: vec![4.0, 1.0], ..Default::default() });
|
||||
st.cap = vectorcraft_doc::LineCap::Round;
|
||||
st.opacity = stroke;
|
||||
n.opacity = object;
|
||||
n
|
||||
};
|
||||
let doc = |object: f32, stroke: f32| {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let n = dashed(&mut d, object, stroke);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
d
|
||||
};
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
assert_eq!(painted_items(&dashed(&mut d, 0.6, 1.0)), 1, "a dashed stroke takes the folded fast path");
|
||||
let mut brushed = dashed(&mut d, 0.6, 1.0);
|
||||
brushed.appearance.stroke_mut().unwrap().brush = Some("Calligraphic".into());
|
||||
assert_ne!(painted_items(&brushed), 1, "a dashed brush stroke draws its pieces one by one: no folding");
|
||||
let folded = render(&doc(0.6, 1.0));
|
||||
let layered = render(&doc(1.0, 0.6));
|
||||
assert_ne!(folded.pixel(20, 40), [255, 255, 255, 255], "the stroke is drawn");
|
||||
for (a, b) in folded.pixels.chunks(4).zip(layered.pixels.chunks(4)) {
|
||||
assert!(a.iter().zip(b).all(|(x, y)| (*x as i32 - *y as i32).abs() <= 1), "folded {a:?} vs layered {b:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! COLR colour glyphs: drawn as their layers (or, for paints documents have no form for, their
|
||||
//! image), which the type's fill doesn't paint, except in the layers in the foreground colour.
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_text::test_fonts::{COLOUR_CHAR, COLR_SWEEP_CHAR, colr_family, colr_font};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// 100 pt `text` in the COLR test font (v1 or v0), filled magenta, its baseline at (20, 120)
|
||||
/// turned by `turn` about there, on a white 160×160 page.
|
||||
fn render(v1: bool, text: char, turn: f64, opts: RenderOptions) -> Rendered {
|
||||
let _adding = crate::tests_fontchange::adding_fonts();
|
||||
vectorcraft_text::FontDb::global().add_font(colr_font(v1).unwrap());
|
||||
let mut d = Document::new(160.0, 160.0);
|
||||
let st = CharStyle { font_family: colr_family(v1).into(), size: 100.0, fill: Paint::solid(Color::rgb(1.0, 0.0, 1.0)), ..Default::default() };
|
||||
let mut t = TextObject::point(Point::new(20.0, 120.0), &text.to_string(), st);
|
||||
t.xf = Affine::rotate_about(turn, (20.0, 120.0)) * t.xf;
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
Renderer::new().render(&d, 160, 160, Affine::IDENTITY, &RenderOptions { background: Some([255, 255, 255, 255]), ..opts })
|
||||
}
|
||||
|
||||
/// The box of the pixels `like` says yes to.
|
||||
fn ink(img: &Rendered, like: impl Fn([u8; 4]) -> bool) -> Option<(u32, u32, u32, u32)> {
|
||||
let mut b: Option<(u32, u32, u32, u32)> = None;
|
||||
for y in 0..img.height {
|
||||
for x in 0..img.width {
|
||||
if like(img.pixel(x, y)) {
|
||||
b = Some(b.map_or((x, y, x, y), |(x0, y0, x1, y1)| (x0.min(x), y0.min(y), x1.max(x), y1.max(y))));
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn magenta(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[2] > 200 && p[1] < 60
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colr_layers_draw_their_colours_not_the_fill() {
|
||||
let img = render(true, COLOUR_CHAR, 0.0, RenderOptions::default());
|
||||
// The `O` with its linear gradient red → blue from x 0 to 500 units (20 to 70 pt).
|
||||
let reddish = ink(&img, |p| p[0] > 180 && p[2] < 90 && p[1] < 60).expect("red at the gradient's start");
|
||||
let bluish = ink(&img, |p| p[2] > 180 && p[0] < 90 && p[1] < 60).expect("blue at its end");
|
||||
assert!(reddish.0 < bluish.0, "red left of blue: {reddish:?} {bluish:?}");
|
||||
assert!(ink(&img, magenta).is_none(), "the fill doesn't paint the glyph");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_foreground_layer_takes_the_fill() {
|
||||
let img = render(false, COLOUR_CHAR, 0.0, RenderOptions::default());
|
||||
assert!(ink(&img, magenta).is_some(), "the `I` layer is in the foreground colour");
|
||||
assert!(ink(&img, |p| p == [255, 0, 0, 255]).is_some(), "the `O` layer in red");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_type_turns_its_colour_layers() {
|
||||
let size = |turn| {
|
||||
let (x0, y0, x1, y1) = ink(&render(false, COLOUR_CHAR, turn, RenderOptions::default()), magenta).unwrap();
|
||||
(x1 - x0, y1 - y0)
|
||||
};
|
||||
let (w, h) = size(0.0);
|
||||
assert!(h > w * 3, "the `I` stands: {w}×{h}");
|
||||
let (w, h) = size(std::f64::consts::FRAC_PI_2);
|
||||
assert!(w > h * 3, "turned, it lies: {w}×{h}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_mode_shows_the_layers_outlines() {
|
||||
let filled = render(false, COLOUR_CHAR, 0.0, RenderOptions::default());
|
||||
let outlined = render(false, COLOUR_CHAR, 0.0, RenderOptions { outline: true, ..Default::default() });
|
||||
let (x0, y0, x1, y1) = ink(&filled, |p| p == [255, 0, 0, 255]).unwrap();
|
||||
let dark = |p: [u8; 4]| p[0] < 128 && p[1] < 128 && p[2] < 128;
|
||||
assert!(ink(&outlined, |p| p == [255, 0, 0, 255]).is_none(), "no colours in outline mode");
|
||||
let (ox0, oy0, ox1, oy1) = ink(&outlined, dark).expect("the outlines show");
|
||||
assert!(ox0 <= x0 + 2 && oy0 <= y0 + 2 && ox1 + 2 >= x1 && oy1 + 2 >= y1, "around the layers: {:?} {:?}", (ox0, oy0, ox1, oy1), (x0, y0, x1, y1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sweep_glyph_draws_its_image() {
|
||||
let img = render(true, COLR_SWEEP_CHAR, 0.0, RenderOptions::default());
|
||||
assert!(ink(&img, |p| p[0] > 180 && p[1] < 60 && p[2] < 120).is_some(), "red where the sweep starts");
|
||||
assert!(ink(&img, magenta).is_none());
|
||||
}
|
||||
@@ -1910,6 +1910,10 @@ impl Writer<'_> {
|
||||
xml_escape(&href)
|
||||
));
|
||||
}
|
||||
// COLR glyphs: their layers, as art.
|
||||
for art in lay.glyphs.iter().filter_map(|g| g.placed_colour(Affine::IDENTITY)) {
|
||||
self.node(&art);
|
||||
}
|
||||
self.xf = saved;
|
||||
self.depth -= 1;
|
||||
self.line("</g>");
|
||||
@@ -2103,8 +2107,9 @@ impl Writer<'_> {
|
||||
let mut face: Option<Arc<FontFace>> = None;
|
||||
for g in &lay.glyphs {
|
||||
let Some(st) = t.runs.get(g.run).map(|r| &r.style) else { continue };
|
||||
// A colour bitmap font's subset would hold no bitmaps: its emoji are left to the viewer.
|
||||
if g.image.is_some() {
|
||||
// A colour font's subset would hold no bitmaps or COLR layers: its emoji are left to the
|
||||
// viewer.
|
||||
if g.image.is_some() || g.colour.is_some() {
|
||||
self.warn("colour emoji fonts are not embedded: viewers show emoji in their own fonts");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -42,3 +42,43 @@ fn embedded_fonts_leave_bitmap_glyphs_to_the_viewer() {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("emoji")), "{:?}", out.warnings);
|
||||
assert!(out.svg.contains(&format!("{COLOUR_CHAR}F")), "the character stays text");
|
||||
}
|
||||
|
||||
/// `ch` in the COLR test font (v1 or v0), 24 pt, filled blue.
|
||||
fn colr_doc(v1: bool, ch: char) -> Document {
|
||||
use vectorcraft_text::test_fonts::{colr_family, colr_font};
|
||||
vectorcraft_text::FontDb::global().add_font(colr_font(v1).unwrap());
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb8(0, 0, 255));
|
||||
let st = CharStyle { font_family: colr_family(v1).into(), size: 24.0, fill, ..CharStyle::default() };
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 50.0), &ch.to_string(), st))));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlined_text_writes_colr_glyphs_as_vector_art() {
|
||||
let svg = export_full(&colr_doc(true, COLOUR_CHAR), &ExportOptions { outline_text: true, ..Default::default() }, None).svg;
|
||||
assert!(!svg.contains("<image "), "{svg}");
|
||||
assert!(svg.contains("<linearGradient") && svg.contains("<radialGradient"), "{svg}");
|
||||
assert!(svg.contains("<clipPath"), "the clip box: {svg}");
|
||||
assert!(svg.contains("mix-blend-mode:multiply") || svg.contains("mix-blend-mode: multiply"), "{svg}");
|
||||
let v0 = export_full(&colr_doc(false, COLOUR_CHAR), &ExportOptions { outline_text: true, ..Default::default() }, None).svg;
|
||||
assert!(v0.contains("#f00") || v0.contains("#ff0000"), "the red layer: {v0}");
|
||||
assert!(v0.contains("#00f") || v0.contains("#0000ff"), "the foreground layer in the fill: {v0}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlined_text_writes_a_sweep_glyph_as_its_image() {
|
||||
use vectorcraft_text::test_fonts::COLR_SWEEP_CHAR;
|
||||
let svg = export_full(&colr_doc(true, COLR_SWEEP_CHAR), &ExportOptions { outline_text: true, ..Default::default() }, None).svg;
|
||||
assert_eq!(svg.matches("<image ").count(), 1, "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_fonts_leave_colr_glyphs_to_the_viewer() {
|
||||
let out = export_full(&colr_doc(false, COLOUR_CHAR), &ExportOptions { embed_fonts: true, ..Default::default() }, None);
|
||||
assert!(!out.svg.contains("base64,"), "no subset without its colour layers: {}", out.svg);
|
||||
assert!(out.warnings.iter().any(|w| w.contains("emoji")), "{:?}", out.warnings);
|
||||
assert!(out.svg.contains(COLOUR_CHAR), "the character stays text");
|
||||
}
|
||||
@@ -28,6 +28,9 @@ icu_segmenter = "2.3"
|
||||
# Grapheme clusters (a Thai consonant with its vowel and tone marks, an accented letter, an emoji
|
||||
# sequence) for caret movement; MIT OR Apache-2.0, already in the build.
|
||||
unicode-segmentation = "1.13"
|
||||
# Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing
|
||||
# modes) into images: the canvas's renderer, already in the build.
|
||||
vello_cpu = { workspace = true }
|
||||
# Builds a small variable font for tests (`test_fonts`; no font file is committed). MIT OR
|
||||
# Apache-2.0, already in the build through subsetter.
|
||||
write-fonts = { version = "0.48", optional = true }
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
//! COLR colour glyphs (v0 layers, v1 paint graphs): read into a tree of document nodes in font
|
||||
//! units (y down, as outlines are), which the renderer, the exporters and Create Outlines draw and
|
||||
//! keep as they do any art. A glyph whose paints VectorCraft has no form for is drawn into an image
|
||||
//! instead, as bitmap glyphs are ([`GlyphImage`]); [`Tree::unsupported`] names what made it one.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
|
||||
use skrifa::color::{Brush, ColorGlyph, ColorGlyphCollection, ColorPainter, ColorPalettes, ColorStop, CompositeMode, Extend, Transform};
|
||||
use skrifa::instance::{LocationRef, Size};
|
||||
use skrifa::outline::DrawSettings;
|
||||
use skrifa::raw::TableProvider;
|
||||
use skrifa::raw::types::BoundingBox;
|
||||
use skrifa::{GlyphId, MetadataProvider};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, FillLayer, ImageBlob, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vello_cpu::peniko;
|
||||
|
||||
use crate::GlyphImage;
|
||||
use crate::fontdb::FlipPen;
|
||||
|
||||
/// The most nodes a colour glyph's tree may have: past it, a font's glyph draws its outline.
|
||||
const MAX_COLR_NODES: usize = 4096;
|
||||
/// The deepest the groups of a colour glyph may nest.
|
||||
const MAX_COLR_DEPTH: usize = 64;
|
||||
/// The pixels per em an image of a colour glyph is drawn at.
|
||||
const FALLBACK_PPEM: f64 = 256.0;
|
||||
/// The largest side of such an image, in pixels.
|
||||
const MAX_FALLBACK_SIDE: f64 = 1024.0;
|
||||
/// The id of the layers' nodes: none, as the art exporters make on the fly has (Create Outlines
|
||||
/// gives them ids of the document's).
|
||||
const NO_ID: NodeId = NodeId(u64::MAX);
|
||||
/// Font units y up → y down.
|
||||
const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
|
||||
|
||||
/// A colour glyph as VectorCraft draws it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum ColourContent {
|
||||
/// Its layers as document nodes in font units (y down): a group.
|
||||
Art(Arc<Node>),
|
||||
/// Its picture, for paints VectorCraft has no form for.
|
||||
Image(Arc<GlyphImage>),
|
||||
}
|
||||
|
||||
/// Does `font` have COLR colour glyphs?
|
||||
pub(crate) fn has_colour_layers(font: &skrifa::FontRef<'_>) -> bool {
|
||||
font.colr().is_ok()
|
||||
}
|
||||
|
||||
/// Glyph `gid`'s colour content in `font` at `location`, palette 0's colours and `foreground` for
|
||||
/// palette index 0xFFFF, and whether it used `foreground`; `None` when it isn't a colour glyph, or
|
||||
/// its graph doesn't read (a cycle, too deep, too many layers).
|
||||
pub(crate) fn colour_glyph(
|
||||
font: &skrifa::FontRef<'_>,
|
||||
location: LocationRef<'_>,
|
||||
upem: f64,
|
||||
gid: u32,
|
||||
foreground: Color,
|
||||
) -> (Option<ColourContent>, bool) {
|
||||
let Some(glyph) = ColorGlyphCollection::new(font).get(GlyphId::new(gid)) else { return (None, false) };
|
||||
let mut tree = Tree::new(font, location, foreground);
|
||||
if glyph.paint(location, &mut tree).is_err() {
|
||||
return (None, false);
|
||||
}
|
||||
let used = tree.foreground_used;
|
||||
if tree.unsupported.is_some() {
|
||||
// What it paints, y up, for a glyph without a clip box.
|
||||
let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b));
|
||||
return (raster(&glyph, font, location, upem, foreground, painted).map(|i| ColourContent::Image(Arc::new(i))), used);
|
||||
}
|
||||
(tree.finish().map(ColourContent::Art), used)
|
||||
}
|
||||
|
||||
/// Palette 0's colours with their alpha.
|
||||
fn palette(font: &skrifa::FontRef<'_>) -> Vec<(Color, f32)> {
|
||||
let palettes = ColorPalettes::new(font);
|
||||
let Some(palette) = palettes.get(0) else { return vec![] };
|
||||
palette.colors().iter().map(|c| (Color::rgb8(c.red, c.green, c.blue), f32::from(c.alpha) / 255.0)).collect()
|
||||
}
|
||||
|
||||
/// The colour and alpha of palette entry `index` (0xFFFF: `foreground`), times `alpha`; `None`
|
||||
/// for an entry the palette doesn't have.
|
||||
fn colour(palette: &[(Color, f32)], foreground: Color, index: u16, alpha: f32) -> Option<(Color, f32)> {
|
||||
let (c, a) = if index == 0xFFFF { (foreground, 1.0) } else { *palette.get(usize::from(index))? };
|
||||
Some((c, (a * alpha).clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
fn affine(t: &Transform) -> Affine {
|
||||
Affine::new([t.xx, t.yx, t.xy, t.yy, t.dx, t.dy].map(f64::from))
|
||||
}
|
||||
|
||||
fn point(p: skrifa::raw::types::Point<f32>) -> Point {
|
||||
Point::new(f64::from(p.x), f64::from(p.y))
|
||||
}
|
||||
|
||||
fn box_path(b: &BoundingBox<f32>) -> BezPath {
|
||||
Rect::new(f64::from(b.x_min), f64::from(b.y_min), f64::from(b.x_max), f64::from(b.y_max)).to_path(0.1)
|
||||
}
|
||||
|
||||
/// Glyph `gid`'s outline in font units, y up (the font database's pen draws y down, as text
|
||||
/// space has it).
|
||||
fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId) -> BezPath {
|
||||
let mut pen = FlipPen(BezPath::new());
|
||||
if let Some(g) = font.outline_glyphs().get(gid) {
|
||||
let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen);
|
||||
}
|
||||
let mut path = pen.0;
|
||||
path.apply_affine(FLIP);
|
||||
path
|
||||
}
|
||||
|
||||
/// A group being built: its clipping path, or the blend mode of a composite's layer.
|
||||
struct Open {
|
||||
clip: Option<BezPath>,
|
||||
blend: Option<BlendMode>,
|
||||
children: Vec<Arc<Node>>,
|
||||
/// A fill filled the clip's whole area: alone, it is the clip filled.
|
||||
flooded: bool,
|
||||
}
|
||||
|
||||
/// A [`ColorPainter`] building a colour glyph's tree.
|
||||
struct Tree<'a> {
|
||||
font: &'a skrifa::FontRef<'a>,
|
||||
location: LocationRef<'a>,
|
||||
palette: Vec<(Color, f32)>,
|
||||
foreground: Color,
|
||||
/// Font units y up → the tree's space (y down), with the paint graph's transforms.
|
||||
transforms: Vec<Affine>,
|
||||
groups: Vec<Open>,
|
||||
nodes: usize,
|
||||
/// What VectorCraft has no form for, the first one met: the glyph becomes an image.
|
||||
unsupported: Option<&'static str>,
|
||||
/// The graph is past [`MAX_COLR_NODES`] or [`MAX_COLR_DEPTH`].
|
||||
too_large: bool,
|
||||
/// The box of what it paints, in the tree's space.
|
||||
painted: Option<Rect>,
|
||||
/// It paints with the foreground colour (palette index 0xFFFF).
|
||||
foreground_used: bool,
|
||||
}
|
||||
|
||||
impl<'a> Tree<'a> {
|
||||
fn new(font: &'a skrifa::FontRef<'a>, location: LocationRef<'a>, foreground: Color) -> Self {
|
||||
let root = Open { clip: None, blend: Some(BlendMode::Normal), children: vec![], flooded: false };
|
||||
Tree {
|
||||
font,
|
||||
location,
|
||||
palette: palette(font),
|
||||
foreground,
|
||||
transforms: vec![FLIP],
|
||||
groups: vec![root],
|
||||
nodes: 0,
|
||||
unsupported: None,
|
||||
too_large: false,
|
||||
painted: None,
|
||||
foreground_used: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn transform(&self) -> Affine {
|
||||
self.transforms.last().copied().unwrap_or(FLIP)
|
||||
}
|
||||
|
||||
fn add(&mut self, node: Node) {
|
||||
self.nodes += 1;
|
||||
self.too_large |= self.nodes > MAX_COLR_NODES;
|
||||
if let Some(g) = self.groups.last_mut().filter(|_| !self.too_large) {
|
||||
g.children.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
|
||||
fn open(&mut self, group: Open) {
|
||||
self.too_large |= self.groups.len() >= MAX_COLR_DEPTH;
|
||||
self.groups.push(group);
|
||||
}
|
||||
|
||||
/// Closes the innermost group into its parent: a clip with only the fill it clips is that
|
||||
/// filled path; an empty group goes.
|
||||
fn close(&mut self) {
|
||||
// The root stays open until `finish`.
|
||||
if self.groups.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let Some(g) = self.groups.pop() else { return };
|
||||
if g.children.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut children = g.children;
|
||||
if let Some(clip) = g.clip {
|
||||
if let ([only], true) = (children.as_slice(), g.flooded) {
|
||||
let only = only.clone();
|
||||
return self.add_arc(only);
|
||||
}
|
||||
let mut path = Node::path(NO_ID, PathData::from_bezpath(&clip), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut path.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
children.insert(0, Arc::new(path));
|
||||
let mut group = Node::group(NO_ID, children);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
return self.add(group);
|
||||
}
|
||||
let mut group = Node::group(NO_ID, children);
|
||||
group.isolate = true;
|
||||
group.blend = g.blend.unwrap_or(BlendMode::Normal);
|
||||
self.add(group);
|
||||
}
|
||||
|
||||
fn add_arc(&mut self, node: Arc<Node>) {
|
||||
if let Some(g) = self.groups.last_mut() {
|
||||
g.children.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
/// The tree: the glyph as a group. It needs no isolation of its own: blend modes only come
|
||||
/// with composites, whose groups are isolated, so they never reach the art behind the type.
|
||||
fn finish(mut self) -> Option<Arc<Node>> {
|
||||
if self.too_large {
|
||||
return None;
|
||||
}
|
||||
while self.groups.len() > 1 {
|
||||
self.close();
|
||||
}
|
||||
let root = self.groups.pop()?;
|
||||
if root.children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Arc::new(Node::group(NO_ID, root.children)))
|
||||
}
|
||||
|
||||
/// `brush` as a VectorCraft paint and opacity, in the tree's space; `None` with
|
||||
/// [`Self::unsupported`] set when it has no form there.
|
||||
fn paint(&mut self, brush: &Brush<'_>) -> Option<(Paint, f32)> {
|
||||
self.foreground_used |= match brush {
|
||||
Brush::Solid { palette_index, .. } => *palette_index == 0xFFFF,
|
||||
Brush::LinearGradient { color_stops, .. } | Brush::RadialGradient { color_stops, .. } | Brush::SweepGradient { color_stops, .. } => {
|
||||
color_stops.iter().any(|s| s.palette_index == 0xFFFF)
|
||||
}
|
||||
};
|
||||
let xf = self.transform();
|
||||
let stops = |stops: &[ColorStop], tree: &Self| -> Vec<GradientStop> {
|
||||
stops
|
||||
.iter()
|
||||
.filter_map(|s| {
|
||||
let (color, opacity) = colour(&tree.palette, tree.foreground, s.palette_index, s.alpha)?;
|
||||
Some(GradientStop { opacity, ..GradientStop::new(s.offset, color) })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let gradient = |kind, stops: Vec<GradientStop>, geom| {
|
||||
let mut paint = GradientPaint::new(Gradient { kind, stops, ..Gradient::default() });
|
||||
paint.geom = Some(geom);
|
||||
Paint::Gradient(Box::new(paint))
|
||||
};
|
||||
match brush {
|
||||
Brush::Solid { palette_index, alpha } => {
|
||||
let (c, a) = colour(&self.palette, self.foreground, *palette_index, *alpha)?;
|
||||
Some((Paint::solid(c), a))
|
||||
}
|
||||
Brush::LinearGradient { p0, p1, color_stops, extend } => {
|
||||
if *extend != Extend::Pad {
|
||||
self.unsupported.get_or_insert("a repeating or reflecting gradient");
|
||||
return None;
|
||||
}
|
||||
let (p0, p1) = (point(*p0), point(*p1));
|
||||
let (stops, first, last) = normalized(stops(color_stops, self))?;
|
||||
// Stops past 0 and 1 move the ends instead.
|
||||
let mut geom = GradientGeom { start: p0.lerp(p1, f64::from(first)), end: p0.lerp(p1, f64::from(last)), aspect: 1.0, focal: None };
|
||||
geom.transform(xf, GradientKind::Linear);
|
||||
Some((gradient(GradientKind::Linear, stops, geom), 1.0))
|
||||
}
|
||||
Brush::RadialGradient { c0, r0, c1, r1, color_stops, extend } => {
|
||||
if *extend != Extend::Pad {
|
||||
self.unsupported.get_or_insert("a repeating or reflecting gradient");
|
||||
return None;
|
||||
}
|
||||
let (c0, c1, r0, r1) = (point(*c0), point(*c1), f64::from(*r0), f64::from(*r1));
|
||||
let concentric = (c0 - c1).hypot() < 1e-6;
|
||||
if (r0 > 1e-6 && !concentric) || r1 <= r0 || (c0 - c1).hypot() >= r1 {
|
||||
self.unsupported.get_or_insert("a radial gradient from a circle");
|
||||
return None;
|
||||
}
|
||||
let mut stops = stops(color_stops, self);
|
||||
if stops.iter().any(|s| !(0.0..=1.0).contains(&s.offset)) {
|
||||
self.unsupported.get_or_insert("a radial gradient with stops past its circles");
|
||||
return None;
|
||||
}
|
||||
// A start circle around the centre starts the stops further out.
|
||||
for s in &mut stops {
|
||||
s.offset = ((r0 + f64::from(s.offset) * (r1 - r0)) / r1) as f32;
|
||||
}
|
||||
let mut geom = GradientGeom { start: c1, end: c1 + Vec2::new(r1, 0.0), aspect: 1.0, focal: (!concentric).then_some(c0) };
|
||||
geom.transform(xf, GradientKind::Radial);
|
||||
Some((gradient(GradientKind::Radial, stops, geom), 1.0))
|
||||
}
|
||||
Brush::SweepGradient { .. } => {
|
||||
self.unsupported.get_or_insert("a sweep gradient");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` (in the tree's space) filled with `brush` (in the current transform's).
|
||||
fn fill_path(&mut self, path: &BezPath, brush: &Brush<'_>) {
|
||||
let b = path.bounding_box();
|
||||
self.painted = Some(self.painted.map_or(b, |p| p.union(b)));
|
||||
let Some((paint, opacity)) = self.paint(brush) else { return };
|
||||
let fill = vectorcraft_doc::AppearanceItem::Fill(FillLayer { opacity, ..FillLayer::new(paint) });
|
||||
self.add(Node::path(NO_ID, PathData::from_bezpath(path), Appearance { items: vec![fill], ..Appearance::default() }));
|
||||
}
|
||||
}
|
||||
|
||||
/// `stops` sorted, from 0 to 1 (as the gradient's ends then move), and where the first and last
|
||||
/// were; `None` without stops.
|
||||
fn normalized(mut stops: Vec<GradientStop>) -> Option<(Vec<GradientStop>, f32, f32)> {
|
||||
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
let (first, last) = (stops.first()?.offset, stops.last()?.offset);
|
||||
let span = last - first;
|
||||
for s in &mut stops {
|
||||
s.offset = if span > 0.0 { (s.offset - first) / span } else { 0.0 };
|
||||
}
|
||||
Some((stops, first, if span > 0.0 { last } else { first + 1.0 }))
|
||||
}
|
||||
|
||||
impl ColorPainter for Tree<'_> {
|
||||
fn push_transform(&mut self, transform: Transform) {
|
||||
let t = self.transform() * affine(&transform);
|
||||
self.transforms.push(t);
|
||||
}
|
||||
|
||||
fn pop_transform(&mut self) {
|
||||
if self.transforms.len() > 1 {
|
||||
self.transforms.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn push_clip_glyph(&mut self, glyph_id: GlyphId) {
|
||||
let mut clip = outline(self.font, self.location, glyph_id);
|
||||
clip.apply_affine(self.transform());
|
||||
self.open(Open { clip: Some(clip), blend: None, children: vec![], flooded: false });
|
||||
}
|
||||
|
||||
fn push_clip_box(&mut self, clip_box: BoundingBox<f32>) {
|
||||
let mut clip = box_path(&clip_box);
|
||||
clip.apply_affine(self.transform());
|
||||
self.open(Open { clip: Some(clip), blend: None, children: vec![], flooded: false });
|
||||
}
|
||||
|
||||
fn pop_clip(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
|
||||
/// A fill fills the innermost clip's shape (a layer between them stays around it).
|
||||
fn fill(&mut self, brush: Brush<'_>) {
|
||||
let Some(at) = self.groups.iter().rposition(|g| g.clip.is_some()) else {
|
||||
self.unsupported.get_or_insert("a fill outside any glyph");
|
||||
return;
|
||||
};
|
||||
let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return };
|
||||
if at + 1 == self.groups.len()
|
||||
&& let Some(g) = self.groups.last_mut()
|
||||
{
|
||||
g.flooded = g.children.is_empty();
|
||||
}
|
||||
self.fill_path(&clip, &brush);
|
||||
}
|
||||
|
||||
/// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays).
|
||||
fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option<Transform>, brush: Brush<'_>) {
|
||||
let mut path = outline(self.font, self.location, glyph_id);
|
||||
path.apply_affine(self.transform());
|
||||
let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine);
|
||||
self.transforms.push(brush_xf);
|
||||
self.fill_path(&path, &brush);
|
||||
self.transforms.pop();
|
||||
}
|
||||
|
||||
fn push_layer(&mut self, mode: CompositeMode) {
|
||||
let blend = blend_mode(mode);
|
||||
if blend.is_none() {
|
||||
self.unsupported.get_or_insert("a compositing mode other than blending");
|
||||
}
|
||||
self.open(Open { clip: None, blend, children: vec![], flooded: false });
|
||||
}
|
||||
|
||||
fn pop_layer(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// COLRv1's blend composite modes as VectorCraft's (`SrcOver` is Normal); `None` for the
|
||||
/// Porter-Duff modes, which it has no form for.
|
||||
fn blend_mode(mode: CompositeMode) -> Option<BlendMode> {
|
||||
Some(match mode {
|
||||
CompositeMode::SrcOver => BlendMode::Normal,
|
||||
CompositeMode::Screen => BlendMode::Screen,
|
||||
CompositeMode::Overlay => BlendMode::Overlay,
|
||||
CompositeMode::Darken => BlendMode::Darken,
|
||||
CompositeMode::Lighten => BlendMode::Lighten,
|
||||
CompositeMode::ColorDodge => BlendMode::ColorDodge,
|
||||
CompositeMode::ColorBurn => BlendMode::ColorBurn,
|
||||
CompositeMode::HardLight => BlendMode::HardLight,
|
||||
CompositeMode::SoftLight => BlendMode::SoftLight,
|
||||
CompositeMode::Difference => BlendMode::Difference,
|
||||
CompositeMode::Exclusion => BlendMode::Exclusion,
|
||||
CompositeMode::Multiply => BlendMode::Multiply,
|
||||
CompositeMode::HslHue => BlendMode::Hue,
|
||||
CompositeMode::HslSaturation => BlendMode::Saturation,
|
||||
CompositeMode::HslColor => BlendMode::Color,
|
||||
CompositeMode::HslLuminosity => BlendMode::Luminosity,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Colour glyph `glyph` drawn into an image at [`FALLBACK_PPEM`], placed in font units (y down)
|
||||
/// as bitmap glyphs are, in its clip box or else the box of what it `painted` (y up); `None` when
|
||||
/// it paints nothing or doesn't draw.
|
||||
fn raster(
|
||||
glyph: &ColorGlyph<'_>,
|
||||
font: &skrifa::FontRef<'_>,
|
||||
location: LocationRef<'_>,
|
||||
upem: f64,
|
||||
foreground: Color,
|
||||
painted: Option<Rect>,
|
||||
) -> Option<GlyphImage> {
|
||||
let b = glyph.bounding_box(location, Size::unscaled()).map(|b| Rect::new(b.x_min.into(), b.y_min.into(), b.x_max.into(), b.y_max.into()));
|
||||
// Without a clip box, the box of what it paints (`painted`, y up).
|
||||
let b = b.or(painted).filter(|b| b.area() > 0.0)?;
|
||||
let s = (FALLBACK_PPEM / upem.max(1.0)).min(MAX_FALLBACK_SIDE / b.width().max(b.height()));
|
||||
if !(s.is_finite() && s > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = ((b.width() * s).ceil() as u16, (b.height() * s).ceil() as u16);
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
// Font units y up → pixels.
|
||||
let to_pixels = Affine::new([s, 0.0, 0.0, -s, -b.x0 * s, b.y1 * s]);
|
||||
let mut ctx = vello_cpu::RenderContext::new(w, h);
|
||||
let mut painter = Pixels { ctx: &mut ctx, font, location, palette: palette(font), foreground, transforms: vec![to_pixels], width: w, height: h };
|
||||
glyph.paint(location, &mut painter).ok()?;
|
||||
ctx.flush();
|
||||
let mut pm = vello_cpu::Pixmap::new(w, h);
|
||||
ctx.render(&mut pm, &mut vello_cpu::Resources::new());
|
||||
let png = pm.into_png().ok()?;
|
||||
let xf = Affine::new([1.0 / s, 0.0, 0.0, 1.0 / s, b.x0, -b.y1]);
|
||||
Some(GlyphImage { blob: ImageBlob::png(png), width: u32::from(w), height: u32::from(h), xf })
|
||||
}
|
||||
|
||||
/// A [`ColorPainter`] drawing a colour glyph with vello_cpu.
|
||||
struct Pixels<'a, 'c> {
|
||||
ctx: &'c mut vello_cpu::RenderContext,
|
||||
font: &'a skrifa::FontRef<'a>,
|
||||
location: LocationRef<'a>,
|
||||
palette: Vec<(Color, f32)>,
|
||||
foreground: Color,
|
||||
transforms: Vec<Affine>,
|
||||
width: u16,
|
||||
height: u16,
|
||||
}
|
||||
|
||||
impl Pixels<'_, '_> {
|
||||
fn transform(&self) -> Affine {
|
||||
self.transforms.last().copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn peniko_colour(&self, index: u16, alpha: f32) -> peniko::Color {
|
||||
let (c, a) = colour(&self.palette, self.foreground, index, alpha).unwrap_or((Color::BLACK, 0.0));
|
||||
let [r, g, b, a] = c.to_rgba8(a);
|
||||
peniko::Color::from_rgba8(r, g, b, a)
|
||||
}
|
||||
|
||||
fn clip(&mut self, path: &BezPath) {
|
||||
self.ctx.set_transform(self.transform());
|
||||
self.ctx.push_clip_layer(path);
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorPainter for Pixels<'_, '_> {
|
||||
fn push_transform(&mut self, transform: Transform) {
|
||||
let t = self.transform() * affine(&transform);
|
||||
self.transforms.push(t);
|
||||
}
|
||||
|
||||
fn pop_transform(&mut self) {
|
||||
if self.transforms.len() > 1 {
|
||||
self.transforms.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn push_clip_glyph(&mut self, glyph_id: GlyphId) {
|
||||
let path = outline(self.font, self.location, glyph_id);
|
||||
self.clip(&path);
|
||||
}
|
||||
|
||||
fn push_clip_box(&mut self, clip_box: BoundingBox<f32>) {
|
||||
self.clip(&box_path(&clip_box));
|
||||
}
|
||||
|
||||
fn pop_clip(&mut self) {
|
||||
self.ctx.pop_layer();
|
||||
}
|
||||
|
||||
fn fill(&mut self, brush: Brush<'_>) {
|
||||
let stops = |stops: &[ColorStop]| -> Vec<peniko::ColorStop> {
|
||||
stops.iter().map(|s| peniko::ColorStop::from((s.offset, self.peniko_colour(s.palette_index, s.alpha)))).collect()
|
||||
};
|
||||
let extend = |e: Extend| match e {
|
||||
Extend::Repeat => peniko::Extend::Repeat,
|
||||
Extend::Reflect => peniko::Extend::Reflect,
|
||||
_ => peniko::Extend::Pad,
|
||||
};
|
||||
let paint: peniko::Brush = match brush {
|
||||
Brush::Solid { palette_index, alpha } => peniko::Brush::Solid(self.peniko_colour(palette_index, alpha)),
|
||||
Brush::LinearGradient { p0, p1, color_stops, extend: e } => {
|
||||
peniko::Gradient::new_linear(point(p0), point(p1)).with_stops(stops(color_stops).as_slice()).with_extend(extend(e)).into()
|
||||
}
|
||||
Brush::RadialGradient { c0, r0, c1, r1, color_stops, extend: e } => peniko::Gradient::new_two_point_radial(point(c0), r0, point(c1), r1)
|
||||
.with_stops(stops(color_stops).as_slice())
|
||||
.with_extend(extend(e))
|
||||
.into(),
|
||||
Brush::SweepGradient { c0, start_angle, end_angle, color_stops, extend: e } => {
|
||||
peniko::Gradient::new_sweep(point(c0), start_angle.to_radians(), end_angle.to_radians())
|
||||
.with_stops(stops(color_stops).as_slice())
|
||||
.with_extend(extend(e))
|
||||
.into()
|
||||
}
|
||||
};
|
||||
// Everything the image shows, in the paint's space.
|
||||
let xf = self.transform();
|
||||
let all = xf.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(self.width), f64::from(self.height)));
|
||||
self.ctx.set_transform(xf);
|
||||
match paint {
|
||||
peniko::Brush::Solid(c) => self.ctx.set_paint(c),
|
||||
peniko::Brush::Gradient(g) => self.ctx.set_paint(g),
|
||||
peniko::Brush::Image(_) => return,
|
||||
}
|
||||
self.ctx.fill_rect(&all);
|
||||
}
|
||||
|
||||
fn push_layer(&mut self, mode: CompositeMode) {
|
||||
use peniko::{BlendMode as Mode, Compose, Mix};
|
||||
let (mix, compose) = match mode {
|
||||
CompositeMode::Clear => (Mix::Normal, Compose::Clear),
|
||||
CompositeMode::Src => (Mix::Normal, Compose::Copy),
|
||||
CompositeMode::Dest => (Mix::Normal, Compose::Dest),
|
||||
CompositeMode::DestOver => (Mix::Normal, Compose::DestOver),
|
||||
CompositeMode::SrcIn => (Mix::Normal, Compose::SrcIn),
|
||||
CompositeMode::DestIn => (Mix::Normal, Compose::DestIn),
|
||||
CompositeMode::SrcOut => (Mix::Normal, Compose::SrcOut),
|
||||
CompositeMode::DestOut => (Mix::Normal, Compose::DestOut),
|
||||
CompositeMode::SrcAtop => (Mix::Normal, Compose::SrcAtop),
|
||||
CompositeMode::DestAtop => (Mix::Normal, Compose::DestAtop),
|
||||
CompositeMode::Xor => (Mix::Normal, Compose::Xor),
|
||||
CompositeMode::Plus => (Mix::Normal, Compose::Plus),
|
||||
CompositeMode::Screen => (Mix::Screen, Compose::SrcOver),
|
||||
CompositeMode::Overlay => (Mix::Overlay, Compose::SrcOver),
|
||||
CompositeMode::Darken => (Mix::Darken, Compose::SrcOver),
|
||||
CompositeMode::Lighten => (Mix::Lighten, Compose::SrcOver),
|
||||
CompositeMode::ColorDodge => (Mix::ColorDodge, Compose::SrcOver),
|
||||
CompositeMode::ColorBurn => (Mix::ColorBurn, Compose::SrcOver),
|
||||
CompositeMode::HardLight => (Mix::HardLight, Compose::SrcOver),
|
||||
CompositeMode::SoftLight => (Mix::SoftLight, Compose::SrcOver),
|
||||
CompositeMode::Difference => (Mix::Difference, Compose::SrcOver),
|
||||
CompositeMode::Exclusion => (Mix::Exclusion, Compose::SrcOver),
|
||||
CompositeMode::Multiply => (Mix::Multiply, Compose::SrcOver),
|
||||
CompositeMode::HslHue => (Mix::Hue, Compose::SrcOver),
|
||||
CompositeMode::HslSaturation => (Mix::Saturation, Compose::SrcOver),
|
||||
CompositeMode::HslColor => (Mix::Color, Compose::SrcOver),
|
||||
CompositeMode::HslLuminosity => (Mix::Luminosity, Compose::SrcOver),
|
||||
_ => (Mix::Normal, Compose::SrcOver),
|
||||
};
|
||||
self.ctx.push_layer(None, Some(Mode::new(mix, compose)), None, None, None);
|
||||
}
|
||||
|
||||
fn pop_layer(&mut self) {
|
||||
self.ctx.pop_layer();
|
||||
}
|
||||
}
|
||||
+84
-19
@@ -14,6 +14,8 @@ use skrifa::string::StringId;
|
||||
use skrifa::{GlyphId, MetadataProvider, Tag};
|
||||
|
||||
use crate::GlyphImage;
|
||||
use crate::colr::ColourContent;
|
||||
use vectorcraft_doc::color::Color;
|
||||
|
||||
/// The family used when a requested family is unknown (Illustrator's Myriad Pro analogue).
|
||||
pub const FALLBACK_FAMILY: &str = "Source Sans 3";
|
||||
@@ -136,6 +138,8 @@ pub struct FontFace {
|
||||
icf_margins: std::sync::OnceLock<IcfMargins>,
|
||||
/// Has `sbix` or `CBDT` strikes: colour bitmap glyphs ([`FontDb::glyph_image`]).
|
||||
colour_bitmaps: bool,
|
||||
/// Has `COLR` colour glyphs ([`FontDb::glyph_colour`]).
|
||||
colour_layers: bool,
|
||||
}
|
||||
|
||||
/// Where the ideographic character face (ICF) lies inside the ideographic em box: its distance
|
||||
@@ -414,28 +418,65 @@ type PostScriptNames = HashMap<String, (String, String)>;
|
||||
/// are neither a loaded nor an installed family.
|
||||
type CanonicalNames = HashMap<(String, String), (String, String)>;
|
||||
|
||||
/// The glyph images [`FontDb::glyph_image`] keeps by face and glyph, and their PNGs' bytes in all.
|
||||
#[derive(Default)]
|
||||
struct GlyphImages {
|
||||
images: HashMap<(u32, u32), Option<Arc<GlyphImage>>>,
|
||||
/// [`FontDb::glyph_image`]'s answers by face and glyph.
|
||||
type GlyphImages = GlyphCache<(u32, u32), Arc<GlyphImage>>;
|
||||
/// [`FontDb::glyph_colour`]'s answers by face and glyph, and the foreground colour for glyphs that
|
||||
/// paint with it.
|
||||
type GlyphColours = GlyphCache<(u32, u32, Option<[u8; 4]>), ColourContent>;
|
||||
|
||||
/// What a glyph's colour content (an image, layers) takes of memory, in bytes.
|
||||
trait Weight {
|
||||
fn bytes(&self) -> usize;
|
||||
}
|
||||
|
||||
impl Weight for Arc<GlyphImage> {
|
||||
fn bytes(&self) -> usize {
|
||||
self.blob.bytes.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl Weight for ColourContent {
|
||||
fn bytes(&self) -> usize {
|
||||
match self {
|
||||
ColourContent::Image(i) => i.bytes(),
|
||||
// Roughly what a path node with its outline and fill takes.
|
||||
ColourContent::Art(art) => {
|
||||
let mut nodes = 0;
|
||||
art.walk(&mut |_| nodes += 1);
|
||||
nodes * 512
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour content of glyphs ([`FontDb::glyph_image`], [`FontDb::glyph_colour`]) kept by
|
||||
/// face, glyph and what else it depends on, and its bytes in all.
|
||||
struct GlyphCache<K, V> {
|
||||
kept: HashMap<K, Option<V>>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl GlyphImages {
|
||||
/// Keeps `image` (or that there is none), first letting go of all it keeps when that would
|
||||
/// take more than [`IMAGE_CACHE_MAX`] images or [`IMAGE_CACHE_BYTES`]. A glyph it keeps
|
||||
impl<K, V> Default for GlyphCache<K, V> {
|
||||
fn default() -> Self {
|
||||
Self { kept: HashMap::new(), bytes: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: std::hash::Hash + Eq, V: Weight> GlyphCache<K, V> {
|
||||
/// Keeps `value` (or that there is none), first letting go of all it keeps when that would
|
||||
/// take more than [`IMAGE_CACHE_MAX`] glyphs or [`IMAGE_CACHE_BYTES`]. A glyph it keeps
|
||||
/// already, which another thread looked up meanwhile, stays as it is.
|
||||
fn keep(&mut self, key: (u32, u32), image: Option<Arc<GlyphImage>>) {
|
||||
if self.images.contains_key(&key) {
|
||||
fn keep(&mut self, key: K, value: Option<V>) {
|
||||
if self.kept.contains_key(&key) {
|
||||
return;
|
||||
}
|
||||
let bytes = image.as_ref().map_or(0, |i| i.blob.bytes.len());
|
||||
if self.images.len() >= IMAGE_CACHE_MAX || self.bytes.saturating_add(bytes) > IMAGE_CACHE_BYTES {
|
||||
self.images.clear();
|
||||
let bytes = value.as_ref().map_or(0, Weight::bytes);
|
||||
if self.kept.len() >= IMAGE_CACHE_MAX || self.bytes.saturating_add(bytes) > IMAGE_CACHE_BYTES {
|
||||
self.kept.clear();
|
||||
self.bytes = 0;
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.images.insert(key, image);
|
||||
self.kept.insert(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,6 +486,7 @@ pub struct FontDb {
|
||||
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
|
||||
/// [`FontDb::glyph_image`]'s answers per (face, glyph), misses too.
|
||||
images: Mutex<GlyphImages>,
|
||||
colours: Mutex<GlyphColours>,
|
||||
catalog: RwLock<Catalog>,
|
||||
/// The installed faces by PostScript name (documents name fonts so: PDF, EPS, .ai).
|
||||
postscript: RwLock<PostScriptNames>,
|
||||
@@ -1554,6 +1596,7 @@ fn make_face(bytes: FontBytes, index: u32, spec: FaceStyle, path: Option<std::pa
|
||||
let underline = decoration(m.underline, (-0.075 * upem, 0.05 * upem));
|
||||
let strikeout = decoration(m.strikeout, (x_height * 0.5 + 0.025 * upem, 0.05 * upem));
|
||||
let colour_bitmaps = crate::bitmap::has_colour_bitmaps(&f);
|
||||
let colour_layers = crate::colr::has_colour_layers(&f);
|
||||
Some(FontFace {
|
||||
keys,
|
||||
traits,
|
||||
@@ -1581,6 +1624,7 @@ fn make_face(bytes: FontBytes, index: u32, spec: FaceStyle, path: Option<std::pa
|
||||
ideographic_centre: std::sync::OnceLock::new(),
|
||||
icf_margins: std::sync::OnceLock::new(),
|
||||
colour_bitmaps,
|
||||
colour_layers,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1684,7 +1728,8 @@ impl FontDb {
|
||||
Self {
|
||||
faces: RwLock::new(faces),
|
||||
outlines: Mutex::new(HashMap::new()),
|
||||
images: Mutex::new(GlyphImages::default()),
|
||||
images: Mutex::new(GlyphCache::default()),
|
||||
colours: Mutex::new(GlyphCache::default()),
|
||||
catalog: RwLock::new(Catalog::new()),
|
||||
postscript: RwLock::new(PostScriptNames::new()),
|
||||
font_paths,
|
||||
@@ -2460,16 +2505,36 @@ impl FontDb {
|
||||
return None;
|
||||
}
|
||||
let key = (face.id, gid);
|
||||
if let Some(i) = self.images.lock().unwrap_or_else(|e| e.into_inner()).images.get(&key) {
|
||||
if let Some(i) = self.images.lock().unwrap_or_else(|e| e.into_inner()).kept.get(&key) {
|
||||
return i.clone();
|
||||
}
|
||||
let image = face.skrifa().and_then(|f| crate::bitmap::glyph_image(&f, face.upem, gid)).map(Arc::new);
|
||||
self.images.lock().unwrap_or_else(|e| e.into_inner()).keep(key, image.clone());
|
||||
image
|
||||
}
|
||||
|
||||
/// Glyph `gid`'s COLR colour content in `face`, its foreground layers in `foreground`, cached
|
||||
/// per (face, glyph), and per foreground colour for the glyphs that paint with it.
|
||||
pub(crate) fn glyph_colour(&self, face: &FontFace, gid: u32, foreground: Color) -> Option<ColourContent> {
|
||||
if !face.colour_layers {
|
||||
return None;
|
||||
}
|
||||
let keyed = Some(foreground.to_rgba8(1.0));
|
||||
{
|
||||
let cache = self.colours.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(c) = cache.kept.get(&(face.id, gid, None)).or_else(|| cache.kept.get(&(face.id, gid, keyed))) {
|
||||
return c.clone();
|
||||
}
|
||||
}
|
||||
let (content, used) = face.skrifa().map_or((None, false), |f| crate::colr::colour_glyph(&f, face.location(), face.upem, gid, foreground));
|
||||
let key = (face.id, gid, if used { keyed } else { None });
|
||||
self.colours.lock().unwrap_or_else(|e| e.into_inner()).keep(key, content.clone());
|
||||
content
|
||||
}
|
||||
}
|
||||
|
||||
struct FlipPen(BezPath);
|
||||
/// A pen drawing outlines y down, as text space has them.
|
||||
pub(crate) struct FlipPen(pub(crate) BezPath);
|
||||
|
||||
impl OutlinePen for FlipPen {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
@@ -2641,16 +2706,16 @@ mod image_cache_tests {
|
||||
let blob = vectorcraft_doc::ImageBlob::png(vec![0; crate::bitmap::MAX_PNG_BYTES]);
|
||||
Some(Arc::new(GlyphImage { blob, width: 1, height: 1, xf: kurbo::Affine::IDENTITY }))
|
||||
};
|
||||
let mut cache = GlyphImages::default();
|
||||
let mut cache = GlyphCache::default();
|
||||
for gid in 0..20 {
|
||||
cache.keep((1, gid), image());
|
||||
assert!(cache.bytes <= IMAGE_CACHE_BYTES, "{} bytes after {} images", cache.bytes, gid + 1);
|
||||
}
|
||||
// The same glyph again, as when two threads look it up at once, counts once.
|
||||
cache.keep((1, 19), image());
|
||||
assert_eq!(cache.bytes, cache.images.values().flatten().map(|i| i.blob.bytes.len()).sum::<usize>());
|
||||
assert_eq!(cache.bytes, cache.kept.values().flatten().map(|i: &Arc<GlyphImage>| i.blob.bytes.len()).sum::<usize>());
|
||||
// A glyph without an image costs nothing, and is still kept.
|
||||
cache.keep((1, 99), None);
|
||||
assert!(cache.images.contains_key(&(1, 99)));
|
||||
assert!(cache.kept.contains_key(&(1, 99)));
|
||||
}
|
||||
}
|
||||
@@ -106,9 +106,24 @@ impl Ctx<'_> {
|
||||
fn emit(&mut self, g: &SGlyph, pre: Affine, origin: Point, angle: f64, advance: f64, line: usize) {
|
||||
// Control characters (tabs) and soft hyphens draw nothing (fonts map them to .notdef).
|
||||
let blank = g.is_soft_hyphen() || g.ch.is_control();
|
||||
// A colour bitmap glyph draws its image, not its outline.
|
||||
let image = if g.inline.is_some() || blank { None } else { self.db.glyph_image(&g.face, g.gid) };
|
||||
let src = if g.inline.is_some() || image.is_some() { std::sync::Arc::new(BezPath::new()) } else { self.db.outline(&g.face, g.gid) };
|
||||
// A colour glyph draws its layers (COLR) or its image (a bitmap, or COLR paints documents
|
||||
// have no form for), not its outline; COLR first. Layers in the foreground colour take
|
||||
// the run's fill, or black when it isn't a colour.
|
||||
let plain = g.inline.is_some() || blank;
|
||||
let foreground = match &self.style_at(g.byte).fill {
|
||||
vectorcraft_doc::color::Paint::Solid { color, .. } => *color,
|
||||
_ => vectorcraft_doc::color::Color::BLACK,
|
||||
};
|
||||
let (colour, image) = match (!plain).then(|| self.db.glyph_colour(&g.face, g.gid, foreground)).flatten() {
|
||||
Some(crate::colr::ColourContent::Art(art)) => (Some(art), None),
|
||||
Some(crate::colr::ColourContent::Image(image)) => (None, Some(image)),
|
||||
None => (None, (!plain).then(|| self.db.glyph_image(&g.face, g.gid)).flatten()),
|
||||
};
|
||||
let src = if g.inline.is_some() || image.is_some() || colour.is_some() {
|
||||
std::sync::Arc::new(BezPath::new())
|
||||
} else {
|
||||
self.db.outline(&g.face, g.gid)
|
||||
};
|
||||
// A glyph whose leading space was taken off (mojikumi) is drawn that much earlier: an
|
||||
// upright one in vertical type by moving it up the column once it stands upright.
|
||||
let upright = self.vertical && !self.on_path && g.tcy.is_none() && stands_upright(g);
|
||||
@@ -173,6 +188,7 @@ impl Ctx<'_> {
|
||||
rtl: g.level.is_rtl() && !self.vertical,
|
||||
scale: 1.0,
|
||||
image,
|
||||
colour,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -730,6 +746,9 @@ fn finish_bounds(out: &mut TextLayout) {
|
||||
if let Some((image, xf)) = g.placed_image() {
|
||||
add(xf.transform_rect_bbox(image.rect()));
|
||||
}
|
||||
if let Some(b) = g.colour.as_ref().and_then(|c| c.geometric_bounds()) {
|
||||
add(g.xf.transform_rect_bbox(b));
|
||||
}
|
||||
}
|
||||
// Ruby: covered by its line's ascent, but its ink can overhang sideways past the line.
|
||||
for g in &out.ruby {
|
||||
@@ -2944,5 +2963,6 @@ fn ruby_glyph(g: &PositionedGlyph, m: Affine, run: usize, byte: usize, line: usi
|
||||
scale: 1.0,
|
||||
// Ruby draws outlines only.
|
||||
image: None,
|
||||
colour: None,
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -11,6 +11,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod bitmap;
|
||||
mod colr;
|
||||
mod composer;
|
||||
pub mod craft_fonts;
|
||||
pub mod edit;
|
||||
@@ -123,8 +124,11 @@ pub struct PositionedGlyph {
|
||||
/// included.
|
||||
pub scale: f64,
|
||||
/// A colour bitmap glyph (emoji), drawn through `xf` instead of an outline: its `outline` is
|
||||
/// empty.
|
||||
/// empty. Also a COLR glyph whose paints documents have no form for, drawn as an image.
|
||||
pub image: Option<Arc<GlyphImage>>,
|
||||
/// A COLR colour glyph's layers, drawn through `xf` instead of an outline: art in font units
|
||||
/// (y down), an isolated group. Its `outline` is empty.
|
||||
pub colour: Option<Arc<vectorcraft_doc::Node>>,
|
||||
}
|
||||
|
||||
impl PositionedGlyph {
|
||||
@@ -132,6 +136,13 @@ impl PositionedGlyph {
|
||||
pub fn placed_image(&self) -> Option<(&Arc<GlyphImage>, Affine)> {
|
||||
self.image.as_ref().map(|i| (i, self.xf * i.xf))
|
||||
}
|
||||
/// The glyph's COLR layers placed through `to_doc` (text space → where they go): a copy of
|
||||
/// [`Self::colour`], transformed, its nodes without ids.
|
||||
pub fn placed_colour(&self, to_doc: Affine) -> Option<vectorcraft_doc::Node> {
|
||||
let mut art = (**self.colour.as_ref()?).clone();
|
||||
art.transform(to_doc * self.xf, true);
|
||||
Some(art)
|
||||
}
|
||||
}
|
||||
|
||||
/// One line of laid-out text.
|
||||
@@ -612,6 +623,8 @@ mod tests_bidi;
|
||||
#[cfg(test)]
|
||||
mod tests_bitmaps;
|
||||
#[cfg(test)]
|
||||
mod tests_colr;
|
||||
#[cfg(test)]
|
||||
mod tests_combos;
|
||||
#[cfg(test)]
|
||||
mod tests_devanagari;
|
||||
|
||||
@@ -585,3 +585,94 @@ pub fn solid_png(side: u32, rgba: [u8; 4]) -> Vec<u8> {
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
/// The palette of [`colr_font`] (palette 0, RGBA): its indices 0, 1 and 2.
|
||||
pub const COLR_RED: [u8; 4] = [255, 0, 0, 255];
|
||||
pub const COLR_BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
pub const COLR_GREEN: [u8; 4] = [0, 255, 0, 255];
|
||||
|
||||
/// The character whose glyph [`colr_font`]`(true)` paints with a sweep gradient.
|
||||
pub const COLR_SWEEP_CHAR: char = 'S';
|
||||
|
||||
/// The family of [`colr_font`] (COLRv1, or v0).
|
||||
pub fn colr_family(v1: bool) -> &'static str {
|
||||
if v1 { "Colrtest Paints" } else { "Colrtest Layers" }
|
||||
}
|
||||
|
||||
/// The glyph ids of `chars` in the bundled Source Sans 3.
|
||||
fn source_sans_gids<const N: usize>(chars: [char; N]) -> Option<[u16; N]> {
|
||||
let font = skrifa::FontRef::new(SOURCE_SANS).ok()?;
|
||||
let mut gids = [0; N];
|
||||
for (gid, ch) in gids.iter_mut().zip(chars) {
|
||||
*gid = u16::try_from(font.charmap().map(ch)?.to_u32()).ok()?;
|
||||
}
|
||||
Some(gids)
|
||||
}
|
||||
|
||||
const SOURCE_SANS: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
|
||||
/// The bundled Source Sans 3 Regular as family [`colr_family`], with `COLR` and `CPAL` tables
|
||||
/// written from the OpenType specification, palette 0 [`COLR_RED`], [`COLR_BLUE`], [`COLR_GREEN`].
|
||||
/// v0: [`COLOUR_CHAR`] is the outline of `O` in red, then that of `I` in the foreground colour
|
||||
/// (palette index 0xFFFF). v1: [`COLOUR_CHAR`] is, in a clip box, `O` filled with a linear
|
||||
/// gradient red → blue, `I` scaled by a half about the origin with a radial gradient blue → green,
|
||||
/// and `-` in green composited with Multiply over `-` in red; [`COLR_SWEEP_CHAR`] is `O` with a
|
||||
/// sweep gradient red → blue. Their outlines stay. `None` when it can't be built.
|
||||
pub fn colr_font(v1: bool) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::colr::{
|
||||
BaseGlyph, BaseGlyphList, BaseGlyphPaint, Clip, ClipBox, ClipList, ColorLine, ColorStop, Colr, CompositeMode, Extend, Layer, LayerList, Paint,
|
||||
};
|
||||
use write_fonts::types::{FWord, GlyphId16, UfWord};
|
||||
let [base, sweep, o, i, dash] = source_sans_gids([COLOUR_CHAR, COLR_SWEEP_CHAR, 'O', 'I', '-'])?;
|
||||
let (base, sweep, o, i, dash) = (GlyphId16::new(base), GlyphId16::new(sweep), GlyphId16::new(o), GlyphId16::new(i), GlyphId16::new(dash));
|
||||
let colr = if v1 {
|
||||
let one = F2Dot14::from_f32(1.0);
|
||||
let line = |from: u16, to: u16| {
|
||||
ColorLine::new(Extend::Pad, 2, vec![ColorStop::new(F2Dot14::from_f32(0.0), from, one), ColorStop::new(one, to, one)])
|
||||
};
|
||||
let w = FWord::new;
|
||||
let layers = vec![
|
||||
Paint::glyph(Paint::linear_gradient(line(0, 1), w(0), w(0), w(500), w(0), w(0), w(500)), o),
|
||||
Paint::scale_uniform(
|
||||
Paint::glyph(Paint::radial_gradient(line(1, 2), w(250), w(300), UfWord::new(0), w(250), w(300), UfWord::new(300)), i),
|
||||
F2Dot14::from_f32(0.5),
|
||||
),
|
||||
Paint::composite(Paint::glyph(Paint::solid(2, one), dash), CompositeMode::Multiply, Paint::glyph(Paint::solid(0, one), dash)),
|
||||
];
|
||||
let mut colr = Colr::new(0, None, None, 0);
|
||||
colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into();
|
||||
let mut glyphs = vec![
|
||||
BaseGlyphPaint::new(base, Paint::colr_layers(3, 0)),
|
||||
BaseGlyphPaint::new(sweep, Paint::glyph(Paint::sweep_gradient(line(0, 1), w(250), w(300), F2Dot14::from_f32(0.0), one), o)),
|
||||
];
|
||||
glyphs.sort_by_key(|g| g.glyph_id);
|
||||
colr.base_glyph_list = Some(BaseGlyphList::new(glyphs.len() as u32, glyphs)).into();
|
||||
let clip = ClipBox::format_1(w(-50), w(-250), w(750), w(800));
|
||||
colr.clip_list = Some(ClipList::new(1, 1, vec![Clip::new(base, base, clip)])).into();
|
||||
colr
|
||||
} else {
|
||||
Colr::new(1, Some(vec![BaseGlyph::new(base, 0, 2)]), Some(vec![Layer::new(o, 0), Layer::new(i, 0xFFFF)]), 2)
|
||||
};
|
||||
colr_font_with(colr_family(v1), &colr)
|
||||
}
|
||||
|
||||
/// The bundled Source Sans 3 Regular as `family` with `colr` and [`colr_font`]'s palette.
|
||||
pub fn colr_font_with(family: &str, colr: &write_fonts::tables::colr::Colr) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::cpal::{ColorRecord, Cpal};
|
||||
let font = skrifa::FontRef::new(SOURCE_SANS).ok()?;
|
||||
let ps = family.replace(' ', "");
|
||||
let name = name_table(&[(1, family), (2, "Regular"), (4, &format!("{family} Regular")), (6, &format!("{ps}-Regular"))])?;
|
||||
let records = [COLR_RED, COLR_BLUE, COLR_GREEN].map(|[r, g, b, a]| ColorRecord::new(b, g, r, a)).to_vec();
|
||||
let cpal = Cpal::new(3, 1, 3, Some(records), vec![0]);
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
builder.add_table(colr).ok()?;
|
||||
builder.add_table(&cpal).ok()?;
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
@@ -161,6 +161,7 @@ fn lines_of_clusters(lines: &[&[(usize, usize, f64)]], rtl: bool) -> TextLayout
|
||||
rtl,
|
||||
scale: 1.0,
|
||||
image: None,
|
||||
colour: None,
|
||||
});
|
||||
x += advance;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
//! COLR colour glyphs (v0 layers, v1 paints): read as trees of document nodes in font units, or
|
||||
//! as an image for paints VectorCraft lacks, and laid out with the type.
|
||||
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::color::ColorGlyphFormat;
|
||||
|
||||
use super::test_fonts::{COLOUR_CHAR, COLR_SWEEP_CHAR, colr_font};
|
||||
|
||||
#[test]
|
||||
fn colr_fonts_build_and_read() {
|
||||
for v1 in [false, true] {
|
||||
let bytes = colr_font(v1).expect("the test font builds");
|
||||
let font = skrifa::FontRef::new(&bytes).unwrap();
|
||||
let glyph = |ch| font.color_glyphs().get(font.charmap().map(ch).unwrap());
|
||||
let format = glyph(COLOUR_CHAR).map(|g| g.format());
|
||||
assert!(matches!((v1, format), (false, Some(ColorGlyphFormat::ColrV0)) | (true, Some(ColorGlyphFormat::ColrV1))), "v1 {v1}");
|
||||
assert_eq!(glyph(COLR_SWEEP_CHAR).is_some(), v1, "only v1 has the sweep glyph");
|
||||
}
|
||||
}
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use skrifa::instance::LocationRef;
|
||||
use vectorcraft_doc::color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
use super::colr::{ColourContent, colour_glyph};
|
||||
use super::test_fonts::{COLR_GREEN, COLR_RED};
|
||||
|
||||
const FOREGROUND: Color = Color::Rgb { r: 0.25, g: 0.5, b: 0.75 };
|
||||
|
||||
/// [`colour_glyph`] of `ch` in `font`.
|
||||
fn content(font: &[u8], ch: char) -> Option<ColourContent> {
|
||||
let font = skrifa::FontRef::new(font).unwrap();
|
||||
let gid = font.charmap().map(ch).unwrap().to_u32();
|
||||
colour_glyph(&font, LocationRef::default(), 1000.0, gid, FOREGROUND).0
|
||||
}
|
||||
|
||||
fn art(font: &[u8], ch: char) -> Arc<Node> {
|
||||
match content(font, ch) {
|
||||
Some(ColourContent::Art(a)) => a,
|
||||
_ => panic!("vector art expected"),
|
||||
}
|
||||
}
|
||||
|
||||
fn children(n: &Node) -> &[Arc<Node>] {
|
||||
n.children().map(Vec::as_slice).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn fill(n: &Node) -> Paint {
|
||||
n.appearance.fill_paint()
|
||||
}
|
||||
|
||||
fn rgb([r, g, b, _]: [u8; 4]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v0_layers_are_paths_in_paint_order() {
|
||||
let root = art(&colr_font(false).unwrap(), COLOUR_CHAR);
|
||||
assert!(!root.isolate, "a group without blending needs no layer of its own");
|
||||
let layers = children(&root);
|
||||
assert_eq!(layers.len(), 2, "{layers:?}");
|
||||
assert!(layers.iter().all(|l| matches!(l.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(fill(&layers[0]), Paint::solid(rgb(COLR_RED)));
|
||||
assert_eq!(fill(&layers[1]), Paint::solid(FOREGROUND), "palette index 0xFFFF is the foreground");
|
||||
// In font units, y down: the `O` stands above the baseline.
|
||||
let b = layers[0].geometric_bounds().unwrap();
|
||||
assert!(b.y1 <= 20.0 && b.y0 < -500.0 && b.width() > 400.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v1_paints_become_gradients_clips_and_isolated_groups() {
|
||||
let root = art(&colr_font(true).unwrap(), COLOUR_CHAR);
|
||||
// The clip box clips the whole glyph.
|
||||
let [clipped] = children(&root) else { panic!("{:?}", children(&root)) };
|
||||
assert!(matches!(clipped.kind, NodeKind::Group { clip: true, .. }), "{:?}", clipped.kind);
|
||||
let layers = &children(clipped)[1..];
|
||||
assert_eq!(layers.len(), 3, "{layers:?}");
|
||||
let gradient = |n: &Node| match fill(n) {
|
||||
Paint::Gradient(g) => g,
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
let linear = gradient(&layers[0]);
|
||||
assert_eq!(linear.gradient.kind, GradientKind::Linear);
|
||||
let geom = linear.geom.unwrap();
|
||||
assert!((geom.start.x - 0.0).abs() < 1e-6 && (geom.end.x - 500.0).abs() < 1e-6, "{geom:?}");
|
||||
let radial = gradient(&layers[1]);
|
||||
assert_eq!(radial.gradient.kind, GradientKind::Radial);
|
||||
// Scaled by a half about the origin, y down: centre (125, -150), radius 150.
|
||||
let geom = radial.geom.unwrap();
|
||||
assert!((geom.start.x - 125.0).abs() < 1e-3 && (geom.start.y + 150.0).abs() < 1e-3, "{geom:?}");
|
||||
assert!(((geom.end - geom.start).hypot() - 150.0).abs() < 1e-3, "{geom:?}");
|
||||
// The composite: an isolated group, the backdrop, then the source multiplied over it.
|
||||
let composite = &layers[2];
|
||||
assert!(composite.isolate);
|
||||
let [backdrop, source] = children(composite) else { panic!("{:?}", children(composite)) };
|
||||
assert_eq!(fill(backdrop), Paint::solid(rgb(COLR_RED)));
|
||||
let source = children(source).first().cloned().unwrap_or_else(|| source.clone());
|
||||
assert_eq!(fill(&source), Paint::solid(rgb(COLR_GREEN)));
|
||||
assert!(children(composite)[1].blend == BlendMode::Multiply, "{:?}", children(composite)[1].blend);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sweep_gradient_makes_the_glyph_an_image() {
|
||||
let Some(ColourContent::Image(image)) = content(&colr_font(true).unwrap(), COLR_SWEEP_CHAR) else { panic!("an image") };
|
||||
assert!(image.blob.bytes.starts_with(b"\x89PNG"));
|
||||
// The `O` is some 600 units tall: at 256 px per em, some 150 px.
|
||||
assert!((100..300).contains(&image.height), "{}", image.height);
|
||||
// Its pixels map back to the glyph's place in font units, y down.
|
||||
let b = image.xf.transform_rect_bbox(image.rect());
|
||||
assert!(b.y1 <= 20.0 && b.y0 < -500.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colr_graph_that_paints_itself_is_no_colour_glyph() {
|
||||
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, Paint};
|
||||
use write_fonts::types::GlyphId16;
|
||||
let base = skrifa::FontRef::new(&colr_font(false).unwrap()).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32();
|
||||
let base = GlyphId16::new(u16::try_from(base).unwrap());
|
||||
let mut colr = Colr::new(0, None, None, 0);
|
||||
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(base, Paint::colr_glyph(base))])).into();
|
||||
let font = super::test_fonts::colr_font_with("Colrtest Loop", &colr).unwrap();
|
||||
assert!(content(&font, COLOUR_CHAR).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colr_graph_nested_past_the_cap_is_no_colour_glyph() {
|
||||
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, Paint};
|
||||
use write_fonts::types::{F2Dot14, GlyphId16};
|
||||
let font = skrifa::FontRef::new(&colr_font(false).unwrap()).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32();
|
||||
let base = GlyphId16::new(u16::try_from(font).unwrap());
|
||||
let mut paint = Paint::glyph(Paint::solid(0, F2Dot14::from_f32(1.0)), base);
|
||||
for _ in 0..200 {
|
||||
paint = Paint::scale_uniform(paint, F2Dot14::from_f32(1.0));
|
||||
}
|
||||
let mut colr = Colr::new(0, None, None, 0);
|
||||
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(base, paint)])).into();
|
||||
let font = super::test_fonts::colr_font_with("Colrtest Deep", &colr).unwrap();
|
||||
assert!(content(&font, COLOUR_CHAR).is_none());
|
||||
}
|
||||
|
||||
// Layout: colour glyphs are laid out with their layers, which move with the type.
|
||||
|
||||
use kurbo::Point as KPoint;
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
|
||||
use super::test_fonts::colr_family;
|
||||
use super::{FontDb, layout};
|
||||
|
||||
fn colr_db(v1: bool) -> FontDb {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(colr_font(v1).expect("the test font builds")), 1);
|
||||
db
|
||||
}
|
||||
|
||||
fn colr_style(v1: bool) -> CharStyle {
|
||||
CharStyle { font_family: colr_family(v1).into(), size: 100.0, ..CharStyle::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colr_glyph_lays_out_its_layers_with_an_empty_outline() {
|
||||
let db = colr_db(false);
|
||||
let l = layout(&db, &TextObject::point(KPoint::new(10.0, 50.0), &format!("{COLOUR_CHAR}F"), colr_style(false)));
|
||||
let (g, f) = (&l.glyphs[0], &l.glyphs[1]);
|
||||
assert!(g.outline.elements().is_empty(), "the layers replace the outline");
|
||||
assert_eq!(g.colour.as_deref().map(|c| children(c).len()), Some(2));
|
||||
assert!(g.image.is_none());
|
||||
assert!(f.colour.is_none() && !f.outline.elements().is_empty(), "other glyphs keep their outlines");
|
||||
// In text space at 100 pt: the `O` layer stands on the baseline (y 0), some 70 pt tall.
|
||||
let placed = g.placed_colour(kurbo::Affine::IDENTITY).unwrap();
|
||||
let b = placed.geometric_bounds().unwrap();
|
||||
assert!(b.y1.abs() < 3.0 && b.height() > 60.0 && b.height() < 80.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_foreground_layer_takes_the_runs_fill_and_black_for_a_gradient_fill() {
|
||||
let db = colr_db(false);
|
||||
let foreground = |fill: Paint| {
|
||||
let st = CharStyle { fill, ..colr_style(false) };
|
||||
let l = layout(&db, &TextObject::point(KPoint::ZERO, &COLOUR_CHAR.to_string(), st));
|
||||
let colour = l.glyphs[0].colour.clone().unwrap();
|
||||
children(&colour)[1].appearance.fill_paint()
|
||||
};
|
||||
let blue = Color::rgb8(0, 0, 200);
|
||||
assert_eq!(foreground(Paint::solid(blue)), Paint::solid(blue));
|
||||
assert_eq!(foreground(Paint::solid(FOREGROUND)), Paint::solid(FOREGROUND), "a new fill colour, a new glyph");
|
||||
let gradient = Paint::Gradient(Box::new(vectorcraft_doc::color::GradientPaint::new(Default::default())));
|
||||
assert_eq!(foreground(gradient), Paint::solid(Color::BLACK));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_bounds_take_in_the_colour_layers() {
|
||||
let db = colr_db(true);
|
||||
let l = layout(&db, &TextObject::point(KPoint::new(10.0, 50.0), &COLOUR_CHAR.to_string(), colr_style(true)));
|
||||
let g = &l.glyphs[0];
|
||||
let b = g.placed_colour(kurbo::Affine::IDENTITY).unwrap().geometric_bounds().unwrap();
|
||||
assert!(l.bounds.contains_rect(b.inset(-0.01)) || l.bounds.contains_rect(b), "{:?} holds {b:?}", l.bounds);
|
||||
// The `O` layer is wider than the `E` the glyph advances by.
|
||||
assert!(b.width() > g.advance * 0.9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_face_with_colr_and_sbix_draws_colr() {
|
||||
use write_fonts::FontBuilder;
|
||||
use write_fonts::types::Tag;
|
||||
let colr = colr_font(false).unwrap();
|
||||
let sbix = super::test_fonts::colour_bitmap_font(true).unwrap();
|
||||
let sbix = skrifa::FontRef::new(&sbix).unwrap();
|
||||
let font = skrifa::FontRef::new(&colr).unwrap();
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_raw(Tag::new(b"sbix"), sbix.table_data(skrifa::Tag::new(b"sbix")).unwrap().as_bytes());
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag()).unwrap().as_bytes());
|
||||
}
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(builder.build()), 1);
|
||||
let l = layout(&db, &TextObject::point(KPoint::ZERO, &COLOUR_CHAR.to_string(), colr_style(false)));
|
||||
assert!(l.glyphs[0].colour.is_some() && l.glyphs[0].image.is_none(), "vectors over bitmaps");
|
||||
}
|
||||
|
||||
/// A v1 font whose glyph of `base` is `paint`, given the glyph id of `O`, its layer list one
|
||||
/// red fill.
|
||||
fn v1_font(family: &str, base: char, paint: impl Fn(write_fonts::types::GlyphId16) -> ColrPaint) -> Vec<u8> {
|
||||
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList};
|
||||
use write_fonts::types::GlyphId16;
|
||||
let bytes = colr_font(false).unwrap();
|
||||
let font = skrifa::FontRef::new(&bytes).unwrap();
|
||||
let gid = |ch| GlyphId16::new(u16::try_from(font.charmap().map(ch).unwrap().to_u32()).unwrap());
|
||||
let mut colr = Colr::new(0, None, None, 0);
|
||||
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(base), paint(gid('O')))])).into();
|
||||
colr.layer_list = Some(LayerList::new(1, vec![solid(0)])).into();
|
||||
super::test_fonts::colr_font_with(family, &colr).unwrap()
|
||||
}
|
||||
|
||||
use write_fonts::tables::colr::Paint as ColrPaint;
|
||||
|
||||
fn solid(index: u16) -> ColrPaint {
|
||||
ColrPaint::solid(index, write_fonts::types::F2Dot14::from_f32(1.0))
|
||||
}
|
||||
|
||||
fn sweep() -> ColrPaint {
|
||||
use write_fonts::tables::colr::{ColorLine, ColorStop, Extend};
|
||||
use write_fonts::types::{F2Dot14, FWord};
|
||||
let one = F2Dot14::from_f32(1.0);
|
||||
let line = ColorLine::new(Extend::Pad, 2, vec![ColorStop::new(F2Dot14::from_f32(0.0), 0, one), ColorStop::new(one, 1, one)]);
|
||||
ColrPaint::sweep_gradient(line, FWord::new(250), FWord::new(300), F2Dot14::from_f32(0.0), one)
|
||||
}
|
||||
|
||||
/// A glyph filled with a composite of solid colours is vector art: the composite's fills fill
|
||||
/// the glyph around them.
|
||||
#[test]
|
||||
fn a_glyph_filled_with_a_composite_is_vector_art() {
|
||||
use write_fonts::tables::colr::CompositeMode;
|
||||
let font = v1_font("Colrtest Composite", COLOUR_CHAR, |o| ColrPaint::glyph(ColrPaint::composite(solid(2), CompositeMode::Multiply, solid(0)), o));
|
||||
assert!(matches!(content(&font, COLOUR_CHAR), Some(ColourContent::Art(_))));
|
||||
}
|
||||
|
||||
/// A colour of its own filling a (TrueType, quadratic) glyph's area is that glyph filled: one
|
||||
/// path, not a clipping group around a copy of it.
|
||||
#[test]
|
||||
fn a_glyph_filled_with_one_colour_is_one_path() {
|
||||
let font = v1_font("Colrtest Flood", COLOUR_CHAR, |o| ColrPaint::glyph(ColrPaint::colr_layers(1, 0), o));
|
||||
let root = art(&font, COLOUR_CHAR);
|
||||
let [only] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::<Vec<_>>()) };
|
||||
assert!(matches!(only.kind, NodeKind::Path { .. }), "{}", only.kind_label());
|
||||
assert_eq!(fill(only), Paint::solid(rgb(COLR_RED)));
|
||||
}
|
||||
|
||||
/// A sweep glyph in a font without clip boxes, its base glyph without an outline (the space's,
|
||||
/// as COLRv1 fonts make them): its image is as large as what it paints.
|
||||
#[test]
|
||||
fn a_sweep_glyph_without_a_clip_box_or_outline_is_an_image_of_its_paint() {
|
||||
let font = v1_font("Colrtest Bare", ' ', |o| ColrPaint::glyph(sweep(), o));
|
||||
let Some(ColourContent::Image(image)) = content(&font, ' ') else { panic!("an image") };
|
||||
assert!((100..300).contains(&image.height), "{}", image.height);
|
||||
}
|
||||
|
||||
/// A transform that collapses the glyph (scale 0, from a font) draws nothing in its image,
|
||||
/// without panicking.
|
||||
#[test]
|
||||
fn a_collapsed_sweep_glyph_draws_nothing() {
|
||||
use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Clip, ClipBox, ClipList, Colr};
|
||||
use write_fonts::types::{F2Dot14, FWord, GlyphId16};
|
||||
let bytes = colr_font(false).unwrap();
|
||||
let read = skrifa::FontRef::new(&bytes).unwrap();
|
||||
let gid = |ch| GlyphId16::new(u16::try_from(read.charmap().map(ch).unwrap().to_u32()).unwrap());
|
||||
let mut colr = Colr::new(0, None, None, 0);
|
||||
let flat = ColrPaint::scale_uniform(ColrPaint::glyph(sweep(), gid('O')), F2Dot14::from_f32(0.0));
|
||||
colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), flat)])).into();
|
||||
// A clip box, so the image is made.
|
||||
let clip = ClipBox::format_1(FWord::new(0), FWord::new(0), FWord::new(500), FWord::new(500));
|
||||
colr.clip_list = Some(ClipList::new(1, 1, vec![Clip::new(gid(COLOUR_CHAR), gid(COLOUR_CHAR), clip)])).into();
|
||||
let font = super::test_fonts::colr_font_with("Colrtest Flat", &colr).unwrap();
|
||||
let Some(ColourContent::Image(image)) = content(&font, COLOUR_CHAR) else { panic!("an image") };
|
||||
assert!(image.blob.bytes.starts_with(b"\x89PNG"));
|
||||
}
|
||||
|
||||
/// Each paint documents have no form for makes the glyph an image.
|
||||
#[test]
|
||||
fn paints_documents_lack_make_the_glyph_an_image() {
|
||||
use write_fonts::tables::colr::{ColorLine, ColorStop, CompositeMode, Extend};
|
||||
use write_fonts::types::{F2Dot14, FWord, UfWord};
|
||||
let one = F2Dot14::from_f32(1.0);
|
||||
let line = |extend| ColorLine::new(extend, 2, vec![ColorStop::new(F2Dot14::from_f32(0.0), 0, one), ColorStop::new(one, 1, one)]);
|
||||
let w = FWord::new;
|
||||
type GlyphPaint<'a> = Box<dyn Fn(write_fonts::types::GlyphId16) -> ColrPaint + 'a>;
|
||||
let cases: [(&str, GlyphPaint<'_>); 3] = [
|
||||
("Colrtest Xor", Box::new(|o| ColrPaint::composite(ColrPaint::glyph(solid(2), o), CompositeMode::Xor, ColrPaint::glyph(solid(0), o)))),
|
||||
(
|
||||
"Colrtest Repeat",
|
||||
Box::new(move |o| ColrPaint::glyph(ColrPaint::linear_gradient(line(Extend::Repeat), w(0), w(0), w(100), w(0), w(0), w(100)), o)),
|
||||
),
|
||||
(
|
||||
"Colrtest Circles",
|
||||
Box::new(move |o| {
|
||||
ColrPaint::glyph(ColrPaint::radial_gradient(line(Extend::Pad), w(200), w(300), UfWord::new(50), w(250), w(300), UfWord::new(300)), o)
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (family, paint) in cases {
|
||||
let font = v1_font(family, COLOUR_CHAR, paint);
|
||||
assert!(matches!(content(&font, COLOUR_CHAR), Some(ColourContent::Image(_))), "{family}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A radial gradient whose start circle is around its centre is vector art, its stops moved out.
|
||||
#[test]
|
||||
fn a_radial_gradient_from_a_circle_around_its_centre_is_vector_art() {
|
||||
use write_fonts::tables::colr::{ColorLine, ColorStop, Extend};
|
||||
use write_fonts::types::{F2Dot14, FWord, UfWord};
|
||||
let one = F2Dot14::from_f32(1.0);
|
||||
let line = ColorLine::new(Extend::Pad, 2, vec![ColorStop::new(F2Dot14::from_f32(0.0), 0, one), ColorStop::new(one, 1, one)]);
|
||||
let w = FWord::new;
|
||||
let font = v1_font("Colrtest Ring", COLOUR_CHAR, |o| {
|
||||
ColrPaint::glyph(ColrPaint::radial_gradient(line.clone(), w(250), w(300), UfWord::new(100), w(250), w(300), UfWord::new(400)), o)
|
||||
});
|
||||
let root = art(&font, COLOUR_CHAR);
|
||||
let Paint::Gradient(g) = fill(&children(&root)[0]) else { panic!("a gradient") };
|
||||
let offsets: Vec<f32> = g.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.25, 1.0], "the stops start a quarter of the way out");
|
||||
}
|
||||
|
||||
/// A glyph whose layers don't use the foreground colour is read once, whatever the type's fill.
|
||||
#[test]
|
||||
fn a_glyph_without_the_foreground_colour_is_read_once_for_every_fill() {
|
||||
let tree = |v1: bool, fill: Color| {
|
||||
let db = colr_db(v1);
|
||||
let st = CharStyle { fill: Paint::solid(fill), ..colr_style(v1) };
|
||||
let first = layout(&db, &TextObject::point(KPoint::ZERO, &COLOUR_CHAR.to_string(), st.clone())).glyphs[0].colour.clone().unwrap();
|
||||
let st = CharStyle { fill: Paint::solid(FOREGROUND), ..st };
|
||||
let other = layout(&db, &TextObject::point(KPoint::ZERO, &COLOUR_CHAR.to_string(), st)).glyphs[0].colour.clone().unwrap();
|
||||
Arc::ptr_eq(&first, &other)
|
||||
};
|
||||
assert!(tree(true, Color::rgb8(0, 0, 200)), "v1's glyph uses only its palette");
|
||||
assert!(!tree(false, Color::rgb8(0, 0, 200)), "v0's foreground layer follows the fill");
|
||||
}
|
||||
@@ -319,10 +319,11 @@ impl BuilderMap {
|
||||
/// line piece or edge nearest `p` within `tol` (as [`BuilderMap::hit`] finds it), from the
|
||||
/// anchor or crossing point before `p` to the one after it on the path it lies on. `outlines`
|
||||
/// are the inputs' outlines as they are drawn (a filled open path without the edge that closes
|
||||
/// it in the map). Returns the input's index and the run; None when no piece is that close,
|
||||
/// when the run is not on the outline as drawn, when it would be a whole closed subpath, when
|
||||
/// it is too short to cut out (see [`po::cut_out`]), or when it is all of the path (a lone
|
||||
/// line), which leaves nothing to split off.
|
||||
/// it in the map). Returns the input's index and the run, going the way the path goes; None
|
||||
/// when no piece is that close, when the run is not on the outline as drawn, when it would be a
|
||||
/// whole closed subpath, when it is too short to cut out (see [`po::cut_out`]), or when it is
|
||||
/// all of the path (a lone line) or leaves no more of it than [`outline_snap`], which leaves
|
||||
/// nothing to split off.
|
||||
pub fn stroke_at(&self, outlines: &[PathData], p: Point, tol: f64) -> Option<(usize, SubPath)> {
|
||||
use kurbo::ParamCurve as _;
|
||||
let piece = match self.hit(p, Some(tol))? {
|
||||
@@ -334,18 +335,26 @@ impl BuilderMap {
|
||||
let drawn = outlines.get(i)?;
|
||||
let stops: Vec<Point> = drawn.anchors().map(|(.., a)| a.p).collect();
|
||||
let snap = outline_snap(drawn);
|
||||
let run = po::run_around(piece.0.path.subpaths.first()?, &stops, p, snap)?;
|
||||
let mut run = po::run_around(piece.0.path.subpaths.first()?, &stops, p, snap)?;
|
||||
let n = run.segment_count();
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let mid = run.segment(n / 2).eval(0.5);
|
||||
drawn.nearest(mid).filter(|n| n.4 <= snap)?;
|
||||
// A run that cannot be cut out, or that is all of the path (such as a lone line), leaves
|
||||
// nothing to split off.
|
||||
if po::cut_out(drawn, &run, false, snap).is_none_or(|rest| rest.is_empty()) {
|
||||
// A run that cannot be cut out, or that is all of the path (such as a lone line) or all
|
||||
// but a speck of it, leaves nothing to split off.
|
||||
if !po::cut_out(drawn, &run, false, snap).is_some_and(|rest| rest.length() > snap) {
|
||||
return None;
|
||||
}
|
||||
// Reverse the run when the path's parameter goes down along it.
|
||||
let seg = run.segment(n / 2);
|
||||
if let (Some(a), Some(b)) = (drawn.nearest(seg.eval(0.25)), drawn.nearest(seg.eval(0.75)))
|
||||
&& a.0 == b.0
|
||||
&& (b.1 as f64 + b.2) < (a.1 as f64 + a.2)
|
||||
{
|
||||
run.reverse();
|
||||
}
|
||||
Some((i, run))
|
||||
}
|
||||
|
||||
|
||||
@@ -376,8 +376,8 @@ impl CurvatureTool {
|
||||
/// and the segment to it: the path being drawn, or the selected one whose end is current.
|
||||
fn leave(&self, cx: &ToolContext) -> Option<(NodeId, Leave)> {
|
||||
match self.active(cx) {
|
||||
Some(id) => self.pts.last().map(|(p, _)| (id, Leave::segment(cx, *p, false))),
|
||||
None => current_end(cx).map(|e| (e.id, Leave::segment(cx, e.p, false))),
|
||||
Some(id) => self.pts.last().map(|(p, _)| (id, Leave::segment(cx, *p, false).without_contact())),
|
||||
None => current_end(cx).map(|e| (e.id, Leave::segment(cx, e.p, false).without_contact())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,7 +420,7 @@ impl CurvatureTool {
|
||||
return Some(out);
|
||||
}
|
||||
if let Some(e) = end {
|
||||
let q = self.snap.press(cx, p, &[e.id], Some(&Leave::segment(cx, e.p, false)));
|
||||
let q = self.snap.press(cx, p, &[e.id], Some(&Leave::segment(cx, e.p, false).without_contact()));
|
||||
let how = self.how(&e);
|
||||
self.placed = Some(Placed { id: e.id, si: e.si, start: e.start, anchors: e.anchors + 1, corner: ev.mods.alt });
|
||||
let v = json!({"id": e.id.0, "subpath": e.si, "op": "extend", "end": e.name(), "x": q.x, "y": q.y, "from": how.name(), "corner": ev.mods.alt});
|
||||
|
||||
+216
-6
@@ -13,8 +13,8 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::hit::{HitOptions, hit_test};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, OrientedBox, Selection};
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
use vectorcraft_geom::{Affine, Line, ParamCurve, PathSeg, Point, Rect, Shape, SubPath, Vec2, constrain_angle_from};
|
||||
use vectorcraft_geom::kurbo::{ParamCurveDeriv, ParamCurveNearest};
|
||||
use vectorcraft_geom::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Shape, SubPath, Vec2, constrain_angle_from};
|
||||
use vectorcraft_text::{FontDb, layout as layout_text};
|
||||
|
||||
use crate::bbox::Handle;
|
||||
@@ -89,6 +89,10 @@ pub struct Targets {
|
||||
/// it ends, as the end that stays put and the unit direction towards the dragged one
|
||||
/// ([`Self::for_anchor_drag`]).
|
||||
extensions: Vec<(Point, Vec2)>,
|
||||
/// Snap to Tangent and Snap to Perpendicular: a drawn line from an anchor lands where it
|
||||
/// grazes a curve, or meets a segment square ([`Self::touching`]).
|
||||
tangent: bool,
|
||||
perpendicular: bool,
|
||||
/// How the guides these targets produce look.
|
||||
style: GuideStyle,
|
||||
}
|
||||
@@ -560,6 +564,11 @@ impl Targets {
|
||||
if let Some(q) = self.crossing(p, tol) {
|
||||
return (q, self.label(q, "intersect").into_iter().collect());
|
||||
}
|
||||
if let Some(f) = from.filter(|f| f.contact)
|
||||
&& let Some((q, perpendicular, dir)) = self.touching(f.at, p, tol)
|
||||
{
|
||||
return (q, self.touch_guides(f.at, q, perpendicular, dir, tol));
|
||||
}
|
||||
if let Some(q) = self.on_segment(p, tol) {
|
||||
return (q, self.label(q, Kind::Edge.label()).into_iter().collect());
|
||||
}
|
||||
@@ -602,6 +611,52 @@ impl Targets {
|
||||
(out, ov)
|
||||
}
|
||||
|
||||
/// Where a line from `at` through a point near `p` touches a target segment: square to it
|
||||
/// (`perpendicular`, the foot of the perpendicular from `at`) or just grazing a curve
|
||||
/// (`tangent`), within `tol` of `p`. The point, whether it is the perpendicular one, and the
|
||||
/// segment's direction there. Targets gather segments for drawn points and dragged anchors only.
|
||||
fn touching(&self, at: Point, p: Point, tol: f64) -> Option<(Point, bool, Vec2)> {
|
||||
if !(self.tangent || self.perpendicular) || ![at.x, at.y, p.x, p.y, tol].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let mut best: Option<(f64, Point, bool, Vec2)> = None;
|
||||
// Every segment in reach is tried: their order is the document's, not the distance.
|
||||
for (_, seg) in self.segments.iter().filter(|(b, _)| b.inflate(tol, tol).contains(p)) {
|
||||
let curved = !matches!(seg, PathSeg::Line(_));
|
||||
for (perpendicular, wanted) in [(true, self.perpendicular && !curved), (false, self.tangent && curved)] {
|
||||
if !wanted {
|
||||
continue;
|
||||
}
|
||||
for t in touch_params(seg, at, perpendicular) {
|
||||
let (q, d) = (seg.eval(t), seg_direction(seg, t));
|
||||
let dist = q.distance(p);
|
||||
if dist <= tol && q.distance(at) > tol && best.is_none_or(|b| dist < b.0) {
|
||||
best = Some((dist, q, perpendicular, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, q, perpendicular, d)| (q, perpendicular, d))
|
||||
}
|
||||
|
||||
/// The guides of a point landed where the line from `at` touches a segment at `q` running
|
||||
/// along `dir`: the line itself, a square corner mark for the perpendicular, and the label.
|
||||
fn touch_guides(&self, at: Point, q: Point, perpendicular: bool, dir: Vec2, tol: f64) -> Vec<Overlay> {
|
||||
let mut out: Vec<Overlay> = self.line(at, q).into_iter().collect();
|
||||
let (u, v) = (at - q, dir);
|
||||
if perpendicular && self.style.lines && u.hypot2() > 1e-18 && v.hypot2() > 1e-18 {
|
||||
let (u, v) = (u / u.hypot(), v / v.hypot());
|
||||
let s = tol * 1.5;
|
||||
let mut mark = BezPath::new();
|
||||
mark.move_to(q + u * s);
|
||||
mark.line_to(q + u * s + v * s);
|
||||
mark.line_to(q + v * s);
|
||||
out.push(Overlay::Path { path: mark, color: self.style.color, width: 1.0, dashed: false });
|
||||
}
|
||||
out.extend(self.label(q, if perpendicular { "perpendicular" } else { "tangent" }));
|
||||
out
|
||||
}
|
||||
|
||||
/// The segment extension nearest `p`, within `tol` of it (and `p` farther than that from the
|
||||
/// end it starts at): that end, its direction and where `p` lands on it. Where `p` is nearer
|
||||
/// the horizontal or the vertical through that end there is none: lining up with it ("align")
|
||||
@@ -1123,6 +1178,53 @@ fn meeting(a: &PathSeg, b: &PathSeg, p: Point) -> Option<Point> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The direction of `seg` at `t` (not normalised; zero in a cusp).
|
||||
fn seg_direction(seg: &PathSeg, t: f64) -> Vec2 {
|
||||
match seg {
|
||||
PathSeg::Line(l) => l.p1 - l.p0,
|
||||
PathSeg::Quad(q) => q.deriv().eval(t).to_vec2(),
|
||||
PathSeg::Cubic(c) => c.deriv().eval(t).to_vec2(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters in (0, 1) where the line from `at` to `seg` is square to it (`perpendicular`)
|
||||
/// or grazes it, found by sampling the curve for a change of sign and bisecting.
|
||||
fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec<f64> {
|
||||
const STEPS: usize = 24;
|
||||
let f = |t: f64| {
|
||||
let (v, d) = (seg.eval(t) - at, seg_direction(seg, t));
|
||||
if perpendicular { v.dot(d) } else { v.cross(d) }
|
||||
};
|
||||
let mut out = vec![];
|
||||
let mut prev = (0.0, f(0.0));
|
||||
for i in 1..=STEPS {
|
||||
let t = i as f64 / STEPS as f64;
|
||||
let cur = (t, f(t));
|
||||
if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 {
|
||||
let (mut lo, mut hi) = (prev, cur);
|
||||
for _ in 0..40 {
|
||||
let mid = 0.5 * (lo.0 + hi.0);
|
||||
let m = (mid, f(mid));
|
||||
if lo.1 * m.1 <= 0.0 {
|
||||
hi = m;
|
||||
} else {
|
||||
lo = m;
|
||||
}
|
||||
}
|
||||
let t = 0.5 * (lo.0 + hi.0);
|
||||
// A jump through a cusp changes sign without crossing zero: the line must really
|
||||
// run along (or square to) the curve there.
|
||||
let (v, d) = (seg.eval(t) - at, seg_direction(seg, t));
|
||||
let scale = v.hypot() * d.hypot();
|
||||
if scale > 1e-12 && f(t).abs() <= 1e-3 * scale {
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
prev = cur;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Snap `p` for a drawing tool when smart guides (or grid snapping) are on.
|
||||
pub fn snap_draw(cx: &ToolContext, p: Point, exclude: &[NodeId]) -> (Point, Vec<Overlay>) {
|
||||
snap_with(cx, p, || Targets::collect(cx.doc, exclude, None))
|
||||
@@ -1148,7 +1250,8 @@ impl PointSnap {
|
||||
None
|
||||
} else if cx.smart_guides {
|
||||
// Snap to Point keeps pulling points onto the ruler guides with Smart Guides on (#812).
|
||||
let t = targets().styled(cx);
|
||||
let mut t = targets().styled(cx);
|
||||
(t.tangent, t.perpendicular) = (cx.snap_tangent, cx.snap_perpendicular);
|
||||
Some((if cx.snap_to_point { t.with_rulers(cx) } else { t }, cx.snapping_tolerance))
|
||||
} else if cx.snap_to_point {
|
||||
Some((targets().for_snap_to_point(cx), cx.snap_tolerance))
|
||||
@@ -1247,6 +1350,8 @@ pub struct Leave {
|
||||
shift: Option<Keep>,
|
||||
/// The angles of the construction guides through `at` (none with them off).
|
||||
angles: &'static [f64],
|
||||
/// A drawn segment: it may land square to a segment or grazing a curve (a box does not).
|
||||
contact: bool,
|
||||
}
|
||||
|
||||
impl Leave {
|
||||
@@ -1257,14 +1362,21 @@ impl Leave {
|
||||
at,
|
||||
shift: shift.then_some(Keep::Angle { step: 45.0, base: cx.constrain_angle }),
|
||||
angles: if cx.smart_guides { cx.construction_angles } else { &[] },
|
||||
contact: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A curved source cannot make a line-to-line perpendicular or line-to-curve tangent contact.
|
||||
pub fn without_contact(mut self) -> Self {
|
||||
self.contact = false;
|
||||
self
|
||||
}
|
||||
|
||||
/// A box dragged from its corner or centre `at` (Rectangle, Ellipse, Arc, the grids, and
|
||||
/// Artboard, which passes no Shift): Shift keeps the dragged corner on a diagonal, the box a
|
||||
/// square.
|
||||
pub fn diagonal(at: Point, shift: bool) -> Self {
|
||||
Self { at, shift: shift.then_some(Keep::Square), angles: &[] }
|
||||
Self { at, shift: shift.then_some(Keep::Square), angles: &[], contact: false }
|
||||
}
|
||||
|
||||
/// Where Shift puts `p`: none without it.
|
||||
@@ -1324,7 +1436,7 @@ struct SnapKey {
|
||||
revision: (u64, u64),
|
||||
exclude: Vec<NodeId>,
|
||||
screen: Option<ScreenFrame>,
|
||||
view: [bool; 5],
|
||||
view: [bool; 7],
|
||||
snap_to_glyph: bool,
|
||||
style: GuideStyle,
|
||||
tolerances: [f64; 2],
|
||||
@@ -1336,7 +1448,7 @@ impl SnapKey {
|
||||
revision: cx.revision,
|
||||
exclude: exclude.to_vec(),
|
||||
screen: cx.screen,
|
||||
view: [cx.smart_guides, cx.snap_to_point, cx.snap_to_pixel, cx.snap_to_grid, cx.guides],
|
||||
view: [cx.smart_guides, cx.snap_to_point, cx.snap_to_pixel, cx.snap_to_grid, cx.guides, cx.snap_tangent, cx.snap_perpendicular],
|
||||
snap_to_glyph: cx.snap_to_glyph && cx.alignment_guides,
|
||||
style: GuideStyle::of(cx),
|
||||
tolerances: [cx.snapping_tolerance, cx.snap_tolerance],
|
||||
@@ -1868,6 +1980,104 @@ mod tests {
|
||||
assert_eq!(labels(&t.snap_from(Point::new(170.0, 201.0), None, 4.0).1), ["path"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perpendicular_snapping_rejects_a_curved_target() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
d.insert(
|
||||
Some(layer),
|
||||
1,
|
||||
vectorcraft_doc::Node::path(
|
||||
id,
|
||||
vectorcraft_geom::shapes::ellipse(Rect::new(450.0, 450.0, 550.0, 550.0)),
|
||||
vectorcraft_doc::Appearance::default_art(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let targets = Targets { tangent: false, perpendicular: true, ..Targets::for_drawing(&d, &[], None, false) };
|
||||
assert!(targets.touching(Point::new(400.0, 500.0), Point::new(450.0, 500.0), 4.0).is_none());
|
||||
assert!(targets.touching(Point::new(300.0, 160.0), Point::new(200.0, 160.0), 4.0).is_some());
|
||||
}
|
||||
|
||||
/// A line drawn from an anchor lands square to a segment (the foot of its perpendicular) and
|
||||
/// just grazing a curve, with a guide and a label; the options switch each off, and the
|
||||
/// result is the same each time and survives non-finite input.
|
||||
#[test]
|
||||
fn drawn_lines_land_perpendicular_to_segments_and_tangent_to_curves() {
|
||||
use vectorcraft_doc::{Appearance, Node};
|
||||
use vectorcraft_geom::shapes;
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), 1, Node::path(id, shapes::ellipse(Rect::new(450.0, 450.0, 550.0, 550.0)), Appearance::default_art())).unwrap();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let snap = |c: &ToolContext, from: Point, to: Point| {
|
||||
let leave = Leave::segment(c, from, false);
|
||||
PointSnap::new(c, || Targets::for_drawing(&d, &[], None, false)).snap_from(c, to, Some(&leave))
|
||||
};
|
||||
// From (300, 160) the rect's right side (x = 200) is square at (200, 160).
|
||||
let (q, ov) = snap(&c, Point::new(300.0, 160.0), Point::new(202.0, 163.0));
|
||||
assert!((q - Point::new(200.0, 160.0)).hypot() < 1e-6, "{q:?}");
|
||||
assert_eq!(labels(&ov), ["perpendicular"]);
|
||||
assert_eq!(lines(&ov), vec![(Point::new(300.0, 160.0), q)]);
|
||||
assert!(ov.iter().any(|o| matches!(o, Overlay::Path { .. })), "the square corner mark: {ov:?}");
|
||||
assert_eq!(snap(&c, Point::new(300.0, 160.0), Point::new(202.0, 163.0)).0, q, "deterministic");
|
||||
// Off, the point only lands on the path, where the pointer is.
|
||||
let curved = Leave::segment(&c, Point::new(300.0, 160.0), false).without_contact();
|
||||
let (_, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, false)).snap_from(&c, Point::new(202.0, 163.0), Some(&curved));
|
||||
assert!(!labels(&ov).contains(&"perpendicular"));
|
||||
let off = ToolContext { snap_perpendicular: false, ..cx(&d, &s, &p) };
|
||||
let (q, ov) = snap(&off, Point::new(300.0, 160.0), Point::new(202.0, 163.0));
|
||||
assert_eq!((q, labels(&ov)), (Point::new(200.0, 163.0), vec!["path"]));
|
||||
// The circle (centre (500, 500), radius 50) seen from (400, 500): the tangent points are 60°
|
||||
// round from the way back, at (475, 456.7) and (475, 543.3).
|
||||
let (q, ov) = snap(&c, Point::new(400.0, 500.0), Point::new(477.0, 459.0));
|
||||
assert_eq!(labels(&ov), ["tangent"]);
|
||||
assert!((q - Point::new(475.0, 500.0 - 1875f64.sqrt())).hypot() < 0.1, "{q:?}");
|
||||
assert!(((q - Point::new(400.0, 500.0)).dot(q - Point::new(500.0, 500.0))).abs() < 20.0, "{q:?}");
|
||||
let none = ToolContext { snap_tangent: false, ..cx(&d, &s, &p) };
|
||||
assert!(!labels(&snap(&none, Point::new(400.0, 500.0), Point::new(477.0, 459.0)).1).contains(&"tangent"));
|
||||
// Out of reach, or with nothing finite to go on: left alone, no panic.
|
||||
assert_eq!(snap(&c, Point::new(300.0, 160.0), Point::new(250.0, 175.0)).0, Point::new(250.0, 175.0));
|
||||
let t = Targets::for_drawing(&d, &[], None, false);
|
||||
let t = Targets { tangent: true, perpendicular: true, ..t };
|
||||
for bad in [f64::NAN, f64::INFINITY] {
|
||||
assert!(t.touching(Point::new(bad, 1.0), Point::new(200.0, 160.0), 4.0).is_none());
|
||||
assert!(t.touching(Point::new(300.0, 160.0), Point::new(bad, 1.0), 4.0).is_none());
|
||||
assert!(t.touching(Point::new(300.0, 160.0), Point::new(200.0, 160.0), bad).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// A box dragged from a corner (Rectangle, Ellipse, ...) never snaps square to a segment, and
|
||||
/// a busy spot does not hide the contact: every segment in reach is tried.
|
||||
#[test]
|
||||
fn contact_snaps_only_for_segments_and_in_busy_spots() {
|
||||
use vectorcraft_geom::kurbo::Line;
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let snap = |t: &Targets, leave: &Leave| t.snap_from(Point::new(202.0, 163.0), Some(leave), 4.0);
|
||||
let t = Targets { tangent: true, perpendicular: true, ..Targets::for_drawing(&d, &[], None, false) };
|
||||
let (_, ov) = snap(&t, &Leave::segment(&c, Point::new(300.0, 160.0), false));
|
||||
assert_eq!(labels(&ov), ["perpendicular"]);
|
||||
let (_, ov) = snap(&t, &Leave::diagonal(Point::new(300.0, 160.0), false));
|
||||
assert!(!labels(&ov).contains(&"perpendicular"), "{ov:?}");
|
||||
// 70 short segments near the pointer, none square to the leave point, then the rect's side.
|
||||
let mut busy = t;
|
||||
let mut segments: Vec<(Rect, PathSeg)> = (0..70)
|
||||
.map(|i| {
|
||||
let y = 160.0 + f64::from(i) * 0.01;
|
||||
(Rect::new(199.0, y, 205.0, y + 0.001), PathSeg::Line(Line::new((199.0, y), (205.0, y + 0.001))))
|
||||
})
|
||||
.collect();
|
||||
segments.extend(busy.segments.iter().cloned());
|
||||
busy.segments = segments;
|
||||
let (_, ov) = snap(&busy, &Leave::segment(&c, Point::new(300.0, 160.0), false));
|
||||
assert_eq!(labels(&ov), ["perpendicular"]);
|
||||
}
|
||||
|
||||
/// The angle sets of Preferences › Smart Guides › Construction Guides.
|
||||
#[test]
|
||||
fn construction_angle_sets() {
|
||||
|
||||
@@ -252,6 +252,11 @@ pub struct ToolContext<'a> {
|
||||
/// points (a transform's reference point) land on anchors and ruler guides within
|
||||
/// [`Self::snap_tolerance`].
|
||||
pub snap_to_point: bool,
|
||||
/// View → Snapping → Snap to Tangent: with Smart Guides on, a line drawn
|
||||
/// from an anchor lands where it touches a nearby curve.
|
||||
pub snap_tangent: bool,
|
||||
/// View → Snapping → Snap to Perpendicular: likewise where it meets a nearby segment square.
|
||||
pub snap_perpendicular: bool,
|
||||
/// View → Snap to Glyph: drawn points snap to live-text baselines and glyph bounds (with Smart Guides).
|
||||
pub snap_to_glyph: bool,
|
||||
/// View → Show Corner Widget: paths show draggable Live Corners widgets in their corners.
|
||||
@@ -1003,6 +1008,8 @@ pub(crate) mod testutil {
|
||||
show_bbox: true,
|
||||
snap_to_pixel: false,
|
||||
snap_to_point: true,
|
||||
snap_tangent: true,
|
||||
snap_perpendicular: true,
|
||||
snap_to_glyph: false,
|
||||
corner_widgets: true,
|
||||
fill_active: true,
|
||||
|
||||
@@ -190,7 +190,10 @@ impl Tool for PenTool {
|
||||
}
|
||||
// The path being drawn moves its bounds as it grows: only its anchors and segments pull.
|
||||
let drawn = active.map(|a| a.0);
|
||||
let from = active.map(|(_, _, last, _)| Leave::segment(cx, last, ev.mods.shift));
|
||||
let from = active.map(|(_, _, last, handle)| {
|
||||
let leave = Leave::segment(cx, last, ev.mods.shift);
|
||||
if handle == last { leave } else { leave.without_contact() }
|
||||
});
|
||||
let p = match ev.kind {
|
||||
PointerKind::Move => self.snap.hover(cx, ev.pos, drawn.as_slice(), from.as_ref()),
|
||||
PointerKind::Down => self.snap.press(cx, ev.pos, drawn.as_slice(), from.as_ref()),
|
||||
|
||||
@@ -4132,6 +4132,37 @@ mod tests {
|
||||
assert_eq!(edges(&mut app), active(2), "Artboard 3 is the active one of the two selected");
|
||||
}
|
||||
|
||||
// Regression test for #824: with the Artboard tool, the active artboard's name was drawn twice,
|
||||
// once by the canvas as for every artboard and once, a little higher and in blue, by the tool.
|
||||
// Now each artboard is named once, and the active one's name sits where the others' do.
|
||||
#[test]
|
||||
fn the_artboard_tool_names_its_active_artboard_once() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
app.select_tool("artboard");
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let drawn = shapes(&mut app, &ctx);
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
// Each name drawn: how far its left edge is right of the artboard's corner, and its bottom above it.
|
||||
let named = |name: &str, board: usize| -> Vec<(f32, f32)> {
|
||||
let r = app.session.active().unwrap().doc.artboards[board].rect;
|
||||
let corner = xf.to_screen(Point::new(r.x0, r.y0));
|
||||
drawn
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Shape::Text(t) if t.galley.text() == name => Some((t.pos.x - corner.x, corner.y - (t.pos.y + t.galley.size().y))),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let (active, other) = (named("01 - Artboard 1", 0), named("02 - Artboard 2", 1));
|
||||
assert_eq!(other.len(), 1, "the other artboard is named once: {other:?}");
|
||||
assert_eq!(active.len(), 1, "the active artboard is named once: {active:?}");
|
||||
assert!((active[0].0 - other[0].0).abs() < 0.6, "flush with the artboard's left edge like the other name: {active:?} vs {other:?}");
|
||||
assert!((active[0].1 - other[0].1).abs() < 2.0, "on the artboard's top edge like the other name: {active:?} vs {other:?}");
|
||||
}
|
||||
|
||||
/// Enable Touch Gestures (#585): a two-finger tap undoes and a three-finger one redoes, and the
|
||||
/// first finger's press (the pointer egui makes of it) draws nothing. Off, a tap does nothing.
|
||||
#[test]
|
||||
|
||||
@@ -215,6 +215,35 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon
|
||||
/// The id of the Control bar's isolation button.
|
||||
const ISOLATION_BUTTON: &str = "cb-isolation";
|
||||
|
||||
/// The room the Control bar needs for the Snapping menu next to the Artboard tool's controls; with
|
||||
/// less, the menu is left out so those controls still fit the narrowest window.
|
||||
const ARTBOARD_SNAPPING_WIDTH: f32 = 900.0;
|
||||
|
||||
/// The Control bar's snapping quick access; every change uses its existing command.
|
||||
fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.menu_button(tl!("Snapping"), |ui| {
|
||||
for (label, cmd, on) in [
|
||||
(tl!("Smart Guides"), "view.smartGuides", app.ui.view.smart_guides),
|
||||
(tl!("Snap to Point"), "view.snapToPoint", app.ui.view.snap_to_point),
|
||||
(tl!("Snap to Grid"), "view.snapToGrid", app.ui.view.snap_to_grid),
|
||||
(tl!("Snap to Pixel"), "view.snapToPixel", app.ui.view.snap_to_pixel),
|
||||
] {
|
||||
if widgets::check(ui, label, on, true) {
|
||||
crate::menus::invoke(app, cmd, json!({}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
for (key, label, on) in [
|
||||
("snapTangent", tl!("Snap to Tangent"), app.session.prefs.snap_tangent),
|
||||
("snapPerpendicular", tl!("Snap to Perpendicular"), app.session.prefs.snap_perpendicular),
|
||||
] {
|
||||
if widgets::check(ui, label, on, true) {
|
||||
crate::menus::invoke(app, "prefs.set", json!({"key": key, "value": !on}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The Control bar's isolation button. In isolation mode it is Exit Isolation Mode, except while a
|
||||
/// pattern is edited (the isolation bar's Done and Cancel end that). Otherwise, with one object
|
||||
/// selected that [`vectorcraft_tools::select::isolates`], it is Isolate Selected Object, which
|
||||
@@ -258,10 +287,15 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
for i in 0..5 {
|
||||
ui.painter().circle_filled(g.center_top() + vec2(0.0, 2.0 + i as f32 * 4.0), 0.9, t.text_disabled);
|
||||
}
|
||||
let Some(st) = app.session.active() else {
|
||||
if app.session.active().is_none() {
|
||||
ui.label(egui::RichText::new(tl!("No Document")).color(t.text_dim));
|
||||
return;
|
||||
};
|
||||
}
|
||||
// The Artboard tool's controls fill the narrowest window, so they keep it to themselves there.
|
||||
if app.session.tool_id() != "artboard" || ui.available_width() >= ARTBOARD_SNAPPING_WIDTH {
|
||||
snapping_menu(app, ui);
|
||||
}
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let sel = st.selection.objects.clone();
|
||||
let units = app.session.general_unit();
|
||||
let first = sel.first().and_then(|id| st.doc.node(*id)).cloned();
|
||||
|
||||
@@ -241,8 +241,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
entries.insert(0, p);
|
||||
// Fitting changes the artboard around existing art; it must never move that art.
|
||||
let common = json!({"moveArt": !d.bool("__fit") && crate::panels::artboards::move_art(app)});
|
||||
// Fitting changes the artboard around existing art; it must neither move nor scale that art.
|
||||
let common = json!({
|
||||
"scaleArt": !d.bool("__fit") && crate::panels::artboards::scale_art(app),
|
||||
"moveArt": !d.bool("__fit") && crate::panels::artboards::move_art(app),
|
||||
});
|
||||
let p = crate::panels::artboards::set_props_params(common, entries).ok_or("no artboard")?;
|
||||
run_and_close(app, "artboard.setProps", p)
|
||||
}
|
||||
|
||||
@@ -894,3 +894,38 @@ mod typed_number_tests {
|
||||
assert!(typed_number(1e20).is_f64());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod selected_text_tests {
|
||||
use super::*;
|
||||
use crate::widgets::look_tests::{frame, glyph_colours, themed};
|
||||
|
||||
// Regression test for #1465: selected text in a dialog's text field was in the accent, on a
|
||||
// selection tinted with the same accent. It is in the strong text colour.
|
||||
#[test]
|
||||
fn selected_text_in_a_dialog_text_field_is_in_the_strong_text_colour() {
|
||||
for brightness in crate::theme::Brightness::ALL {
|
||||
let ctx = themed(brightness);
|
||||
let t = Tokens::get(&ctx);
|
||||
let mut d = Dialog::new("test", json!({"name": "Artboard 1"}));
|
||||
let id = std::cell::Cell::new(egui::Id::NULL);
|
||||
let mut add = |ui: &mut egui::Ui| {
|
||||
id.set(ui.id().with(("dlg-text", "name")));
|
||||
text_edit(ui, &mut d, "name", 120.0);
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
// Focus the field and select all of its text.
|
||||
ctx.memory_mut(|m| m.request_focus(id.get()));
|
||||
frame(&ctx, 0.1, vec![], &mut add);
|
||||
let mut state = egui::TextEdit::load_state(&ctx, id.get()).unwrap_or_default();
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(10))));
|
||||
state.store(&ctx, id.get());
|
||||
let shapes = frame(&ctx, 0.2, vec![], &mut add);
|
||||
let colours = glyph_colours(&shapes);
|
||||
assert!(!colours.is_empty(), "{brightness:?}: the text is drawn");
|
||||
let mut used = colours.clone();
|
||||
used.dedup();
|
||||
assert_eq!(used, [t.text_strong], "{brightness:?}: selected text in {used:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1843,6 +1843,9 @@ fn artboard_options_fit_drafts_cancel_and_apply_without_moving_art() {
|
||||
let mut app = app();
|
||||
app.run("shape.rectangle", json!({"x":30,"y":40,"width":80,"height":60})).unwrap();
|
||||
app.run("paint.setStroke", json!({"none":true})).unwrap();
|
||||
app.select_tool("artboard");
|
||||
app.session.set_tool_option("scaleArt", &json!(true));
|
||||
app.session.set_tool_option("moveArt", &json!(true));
|
||||
let before = app.session.doc().unwrap().doc.clone();
|
||||
for apply in [false, true] {
|
||||
artboard_options::open(&mut app).unwrap();
|
||||
@@ -1865,6 +1868,54 @@ fn artboard_options_fit_drafts_cancel_and_apply_without_moving_art() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Size edits honor the live tool switch; drafts/cancel and one-step history remain intact.
|
||||
#[test]
|
||||
fn artboard_options_size_changes_honor_scale_artwork() {
|
||||
for scale in [false, true] {
|
||||
for (choice, width, height) in
|
||||
[(json!(null), 400.0, 200.0), (json!({"preset":[612.0,792.0]}), 792.0, 612.0), (json!({"landscape":false}), 100.0, 200.0)]
|
||||
{
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({"width":200,"height":100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x":20,"y":10,"width":40,"height":20})).unwrap();
|
||||
app.run("paint.setStroke", json!({"none":true})).unwrap();
|
||||
app.select_tool("artboard");
|
||||
app.session.set_tool_option("scaleArt", &json!(scale));
|
||||
let before = app.session.doc().unwrap().doc.clone();
|
||||
for apply in [false, true] {
|
||||
artboard_options::open(&mut app).unwrap();
|
||||
let draft = app.ui.dialog.as_mut().unwrap();
|
||||
draft.fields.insert("width".into(), json!(width));
|
||||
draft.fields.insert("height".into(), json!(height));
|
||||
if !choice.is_null() {
|
||||
draft.fields.insert("__sizeChoice".into(), choice.clone());
|
||||
}
|
||||
assert_eq!(app.session.doc().unwrap().doc, before, "size change remains a draft");
|
||||
if !apply {
|
||||
cancel(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
continue;
|
||||
}
|
||||
let steps = app.session.doc().unwrap().history.undo.len();
|
||||
confirm(&mut app).unwrap();
|
||||
let after = app.session.doc().unwrap().doc.clone();
|
||||
let bounds = vectorcraft_render::encode::art_bounds(&after).unwrap();
|
||||
let (sx, sy) = if scale { (width / 200.0, height / 100.0) } else { (1.0, 1.0) };
|
||||
for (actual, expected) in [(bounds.x0, 20.0 * sx), (bounds.y0, 10.0 * sy), (bounds.x1, 60.0 * sx), (bounds.y1, 30.0 * sy)] {
|
||||
assert!((actual - expected).abs() < 1e-6, "{actual} != {expected}, scale={scale}, choice={choice}");
|
||||
}
|
||||
assert_eq!((after.artboards[0].rect.width(), after.artboards[0].rect.height()), (width, height));
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
app.run("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc, after);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_options_shared_preset_drafts_and_resizes_selected_boards_in_their_orientations() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -5307,6 +5307,10 @@ theme Appearance Външен вид
|
||||
Persistent Постоянна
|
||||
Locate Library… Намиране на библиотека…
|
||||
Library Panel Options Опции на панела с библиотека
|
||||
Snapping Прилепване
|
||||
Snap to Tangent Прилепване към допирателна
|
||||
Snap to Perpendicular Прилепване към перпендикуляр
|
||||
@msg unknown snap option `{key}` (use {options}) неизвестна опция за прилепване `{key}` (използвайте {options})
|
||||
Gap Length: Дължина на пропуска:
|
||||
Artboard {n} of {total} Работна област {n} от {total}
|
||||
Encoding and writing the file… Кодиране и записване на файла…
|
||||
@@ -5357,6 +5361,7 @@ theme Appearance Външен вид
|
||||
Water Paper Мокра хартия
|
||||
Ruby… Руби…
|
||||
Ruby Руби
|
||||
Geometric Guides Геометрични водачи
|
||||
Ease In Плавно начало
|
||||
Ease Out Плавен край
|
||||
Ease In Out Плавно начало и край
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4627,6 +4627,7 @@ imageTrace Outline Obrys
|
||||
@msg {_1} font families available Dostupné rodiny písem: {_1}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} je živý efekt (Efekt › Zásuvné moduly)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} je exportní zásuvný modul (Soubor › Export › Exportovat jako…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` má {size} bajtů (limit {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} už používá {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show propojené soubory ({_1}) zde nelze přečíst: zobrazují se jejich náhledy
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions propojené obrázky ({_1}) se na disku změnily: nové verze zobrazí Aktualizovat propojení
|
||||
@@ -5352,6 +5353,10 @@ mark-style Japanese Japonské
|
||||
@msg too many library panels were opened in this session v této relaci bylo otevřeno příliš mnoho panelů knihoven
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Obraz má {_1} × {_2} pixelů, na jedné straně více než {LARGE_TRACE_SIDE}: vektorizuje se, ale pomaleji. Rychleji se vektorizuje s předvolbou nižší věrnosti nebo menší kopie obrazu.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Obraz byl vektorizován v rozlišení {_1} × {_2} pixelů, zmenšený z {_3} × {_4} (nejvýše {_5} megapixelů).
|
||||
Snapping Přichytávání
|
||||
Snap to Tangent Přichytávat k tečně
|
||||
Snap to Perpendicular Přichytávat ke kolmici
|
||||
@msg unknown snap option `{key}` (use {options}) neznámá možnost přichytávání `{key}` (použijte {options})
|
||||
Gap Length: Délka mezery:
|
||||
Artboard {n} of {total} Pracovní plocha {n} z {total}
|
||||
Encoding and writing the file… Kódování a zápis souboru…
|
||||
@@ -5402,6 +5407,7 @@ mark-style Japanese Japonské
|
||||
Water Paper Mokrý papír
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometrická vodítka
|
||||
Ease In Pozvolný začátek
|
||||
Ease Out Pozvolný konec
|
||||
Ease In Out Pozvolný začátek a konec
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -5303,6 +5303,10 @@ swatch Bright Violet Kraftig violet
|
||||
Persistent Vedvarende
|
||||
Locate Library… Lokalisér bibliotek…
|
||||
Library Panel Options Indstillinger for bibliotekspanel
|
||||
Snapping Fastgørelse
|
||||
Snap to Tangent Fastgør til tangent
|
||||
Snap to Perpendicular Fastgør vinkelret
|
||||
@msg unknown snap option `{key}` (use {options}) ukendt fastgørelsesindstilling `{key}` (brug {options})
|
||||
Gap Length: Hullængde:
|
||||
Artboard {n} of {total} Tegneflade {n} af {total}
|
||||
Encoding and writing the file… Koder og skriver filen…
|
||||
@@ -5373,6 +5377,7 @@ swatch Bright Violet Kraftig violet
|
||||
Water Paper Vådt papir
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometriske hjælpelinjer
|
||||
Ease In Langsom start
|
||||
Ease Out Langsom slutning
|
||||
Ease In Out Langsom start og slutning
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4250,6 +4250,7 @@ theme Appearance Erscheinungsbild
|
||||
@msg {_1} font families available {_1} Schriftfamilien verfügbar
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} ist ein Live-Effekt (Effekt › Plug-ins)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} ist ein Export-Plug-in (Datei › Exportieren › Exportieren als…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ist {size} Byte groß (Grenze {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} wird bereits von {_2} verwendet
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} verknüpfte Datei(en) können hier nicht gelesen werden: Ihre Vorschauen werden angezeigt
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} verknüpfte(s) Bild(er) wurde(n) auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neuen Versionen
|
||||
@@ -4932,6 +4933,10 @@ effect Soft Weich
|
||||
@msg too many library panels were opened in this session in dieser Sitzung wurden zu viele Bibliotheksbedienfelder geöffnet
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Das Bild hat {_1} × {_2} Pixel, mehr als {LARGE_TRACE_SIDE} auf einer Seite: Es wird nachgezeichnet, aber langsamer. Eine Vorgabe mit geringerer Detailtreue oder eine kleinere Kopie des Bildes geht schneller.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Das Bild wurde mit {_1} × {_2} Pixeln nachgezeichnet, verkleinert von {_3} × {_4} (höchstens {_5} Megapixel).
|
||||
Snapping Einrasten
|
||||
Snap to Tangent An Tangente ausrichten
|
||||
Snap to Perpendicular An Senkrechter ausrichten
|
||||
@msg unknown snap option `{key}` (use {options}) unbekannte Einrastoption `{key}` (möglich: {options})
|
||||
Gap Length: Lückenlänge:
|
||||
Artboard {n} of {total} Zeichenfläche {n} von {total}
|
||||
Encoding and writing the file… Datei wird codiert und geschrieben…
|
||||
@@ -4983,6 +4988,7 @@ effect Soft Weich
|
||||
Water Paper Feuchtes Papier
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometrische Hilfslinien
|
||||
Ease In Langsam starten
|
||||
Ease Out Langsam enden
|
||||
Ease In Out Langsam starten und enden
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4298,6 +4298,7 @@ theme Appearance Εμφάνιση
|
||||
@msg {_1} font families available {_1} διαθέσιμες οικογένειες γραμματοσειρών
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) το {_1} είναι δυναμικό εφέ (Εφέ › Πρόσθετα)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) το {_1} είναι πρόσθετο εξαγωγής (Αρχείο › Εξαγωγή › Εξαγωγή ως…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) το `documentData` έχει {size} byte (όριο {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} το {_1} χρησιμοποιείται ήδη από το {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} συνδεδεμένα αρχεία δεν μπορούν να διαβαστούν εδώ: εμφανίζονται οι προεπισκοπήσεις τους
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} συνδεδεμένες εικόνες άλλαξαν στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τις νέες εκδόσεις
|
||||
@@ -5304,6 +5305,10 @@ effect Points Σημεία
|
||||
@msg too many library panels were opened in this session άνοιξαν πάρα πολλοί πίνακες βιβλιοθηκών σε αυτή τη συνεδρία
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Η εικόνα είναι {_1} × {_2} εικονοστοιχεία, πάνω από {LARGE_TRACE_SIDE} σε μία πλευρά: ανιχνεύεται, αλλά πιο αργά. Μια προρύθμιση χαμηλότερης πιστότητας ή ένα μικρότερο αντίγραφο της εικόνας ανιχνεύεται γρηγορότερα.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Η εικόνα ανιχνεύτηκε σε {_1} × {_2} εικονοστοιχεία, σμικρυμένη από {_3} × {_4} (το πολύ {_5} megapixel).
|
||||
Snapping Προσκόλληση
|
||||
Snap to Tangent Προσκόλληση σε εφαπτομένη
|
||||
Snap to Perpendicular Προσκόλληση σε κάθετο
|
||||
@msg unknown snap option `{key}` (use {options}) άγνωστη επιλογή προσκόλλησης `{key}` (χρησιμοποιήστε {options})
|
||||
Gap Length: Μήκος κενού:
|
||||
Artboard {n} of {total} Πίνακας σχεδίασης {n} από {total}
|
||||
Encoding and writing the file… Κωδικοποίηση και εγγραφή του αρχείου…
|
||||
@@ -5354,6 +5359,7 @@ effect Points Σημεία
|
||||
Water Paper Βρεγμένο χαρτί
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Γεωμετρικοί οδηγοί
|
||||
Ease In Ομαλή αρχή
|
||||
Ease Out Ομαλό τέλος
|
||||
Ease In Out Ομαλή αρχή και τέλος
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2045 and column 19.
|
@@ -4325,6 +4325,7 @@ axis Both Ambos
|
||||
@msg {_1} font families available {_1} familias de fuentes disponibles
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} es un efecto interactivo (Efecto › Plugins)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} es un plugin de exportación (Archivo › Exportar › Exportar como…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ocupa {size} bytes (límite {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} ya lo usa {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show aquí no se pueden leer {_1} archivo(s) vinculado(s): se muestran sus previsualizaciones
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imagen(es) vinculada(s) cambiaron en el disco: Actualizar vínculos muestra las versiones nuevas
|
||||
@@ -5294,6 +5295,10 @@ mark-style Japanese Japonesas
|
||||
@msg too many library panels were opened in this session se abrieron demasiados paneles de biblioteca en esta sesión
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. La imagen tiene {_1} × {_2} píxeles, más de {LARGE_TRACE_SIDE} en un lado: se calcará, pero más despacio. Un ajuste preestablecido de menor fidelidad o una copia más pequeña de la imagen se calcan más rápido.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). La imagen se calcó a {_1} × {_2} píxeles, reducida desde {_3} × {_4} ({_5} megapíxeles como máximo).
|
||||
Snapping Ajuste
|
||||
Snap to Tangent Ajustar a tangente
|
||||
Snap to Perpendicular Ajustar a perpendicular
|
||||
@msg unknown snap option `{key}` (use {options}) opción de ajuste desconocida `{key}` (use {options})
|
||||
Gap Length: Longitud del hueco:
|
||||
Artboard {n} of {total} Mesa de trabajo {n} de {total}
|
||||
Encoding and writing the file… Codificando y escribiendo el archivo…
|
||||
@@ -5344,6 +5349,7 @@ mark-style Japanese Japonesas
|
||||
Water Paper Papel mojado
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Guías geométricas
|
||||
Ease In Entrada suave
|
||||
Ease Out Salida suave
|
||||
Ease In Out Entrada y salida suaves
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4534,6 +4534,7 @@ imageTrace Outline Ääriviiva
|
||||
@msg {_1} font families available {_1} fonttiperhettä käytettävissä
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} on live-tehoste (Tehoste › Laajennukset)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} on vientilaajennus (Tiedosto › Vie › Vie muodossa…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` on {size} tavua (raja {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} on jo käytössä kohteella {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} linkitettyä tiedostoa ei voi lukea täällä: niiden esikatselut näytetään
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} linkitettyä kuvaa muuttui levyllä: Päivitä linkit näyttää uudet versiot
|
||||
@@ -5316,6 +5317,10 @@ mark-style Japanese Japanilainen
|
||||
@msg too many library panels were opened in this session tässä istunnossa on avattu liian monta kirjastopaneelia
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Kuva on {_1} × {_2} kuvapistettä, yhdeltä sivultaan yli {LARGE_TRACE_SIDE}: se jäljitetään, mutta hitaammin. Pienemmän tarkkuuden esiasetus tai kuvan pienempi kopio jäljittyy nopeammin.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Kuva jäljitettiin kokoon {_1} × {_2} kuvapistettä pienennettynä koosta {_3} × {_4} (enintään {_5} megapikseliä).
|
||||
Snapping Tartunta
|
||||
Snap to Tangent Kohdista tangenttiin
|
||||
Snap to Perpendicular Kohdista kohtisuoraan
|
||||
@msg unknown snap option `{key}` (use {options}) tuntematon tartuntavalinta `{key}` (käytä: {options})
|
||||
Gap Length: Aukon pituus:
|
||||
Artboard {n} of {total} Piirtoalusta {n}/{total}
|
||||
Encoding and writing the file… Tiedostoa koodataan ja kirjoitetaan…
|
||||
@@ -5433,6 +5438,7 @@ swatch Bright Violet Kirkas violetti
|
||||
Water Paper Märkä paperi
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometriset apuviivat
|
||||
Ease In Hidas alku
|
||||
Ease Out Hidas loppu
|
||||
Ease In Out Hidas alku ja loppu
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4322,6 +4322,7 @@ axis Both Les deux
|
||||
@msg {_1} font families available {_1} familles de polices disponibles
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} est un effet dynamique (Effet › Plug-ins)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} est un module externe d’exportation (Fichier › Exporter › Exporter sous…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` fait {size} octets (limite {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} est déjà utilisé par {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} fichier(s) lié(s) illisible(s) ici : leurs aperçus sont affichés
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} image(s) liée(s) modifiée(s) sur le disque : Mettre à jour les liens affiche les nouvelles versions
|
||||
@@ -5351,6 +5352,10 @@ theme Appearance Apparence
|
||||
@msg too many library panels were opened in this session trop de panneaux de bibliothèque ont été ouverts dans cette session
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. L’image fait {_1} × {_2} pixels, plus de {LARGE_TRACE_SIDE} sur un côté : elle est vectorisée, mais plus lentement. Un paramètre prédéfini moins fidèle ou une copie plus petite de l’image se vectorise plus vite.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). L’image a été vectorisée à {_1} × {_2} pixels, réduite de {_3} × {_4} ({_5} mégapixels au plus).
|
||||
Snapping Magnétisme
|
||||
Snap to Tangent Magnétisme de la tangente
|
||||
Snap to Perpendicular Magnétisme de la perpendiculaire
|
||||
@msg unknown snap option `{key}` (use {options}) option de magnétisme inconnue `{key}` (utilisez {options})
|
||||
Gap Length: Longueur de lacune :
|
||||
Artboard {n} of {total} Plan de travail {n} sur {total}
|
||||
Encoding and writing the file… Encodage et écriture du fichier…
|
||||
@@ -5401,6 +5406,7 @@ theme Appearance Apparence
|
||||
Water Paper Papier humide
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Repères géométriques
|
||||
Ease In Accélération progressive
|
||||
Ease Out Décélération progressive
|
||||
Ease In Out Accélération et décélération
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -5083,6 +5083,7 @@ imageTrace Outline Körvonal
|
||||
@msg {_1} has no {_2} style ennek nincs ilyen stílusa: {_1} ({_2})
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) élő effektus: {_1} (Effektus › Bővítmények)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) exportáló bővítmény: {_1} (Fájl › Exportálás › Exportálás másként…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) a `documentData` mérete {size} bájt (korlát: {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} már foglalt: {_1} (használja: {_2})
|
||||
@msg {_1} linked file(s) can't be read here: their previews show Itt nem olvasható csatolt fájlok: {_1}; az előnézetük látszik
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions A lemezen módosult csatolt képek: {_1}; a Csatolások frissítése az új változatokat mutatja
|
||||
@@ -5338,6 +5339,10 @@ imageTrace Outline Körvonal
|
||||
@msg too many library panels were opened in this session ebben a munkamenetben túl sok könyvtárpanel nyílt meg
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. A kép {_1} × {_2} képpont, egyik oldalán több mint {LARGE_TRACE_SIDE}: a vektorizálás megtörténik, de lassabban. Kisebb hűségű előbeállítással vagy a kép kisebb másolatával gyorsabb.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). A kép vektorizálása {_1} × {_2} képponton történt, {_3} × {_4} méretről kicsinyítve (legfeljebb {_5} megapixel).
|
||||
Snapping Illesztés
|
||||
Snap to Tangent Illesztés érintőre
|
||||
Snap to Perpendicular Illesztés merőlegesre
|
||||
@msg unknown snap option `{key}` (use {options}) ismeretlen illesztési beállítás: `{key}` (használható: {options})
|
||||
Gap Length: Rés hossza:
|
||||
Artboard {n} of {total} Rajztábla: {n} / {total}
|
||||
Encoding and writing the file… A fájl kódolása és írása…
|
||||
@@ -5388,6 +5393,7 @@ imageTrace Outline Körvonal
|
||||
Water Paper Nedves papír
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometriai segédvonalak
|
||||
Ease In Lassú kezdés
|
||||
Ease Out Lassú befejezés
|
||||
Ease In Out Lassú kezdés és befejezés
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -5303,6 +5303,10 @@ swatch Bright Violet Violet cerah
|
||||
Persistent Persisten
|
||||
Locate Library… Temukan pustaka…
|
||||
Library Panel Options Opsi panel pustaka
|
||||
Snapping Snap
|
||||
Snap to Tangent Snap ke garis singgung
|
||||
Snap to Perpendicular Snap tegak lurus
|
||||
@msg unknown snap option `{key}` (use {options}) opsi snap `{key}` tidak dikenal (gunakan {options})
|
||||
Gap Length: Panjang celah:
|
||||
Artboard {n} of {total} Artboard {n} dari {total}
|
||||
Encoding and writing the file… Mengodekan dan menulis berkas…
|
||||
@@ -5373,6 +5377,7 @@ swatch Bright Violet Violet cerah
|
||||
Water Paper Kertas Basah
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Panduan Geometris
|
||||
Ease In Awal Lambat
|
||||
Ease Out Akhir Lambat
|
||||
Ease In Out Awal dan Akhir Lambat
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 3816 and column 19.
|
@@ -4365,6 +4365,7 @@ axis Both Entrambi
|
||||
@msg {_1} font families available {_1} famiglie di font disponibili
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} è un effetto dinamico (Effetto › Plug-in)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} è un plug-in di esportazione (File › Esporta › Esporta come…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` occupa {size} byte (limite {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} è già usato da {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show file collegati non leggibili qui: {_1}; vengono mostrate le loro anteprime
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions immagini collegate modificate su disco: {_1}; Aggiorna collegamenti mostra le nuove versioni
|
||||
@@ -4966,6 +4967,10 @@ lighting Light Luce
|
||||
@msg too many library panels were opened in this session in questa sessione sono stati aperti troppi pannelli libreria
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. L’immagine è di {_1} × {_2} pixel, più di {LARGE_TRACE_SIDE} su un lato: viene vettorializzata, ma più lentamente. Un predefinito a fedeltà più bassa o una copia più piccola dell’immagine è più veloce.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). L’immagine è stata vettorializzata a {_1} × {_2} pixel, ridotta da {_3} × {_4} (al massimo {_5} megapixel).
|
||||
Snapping Aggancio
|
||||
Snap to Tangent Aggancia alla tangente
|
||||
Snap to Perpendicular Aggancia alla perpendicolare
|
||||
@msg unknown snap option `{key}` (use {options}) opzione di aggancio sconosciuta `{key}` (usare {options})
|
||||
Gap Length: Lunghezza lacuna:
|
||||
Artboard {n} of {total} Tavola da disegno {n} di {total}
|
||||
Encoding and writing the file… Codifica e scrittura del file…
|
||||
@@ -5017,6 +5022,7 @@ lighting Light Luce
|
||||
Water Paper Carta bagnata
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Guide geometriche
|
||||
Ease In Inizio graduale
|
||||
Ease Out Fine graduale
|
||||
Ease In Out Inizio e fine graduali
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4355,6 +4355,7 @@ swatch Bright Violet ビビッドバイオレット
|
||||
@msg no plug-in {id} is installed プラグイン {id} はインストールされていません
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} はライブ効果です (「効果 › プラグイン」から使用してください)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} は書き出しプラグインです (「ファイル › 書き出し › 形式を指定して書き出し…」から使用してください)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` は {size} バイトです (上限 {MAX_DOCUMENT_DATA})
|
||||
@msg a preset named `{_1}` exists `{_1}` という名前のプリセットはすでに存在します
|
||||
@msg a swatch or color group named `{n}` exists `{n}` という名前のスウォッチまたはカラーグループはすでに存在します
|
||||
@msg no print preset named `{base}` `{base}` という名前のプリントプリセットが見つかりません
|
||||
@@ -5006,6 +5007,10 @@ lighting Light ライト
|
||||
@msg too many library panels were opened in this session このセッションで開いたライブラリパネルが多すぎます
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. 画像は {_1} × {_2} ピクセルで、一辺が {LARGE_TRACE_SIDE} を超えています。トレースはできますが、時間がかかります。忠実度の低いプリセットや画像の小さいコピーを使うと速くなります。
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). 画像は {_3} × {_4} から縮小した {_1} × {_2} ピクセルでトレースされました (最大 {_5} メガピクセル)。
|
||||
Snapping スナップ
|
||||
Snap to Tangent 接線にスナップ
|
||||
Snap to Perpendicular 垂線にスナップ
|
||||
@msg unknown snap option `{key}` (use {options}) 不明なスナップオプション `{key}` ({options} を使用してください)
|
||||
Gap Length: ギャップの長さ:
|
||||
Artboard {n} of {total} アートボード {n} / {total}
|
||||
Encoding and writing the file… ファイルをエンコードして書き込み中…
|
||||
@@ -5064,6 +5069,7 @@ lighting Light ライト
|
||||
Yonroku-ban 四六判
|
||||
Ruby… ルビ…
|
||||
Ruby ルビ
|
||||
Geometric Guides 幾何ガイド
|
||||
Ease In イーズイン
|
||||
Ease Out イーズアウト
|
||||
Ease In Out イーズインアウト
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4083,6 +4083,7 @@ effect Regular ჩვეულებრივი
|
||||
@msg {_1} font families available ხელმისაწვდომი შრიფტების ოჯახები: {_1}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} ცოცხალი ეფექტია (ეფექტი › პლაგინები)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} ექსპორტის პლაგინია (ფაილი › ექსპორტირება › ექსპორტირება ფორმატში…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` {size} ბაიტია (ლიმიტი {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} უკვე გამოიყენება აქ: {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show მიბმული ფაილების წაკითხვა აქ ვერ ხერხდება ({_1}): ჩანს მათი გადახედვა
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions მიბმული გამოსახულებები შეიცვალა დისკზე ({_1}): ბმულების განახლება აჩვენებს ახალ ვერსიებს
|
||||
@@ -4403,7 +4404,7 @@ effect Regular ჩვეულებრივი
|
||||
High Contrast 3 მაღალი კონტრასტი 3
|
||||
Pentagram პენტაგრამა
|
||||
Perceptual აღქმითი
|
||||
Relative Colorimetric შეფარდებით კოლორიმეტრული
|
||||
Relative Colorimetric ფარდობითი კოლორიმეტრიული
|
||||
Absolute Colorimetric აბსოლუტური კოლორიმეტრიული
|
||||
Exact ზუსტი
|
||||
Preserve Tints ტონირებების შენარჩუნება
|
||||
@@ -5257,6 +5258,10 @@ imageTrace Outline კონტური
|
||||
# Select by Color (select.color)
|
||||
Select by Color მონიშვნა ფერის მიხედვით
|
||||
@msg thumbnail: no page {n} (the file has 1) thumbnail: გვერდი {n} არ არსებობს (ფაილს 1 გვერდი აქვს)
|
||||
Snapping მიბმა
|
||||
Snap to Tangent მხებზე მიბმა
|
||||
Snap to Perpendicular პერპენდიკულარზე მიბმა
|
||||
@msg unknown snap option `{key}` (use {options}) უცნობი მიბმის პარამეტრი `{key}` (გამოიყენეთ: {options})
|
||||
Gap Length: ღრეჩოს სიგრძე:
|
||||
Smudge Stick… დასაზელი ჯოხი…
|
||||
Smudge Stick დასაზელი ჯოხი
|
||||
@@ -5307,6 +5312,7 @@ imageTrace Outline კონტური
|
||||
selects several, or draws one inside an artboard) რამდენიმეს მონიშნავს ან ახალს სამუშაო დაფის შიგნით ხატავს)
|
||||
Ruby… რუბი…
|
||||
Ruby რუბი
|
||||
Geometric Guides გეომეტრიული მიმმართველები
|
||||
Ease In ნელი დასაწყისი
|
||||
Ease Out ნელი დასასრული
|
||||
Ease In Out ნელი დასაწყისი და დასასრული
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4287,6 +4287,7 @@ theme Appearance 외관
|
||||
@msg no plug-in {id} is installed 플러그인 {id}이(가) 설치되어 있지 않습니다
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1}은(는) 라이브 효과입니다(효과 › 플러그인)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1}은(는) 내보내기 플러그인입니다(파일 › 내보내기 › 다른 이름으로 내보내기…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData`가 {size}바이트입니다(한도 {MAX_DOCUMENT_DATA})
|
||||
@msg a preset named `{_1}` exists `{_1}`이라는 프리셋이 이미 있습니다
|
||||
@msg a swatch or color group named `{n}` exists `{n}`이라는 견본 또는 색상 그룹이 이미 있습니다
|
||||
@msg no print preset named `{base}` `{base}`라는 인쇄 프리셋이 없습니다
|
||||
@@ -4929,6 +4930,10 @@ lighting Light 광원
|
||||
@msg too many library panels were opened in this session 이 세션에서 라이브러리 패널을 너무 많이 열었습니다
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. 이미지가 {_1} × {_2}픽셀로 한 변이 {LARGE_TRACE_SIDE}을 넘습니다. 추적은 되지만 더 느립니다. 충실도가 낮은 사전 설정이나 이미지의 작은 사본을 사용하면 더 빠릅니다.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). 이미지를 {_3} × {_4}에서 축소한 {_1} × {_2}픽셀로 추적했습니다(최대 {_5}메가픽셀).
|
||||
Snapping 스냅
|
||||
Snap to Tangent 접선에 스냅
|
||||
Snap to Perpendicular 수직선에 스냅
|
||||
@msg unknown snap option `{key}` (use {options}) 알 수 없는 스냅 옵션 `{key}` ({options} 중에서 사용하세요)
|
||||
Gap Length: 간격 길이:
|
||||
Artboard {n} of {total} 아트보드 {n} / {total}
|
||||
Encoding and writing the file… 파일을 인코딩하고 쓰는 중…
|
||||
@@ -4980,6 +4985,7 @@ lighting Light 광원
|
||||
Water Paper 물 종이
|
||||
Ruby… 루비…
|
||||
Ruby 루비
|
||||
Geometric Guides 기하학적 안내선
|
||||
Ease In 서서히 시작
|
||||
Ease Out 서서히 종료
|
||||
Ease In Out 서서히 시작 및 종료
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -5313,6 +5313,10 @@ swatch Bright Violet Felviolet
|
||||
Typing Typen
|
||||
Persistent Permanent
|
||||
Library Panel Options Opties voor bibliotheekpaneel
|
||||
Snapping Uitlijnen
|
||||
Snap to Tangent Uitlijnen op raaklijn
|
||||
Snap to Perpendicular Uitlijnen op loodlijn
|
||||
@msg unknown snap option `{key}` (use {options}) onbekende uitlijnoptie `{key}` (gebruik {options})
|
||||
Gap Length: Lengte van opening:
|
||||
Locate Library… Bibliotheek lokaliseren…
|
||||
|
||||
@@ -5416,6 +5420,7 @@ swatch Bright Violet Felviolet
|
||||
Water Paper Nat papier
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometrische hulplijnen
|
||||
Ease In Langzaam beginnen
|
||||
Ease Out Langzaam eindigen
|
||||
Ease In Out Langzaam beginnen en eindigen
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4452,6 +4452,7 @@ imageTrace Outline Kontur
|
||||
@msg {_1} font families available dostępne rodziny czcionek: {_1}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} to efekt na żywo (Efekt › Wtyczki)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} to wtyczka eksportu (Plik › Eksportuj › Eksportuj jako…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` ma {size} bajtów (limit {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} jest już używany przez {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show połączonych plików nie można tu odczytać ({_1}): wyświetlane są ich podglądy
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions połączone obrazy zmienione na dysku: {_1} — Aktualizuj łącza pokaże nowe wersje
|
||||
@@ -5204,6 +5205,10 @@ mark-style Japanese Japońskie
|
||||
@msg too many library panels were opened in this session w tej sesji otwarto zbyt wiele paneli bibliotek
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Obraz ma {_1} × {_2} pikseli, ponad {LARGE_TRACE_SIDE} na jednym boku: zostanie obrysowany, ale wolniej. Ustawienie wstępne o niższej wierności lub mniejsza kopia obrazu obrysuje się szybciej.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Obraz obrysowano w rozdzielczości {_1} × {_2} pikseli, po zmniejszeniu z {_3} × {_4} (najwyżej {_5} megapikseli).
|
||||
Snapping Przyciąganie
|
||||
Snap to Tangent Przyciągaj do stycznych
|
||||
Snap to Perpendicular Przyciągaj do prostopadłych
|
||||
@msg unknown snap option `{key}` (use {options}) nieznana opcja przyciągania `{key}` (użyj: {options})
|
||||
Gap Length: Długość przerwy:
|
||||
Artboard {n} of {total} Obszar kompozycji {n} z {total}
|
||||
Encoding and writing the file… Kodowanie i zapisywanie pliku…
|
||||
@@ -5254,6 +5259,7 @@ mark-style Japanese Japońskie
|
||||
Water Paper Mokry papier
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Prowadnice geometryczne
|
||||
Ease In Łagodny początek
|
||||
Ease Out Łagodny koniec
|
||||
Ease In Out Łagodny początek i koniec
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3898,6 +3898,7 @@ axis Both Ambos
|
||||
@msg {_1} font families available {_1} famílias de fontes disponíveis
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} é um efeito dinâmico (Efeito › Plug-ins)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} é um plug-in de exportação (Arquivo › Exportar › Exportar Como…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` tem {size} bytes (limite {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} já é usado por {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} arquivo(s) vinculado(s) não podem ser lidos aqui: suas visualizações são exibidas
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imagem(ns) vinculada(s) mudou(aram) no disco: Atualizar links mostra as novas versões
|
||||
@@ -5269,6 +5270,10 @@ mark-style Japanese Japonesas
|
||||
@msg too many library panels were opened in this session foram abertos painéis de biblioteca demais nesta sessão
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. A imagem tem {_1} × {_2} pixels, mais de {LARGE_TRACE_SIDE} em um lado: ela é traçada, mas mais devagar. Uma predefinição de menor fidelidade ou uma cópia menor da imagem traça mais rápido.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). A imagem foi traçada em {_1} × {_2} pixels, reduzida de {_3} × {_4} (no máximo {_5} megapixels).
|
||||
Snapping Ajuste
|
||||
Snap to Tangent Ajustar à Tangente
|
||||
Snap to Perpendicular Ajustar à Perpendicular
|
||||
@msg unknown snap option `{key}` (use {options}) opção de ajuste desconhecida `{key}` (use {options})
|
||||
Gap Length: Comprimento da Lacuna:
|
||||
Artboard {n} of {total} Mesa de Trabalho {n} de {total}
|
||||
Encoding and writing the file… Codificando e gravando o arquivo…
|
||||
@@ -5319,6 +5324,7 @@ mark-style Japanese Japonesas
|
||||
Water Paper Papel molhado
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Guias geométricas
|
||||
Ease In Entrada suave
|
||||
Ease Out Saída suave
|
||||
Ease In Out Entrada e saída suaves
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -4361,6 +4361,7 @@ axis Both Оба
|
||||
@msg {_1} font families available доступно семейств шрифтов: {_1}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} — динамический эффект (Эффект › Модули)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} — модуль экспорта (Файл › Экспорт › Экспортировать как…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` занимает {size} байт (предел {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} уже используется {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show здесь невозможно прочитать связанных файлов: {_1}: отображаются их предварительные просмотры
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions связанных изображений ({_1}) изменились на диске: «Обновить связи» покажет новые версии
|
||||
@@ -4962,6 +4963,10 @@ lighting Light Свет
|
||||
@msg too many library panels were opened in this session в этом сеансе открыто слишком много панелей библиотек
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Изображение {_1} × {_2} пикселей, больше {LARGE_TRACE_SIDE} по одной стороне: трассировка выполняется, но медленнее. Стиль с меньшей точностью или уменьшенная копия изображения трассируются быстрее.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Изображение трассировано в размере {_1} × {_2} пикселей, уменьшенное с {_3} × {_4} (не более {_5} мегапикселей).
|
||||
Snapping Привязка
|
||||
Snap to Tangent Привязать к касательной
|
||||
Snap to Perpendicular Привязать к перпендикуляру
|
||||
@msg unknown snap option `{key}` (use {options}) неизвестный параметр привязки `{key}` (допустимо: {options})
|
||||
Gap Length: Длина зазора:
|
||||
Artboard {n} of {total} Монтажная область {n} из {total}
|
||||
Encoding and writing the file… Кодирование и запись файла…
|
||||
@@ -5013,6 +5018,7 @@ lighting Light Свет
|
||||
Water Paper Мокрая бумага
|
||||
Ruby… Руби…
|
||||
Ruby Руби
|
||||
Geometric Guides Геометрические направляющие
|
||||
Ease In Плавное начало
|
||||
Ease Out Плавное окончание
|
||||
Ease In Out Плавное начало и окончание
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4234,6 +4234,7 @@ axis Both Båda
|
||||
@msg {_1} font families available {_1} teckensnittsfamiljer tillgängliga
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} är en live-effekt (Effekt › Insticksprogram)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} är ett exportinsticksprogram (Fil › Exportera › Exportera som…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` är {size} byte (gräns {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} används redan av {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} länkade fil(er) kan inte läsas här: deras förhandsgranskningar visas
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} länkade bild(er) har ändrats på disken: Uppdatera länkar visar de nya versionerna
|
||||
@@ -5308,6 +5309,10 @@ theme Appearance Utseende
|
||||
@msg too many library panels were opened in this session för många bibliotekspaneler har öppnats i den här sessionen
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Bilden är {_1} × {_2} pixlar, mer än {LARGE_TRACE_SIDE} på en sida: den vektoriseras, men långsammare. En förinställning med lägre återgivning eller en mindre kopia av bilden går snabbare.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Bilden vektoriserades vid {_1} × {_2} pixlar, nedskalad från {_3} × {_4} (högst {_5} megapixlar).
|
||||
Snapping Fästning
|
||||
Snap to Tangent Fäst mot tangent
|
||||
Snap to Perpendicular Fäst mot vinkelrät
|
||||
@msg unknown snap option `{key}` (use {options}) okänt fästalternativ `{key}` (använd {options})
|
||||
Gap Length: Lucklängd:
|
||||
Artboard {n} of {total} Rityta {n} av {total}
|
||||
Encoding and writing the file… Kodar och skriver filen…
|
||||
@@ -5358,6 +5363,7 @@ theme Appearance Utseende
|
||||
Water Paper Vått papper
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Geometriska stödlinjer
|
||||
Ease In Långsam start
|
||||
Ease Out Långsamt slut
|
||||
Ease In Out Långsam start och slut
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -5176,6 +5176,7 @@ theme Appearance Görünüm
|
||||
@msg select an Objects on Path group bir Yol Üzerindeki Nesneler grubu seçin
|
||||
@msg the Simplify slider is not open Basitleştirme kaydırıcısı açık değil
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} bir dışa aktarma eklentisidir (Dosya › Dışa Aktar › Farklı Dışa Aktar…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` {size} bayt (sınır {MAX_DOCUMENT_DATA})
|
||||
Alt key toggles to Smooth Tool Alt tuşu Düzleştirme Aracına geçiş yapar
|
||||
Auto-Simplify Otomatik Basitleştir
|
||||
Drag an item here, or right-click one, to put it in this group. Bu gruba eklemek için bir öğeyi buraya sürükleyin veya sağ tıklayın.
|
||||
@@ -5399,4 +5400,8 @@ axis Y Axis Y ekseni
|
||||
@msg `dither` applies to gradient fills (stroke: false) `dither` degrade dolgulara uygulanır (stroke: false)
|
||||
@msg `dither` applies to gradient fills (paint.setFill) `dither` degrade dolgulara uygulanır (paint.setFill)
|
||||
@msg `dither` must be true or false "dither" doğru veya yanlış olmalıdır
|
||||
Snapping Yaslama
|
||||
Snap to Tangent Teğete Yasla
|
||||
Snap to Perpendicular Dikeye Yasla
|
||||
Geometric Guides Geometrik Kılavuzlar
|
||||
@msg `method` must be classic or perceptual `method` classic veya perceptual olmalıdır
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -4349,6 +4349,7 @@ axis Both Обидві
|
||||
@msg {_1} font families available доступно сімейства шрифтів: {_1}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} - динамічний ефект (Ефект › Модулі)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} - модуль експорту (Файл › Експорт › Експортувати як…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` займає {size} байт (межа {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} вже використовується {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show тут неможливо прочитати пов’язані файли: {_1}: відображаються їх попередні перегляди
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions пов’язаних зображень ({_1}) змінилися на диску: «Оновити зв’язки» покаже нові версії
|
||||
@@ -4946,6 +4947,10 @@ lighting Light Світло
|
||||
@msg too many library panels were opened in this session у цьому сеансі відкрито забагато панелей бібліотек
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Зображення {_1} × {_2} пікселів, понад {LARGE_TRACE_SIDE} з одного боку: трасування виконується, але повільніше. Стиль із нижчою точністю або менша копія зображення трасуються швидше.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Зображення трасовано в розмірі {_1} × {_2} пікселів, зменшене з {_3} × {_4} (щонайбільше {_5} мегапікселів).
|
||||
Snapping Прив’язка
|
||||
Snap to Tangent Прив’язати до дотичної
|
||||
Snap to Perpendicular Прив’язати до перпендикуляра
|
||||
@msg unknown snap option `{key}` (use {options}) невідомий параметр прив’язки `{key}` (використовуйте {options})
|
||||
Gap Length: Довжина проміжку:
|
||||
Artboard {n} of {total} Монтажна область {n} з {total}
|
||||
Encoding and writing the file… Кодування та запис файлу…
|
||||
@@ -4997,6 +5002,7 @@ lighting Light Світло
|
||||
Water Paper Мокрий папір
|
||||
Ruby… Рубі…
|
||||
Ruby Рубі
|
||||
Geometric Guides Геометричні напрямні
|
||||
Ease In Плавний початок
|
||||
Ease Out Плавне завершення
|
||||
Ease In Out Плавний початок і завершення
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 733 and column 40.
|
@@ -4742,6 +4742,7 @@ theme Appearance Giao diện
|
||||
@msg {_1} has no {_2} style {_1} không có kiểu {_2}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} là hiệu ứng trực tiếp (Hiệu ứng › Plug-ins)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} là plug-in xuất (Tệp › Xuất › Xuất thành…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` có {size} byte (giới hạn {MAX_DOCUMENT_DATA})
|
||||
@msg {_1} is already used by {_2} {_1} đã được dùng bởi {_2}
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} tệp liên kết không thể đọc ở đây: bản xem trước được hiển thị
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} ảnh liên kết đã thay đổi trên đĩa: Cập nhật liên kết hiển thị phiên bản mới
|
||||
@@ -4946,6 +4947,10 @@ theme Appearance Giao diện
|
||||
@msg too many library panels were opened in this session đã mở quá nhiều bảng thư viện trong phiên này
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Ảnh có kích thước {_1} × {_2} điểm ảnh, hơn {LARGE_TRACE_SIDE} ở một cạnh: ảnh vẫn được dò, nhưng chậm hơn. Một thiết lập sẵn có độ trung thực thấp hơn hoặc một bản sao nhỏ hơn của ảnh sẽ dò nhanh hơn.
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Ảnh đã được dò ở {_1} × {_2} điểm ảnh, thu nhỏ từ {_3} × {_4} (tối đa {_5} megapixel).
|
||||
Snapping Hút
|
||||
Snap to Tangent Hút vào tiếp tuyến
|
||||
Snap to Perpendicular Hút vào đường vuông góc
|
||||
@msg unknown snap option `{key}` (use {options}) tùy chọn hút không hợp lệ `{key}` (dùng {options})
|
||||
Gap Length: Độ dài khoảng hở:
|
||||
Artboard {n} of {total} Bảng vẽ {n} / {total}
|
||||
Encoding and writing the file… Đang mã hóa và ghi tệp…
|
||||
@@ -4997,6 +5002,7 @@ theme Appearance Giao diện
|
||||
Water Paper Giấy ướt
|
||||
Ruby… Ruby…
|
||||
Ruby Ruby
|
||||
Geometric Guides Đường dẫn hình học
|
||||
Ease In Chậm lúc đầu
|
||||
Ease Out Chậm lúc cuối
|
||||
Ease In Out Chậm lúc đầu và cuối
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4030 and column 10.
|
@@ -4082,6 +4082,7 @@ imageTrace Outline 轮廓
|
||||
@msg no plug-in {id} is installed 未安装增效工具 {id}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} 是实时效果 (效果 › 增效工具)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} 是导出增效工具 (文件 › 导出 › 导出为…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` 为 {size} 字节(上限 {MAX_DOCUMENT_DATA})
|
||||
@msg a preset named `{_1}` exists 名为 `{_1}` 的预设已存在
|
||||
@msg a swatch or color group named `{n}` exists 名为 `{n}` 的色板或颜色组已存在
|
||||
@msg no print preset named `{base}` 没有名为 `{base}` 的打印预设
|
||||
@@ -5185,6 +5186,10 @@ lighting Light 光源
|
||||
@msg too many library panels were opened in this session 本次会话中打开的库面板过多
|
||||
@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. 图像为 {_1} × {_2} 像素,某一边超过 {LARGE_TRACE_SIDE}:会进行描摹,但速度较慢。使用保真度较低的预设或图像的较小副本会更快。
|
||||
@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). 图像已按 {_1} × {_2} 像素描摹,由 {_3} × {_4} 缩小而来(最多 {_5} 百万像素)。
|
||||
Snapping 对齐
|
||||
Snap to Tangent 对齐切线
|
||||
Snap to Perpendicular 对齐垂线
|
||||
@msg unknown snap option `{key}` (use {options}) 未知的对齐选项 `{key}`(可用:{options})
|
||||
Gap Length: 间隙长度:
|
||||
# Links and Attributes: files and URLs handed to other apps.
|
||||
@msg Edit Original opens image and document files only; “{name}” is not one 编辑原稿只能打开图像和文档文件;“{name}” 不是其中之一
|
||||
@@ -5241,6 +5246,7 @@ lighting Light 光源
|
||||
Water Paper 水彩画纸
|
||||
Ruby… 注音…
|
||||
Ruby 注音
|
||||
Geometric Guides 几何参考线
|
||||
Ease In 缓入
|
||||
Ease Out 缓出
|
||||
Ease In Out 缓入缓出
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2068,6 +2068,7 @@ file-filter Templates 範本
|
||||
@msg no plug-in {id} is installed 未安裝增效模組 {id}
|
||||
@msg {_1} is a live effect (Effect › Plug-ins) {_1} 是即時效果 (效果 › 增效模組)
|
||||
@msg {_1} is an exporter (File › Export › Export As…) {_1} 是匯出增效模組 (檔案 › 匯出 › 匯出為…)
|
||||
@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` 為 {size} 位元組(上限 {MAX_DOCUMENT_DATA})
|
||||
@msg a preset named `{_1}` exists 名為 `{_1}` 的預設集已存在
|
||||
@msg a swatch or color group named `{n}` exists 名為 `{n}` 的色票或顏色群組已存在
|
||||
@msg no print preset named `{base}` 沒有名為 `{base}` 的列印預設集
|
||||
@@ -4980,6 +4981,10 @@ lighting Light 光源
|
||||
Persistent 持久
|
||||
Locate Library… 尋找資料庫…
|
||||
Library Panel Options 資料庫面板選項
|
||||
Snapping 靠齊
|
||||
Snap to Tangent 靠齊切線
|
||||
Snap to Perpendicular 靠齊垂線
|
||||
@msg unknown snap option `{key}` (use {options}) 未知的靠齊選項 `{key}`(可用:{options})
|
||||
Gap Length: 間隙長度:
|
||||
Artboard {n} of {total} 工作區域 {n} / {total}
|
||||
Encoding and writing the file… 正在編碼並寫入檔案…
|
||||
@@ -5036,6 +5041,7 @@ lighting Light 光源
|
||||
Water Paper 水彩畫紙
|
||||
Ruby… 注音…
|
||||
Ruby 注音
|
||||
Geometric Guides 幾何參考線
|
||||
Ease In 緩入
|
||||
Ease Out 緩出
|
||||
Ease In Out 緩入緩出
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -187,6 +187,31 @@ mod tests {
|
||||
assert!(appearance.contains("<circle") && !pathfinder.contains("<circle"), "appearance should read as a list, not overlapping squares");
|
||||
}
|
||||
|
||||
// Regression test for #479: the Add and Delete Anchor Point tools' icons were drawn apart from
|
||||
// the Pen tool's, so the three tools didn't read as one family. They are the Pen's pen with a
|
||||
// plus or a minus beside it.
|
||||
#[test]
|
||||
fn the_add_and_delete_anchor_tool_icons_are_the_pen_icon_with_a_badge() {
|
||||
let svg = |tool: &str| {
|
||||
let name = tool_icon(tool);
|
||||
let (_, bytes) =
|
||||
crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{tool} maps to {name}, which isn't an icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
};
|
||||
let shapes =
|
||||
|svg: &str| svg.lines().map(|l| l.trim().to_string()).filter(|l| l.starts_with("<path") || l.starts_with("<circle")).collect::<Vec<_>>();
|
||||
let pen = shapes(&svg("tool-pen"));
|
||||
assert!(!pen.is_empty(), "the Pen's icon has shapes");
|
||||
let (add, delete) = (shapes(&svg("tool-pen-add")), shapes(&svg("tool-pen-delete")));
|
||||
for (tool, icon) in [("tool-pen-add", &add), ("tool-pen-delete", &delete)] {
|
||||
for shape in &pen {
|
||||
assert!(icon.contains(shape), "{tool}'s icon lacks the Pen's {shape}");
|
||||
}
|
||||
assert!(icon.len() > pen.len(), "{tool}'s icon has a badge of its own");
|
||||
}
|
||||
assert_ne!(add, delete, "plus and minus differ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_catalog_preserves_fallback_and_tool_aliases() {
|
||||
let ImageSource::Bytes { uri, bytes } = source("missing-icon") else { panic!("expected SVG bytes") };
|
||||
|
||||
@@ -1372,11 +1372,14 @@ mod tests {
|
||||
bar_frame_in(&mut app, &ctx, vec![], width);
|
||||
let texts = bar_frame_in(&mut app, &ctx, vec![], width);
|
||||
assert!(has(&texts, "Scale Artwork with Artboard") && !has(&texts, "X:") && !has(&texts, "W:"), "{texts:?}");
|
||||
// The Snapping menu sits first on a wide bar and leaves the narrow bar to the artboard controls.
|
||||
assert!(has(&bar_texts(&mut app, &ctx), "Snapping"));
|
||||
// In the app's narrowest window, 800 points wide, the name and the Transform link still fit,
|
||||
// and a click on the link shows the artboard's X, Y, W and H in the Transform panel's popover.
|
||||
let narrow = |app: &mut VectorcraftApp, events| bar_frame_in(app, &ctx, events, 800.0);
|
||||
narrow(&mut app, vec![]);
|
||||
let texts = narrow(&mut app, vec![]);
|
||||
assert!(!has(&texts, "Snapping"), "{texts:?}");
|
||||
let link = text_rect(&texts, "Transform");
|
||||
assert!(link.right() < 790.0 && text_rect(&texts, "Artboard 1").right() < link.left(), "{texts:?}");
|
||||
// Move and Scale Artwork with Artboard show as their boxes alone, inside the window, and the
|
||||
|
||||
@@ -802,6 +802,25 @@ mod tests {
|
||||
assert_eq!(selected(&app), std::slice::from_ref(&mask), "Edit Clipping Path selects the clipping path");
|
||||
}
|
||||
|
||||
// Regression test for #1910: the Properties panel's flip buttons are named as the reference
|
||||
// app's Properties panel names them, not Flip Horizontal and Flip Vertical (the Transform
|
||||
// panel menu's names).
|
||||
#[test]
|
||||
fn the_flip_buttons_keep_the_reference_properties_names() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let tree = crate::widgets::accessibility_tests::tree(|ui| transform_section(&mut app, ui));
|
||||
let names: Vec<&str> = tree.iter().filter_map(|n| n.label()).collect();
|
||||
for want in ["Flip Along Horizontal Axis", "Flip Along Vertical Axis"] {
|
||||
assert!(names.contains(&want), "{want} in {names:?}");
|
||||
}
|
||||
for old in ["Flip Horizontal", "Flip Vertical"] {
|
||||
assert!(!names.contains(&old), "{old} in {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3451: the Properties panel Transform section shows ellipse pie angles and Invert Pie.
|
||||
#[test]
|
||||
fn transform_section_shows_ellipse_pie_properties() {
|
||||
|
||||
@@ -423,6 +423,20 @@ mod tests {
|
||||
use crate::Services;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
#[test]
|
||||
fn geometric_snapping_is_a_saved_smart_guides_preference() {
|
||||
let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
open(&mut a, Some("Smart Guides"));
|
||||
let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx()));
|
||||
assert!(text.contains("Geometric Guides") && text.contains("Snap to Perpendicular") && text.contains("Snap to Tangent"), "{text}");
|
||||
a.ui.dialog.as_mut().unwrap().fields.insert("snapPerpendicular".into(), json!(false));
|
||||
confirm(&mut a).unwrap();
|
||||
assert!(!a.session.prefs.snap_perpendicular && a.session.prefs.snap_tangent);
|
||||
let saved: Prefs = serde_json::from_value(a.ui.engine_prefs.clone()).unwrap();
|
||||
assert!(!saved.snap_perpendicular && saved.snap_tangent);
|
||||
assert!(a.run("view.snapping", json!({})).is_err());
|
||||
}
|
||||
|
||||
/// A resting checkbox must have a visible outline in both states and every brightness.
|
||||
#[test]
|
||||
fn preference_checkboxes_draw_outlines_without_hover() {
|
||||
|
||||
@@ -2970,3 +2970,246 @@ mod button_tests {
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// How the shared widgets look once laid out and painted: shapes of whole frames, measured.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod look_tests {
|
||||
use super::*;
|
||||
|
||||
/// A context with the fonts and the theme in `brightness`, in English.
|
||||
pub(crate) fn themed(brightness: theme::Brightness) -> egui::Context {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let ctx = egui::Context::default();
|
||||
theme::install_fonts(&ctx);
|
||||
theme::apply(&ctx, brightness);
|
||||
ctx
|
||||
}
|
||||
|
||||
/// One frame at `time` seconds of `add` in a 600 × 400 window with `events` → the shapes it
|
||||
/// drew, `Shape::Vec`s flattened.
|
||||
pub(crate) fn frame(ctx: &egui::Context, time: f64, events: Vec<egui::Event>, add: impl FnMut(&mut Ui)) -> Vec<egui::Shape> {
|
||||
fn flat(s: egui::Shape, out: &mut Vec<egui::Shape>) {
|
||||
match s {
|
||||
egui::Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)),
|
||||
s => out.push(s),
|
||||
}
|
||||
}
|
||||
let raw =
|
||||
egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 400.0))), events, ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, add);
|
||||
out.textures_delta.clear();
|
||||
let mut shapes = vec![];
|
||||
out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes));
|
||||
shapes
|
||||
}
|
||||
|
||||
// Regression test for #808: the scroll bar of the toolbar and the dock's icon column widened to
|
||||
// 10 points while it was dragged or the pointer was on it, covering the group labels and the
|
||||
// right edge of the tool icons. It stays a slim line.
|
||||
#[test]
|
||||
fn the_strip_scroll_bar_stays_a_slim_line_while_the_pointer_is_on_it() {
|
||||
let ctx = themed(Default::default());
|
||||
let area = std::cell::Cell::new(Rect::NOTHING);
|
||||
let mut add = |ui: &mut Ui| {
|
||||
area.set(
|
||||
ui.allocate_ui(vec2(80.0, 200.0), |ui| {
|
||||
strip_scroll(ui, "strip", |ui| {
|
||||
for i in 0..40 {
|
||||
ui.label(format!("Tool {i}"));
|
||||
}
|
||||
});
|
||||
})
|
||||
.response
|
||||
.rect,
|
||||
);
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
let area = area.get();
|
||||
assert!(area.height() >= 199.0, "the strip fills the height it was given: {area:?}");
|
||||
// The pointer comes onto the bar's edge and stays there while the bar settles.
|
||||
let on_the_bar = egui::Event::PointerMoved(pos2(area.right() - 1.0, area.center().y));
|
||||
let mut widest = 0.0_f32;
|
||||
for i in 1..=15 {
|
||||
let shapes = frame(&ctx, f64::from(i) * 0.1, if i == 1 { vec![on_the_bar.clone()] } else { vec![] }, &mut add);
|
||||
for s in shapes {
|
||||
// The bar's track and handle are the filled rectangles.
|
||||
if let egui::Shape::Rect(r) = s
|
||||
&& r.fill != Color32::TRANSPARENT
|
||||
{
|
||||
widest = widest.max(r.rect.width());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(widest > 0.0, "the scroll bar is drawn");
|
||||
assert!(widest <= 4.5, "the scroll bar is {widest} points wide");
|
||||
}
|
||||
// Regression test for #900: a number field with a spinner and a preset list drew as three
|
||||
// boxes side by side: its text box was a point taller than the 26-point row, and each joint had
|
||||
// two borders.
|
||||
#[test]
|
||||
fn a_spinner_field_reads_as_one_box_in_three_parts() {
|
||||
let ctx = themed(Default::default());
|
||||
let mut add = |ui: &mut Ui| {
|
||||
ui.horizontal(|ui| spin_field(ui, "weight", Some(4.0), Unit::Points, 100.0, 1.0, 0.0, &[1.0, 2.0]));
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
let shapes = frame(&ctx, 0.1, vec![], &mut add);
|
||||
// The boxes of the row: the spinner, the field and the preset chevron, left to right.
|
||||
let mut boxes: Vec<Rect> = vec![];
|
||||
for s in &shapes {
|
||||
if let egui::Shape::Rect(r) = s
|
||||
&& r.rect.height() > 20.0
|
||||
&& !boxes.contains(&r.rect)
|
||||
{
|
||||
boxes.push(r.rect);
|
||||
}
|
||||
}
|
||||
boxes.sort_by(|a, b| a.min.x.total_cmp(&b.min.x));
|
||||
assert_eq!(boxes.len(), 3, "{boxes:?}");
|
||||
for b in &boxes {
|
||||
assert_eq!((b.min.y, b.height()), (boxes[0].min.y, 26.0), "all as tall as the row: {boxes:?}");
|
||||
}
|
||||
for pair in boxes.windows(2) {
|
||||
assert!((pair[1].min.x - pair[0].max.x + 1.0).abs() < 0.01, "neighbours share one border: {boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour of every glyph of the text in `shapes`: selected glyphs are drawn in the
|
||||
/// selection stroke's colour.
|
||||
pub(crate) fn glyph_colours(shapes: &[egui::Shape]) -> Vec<Color32> {
|
||||
let mut colours = vec![];
|
||||
for s in shapes {
|
||||
if let egui::Shape::Text(t) = s {
|
||||
for row in &t.galley.rows {
|
||||
let visuals = &row.row.visuals;
|
||||
colours.extend(visuals.mesh.vertices[visuals.glyph_vertex_range.clone()].iter().map(|v| v.color));
|
||||
}
|
||||
}
|
||||
}
|
||||
colours
|
||||
}
|
||||
|
||||
// Regression test for #1465: the selected number in a value field was hard to read in every
|
||||
// brightness: egui draws selected text in the selection stroke's colour, the accent, on a
|
||||
// selection tinted with the same accent. It is in the strong text colour.
|
||||
#[test]
|
||||
fn selected_text_in_a_value_field_is_in_the_strong_text_colour() {
|
||||
for brightness in theme::Brightness::ALL {
|
||||
let ctx = themed(brightness);
|
||||
let t = Tokens::get(&ctx);
|
||||
let id = std::cell::Cell::new(egui::Id::NULL);
|
||||
let mut add = |ui: &mut Ui| {
|
||||
id.set(ui.id().with("w"));
|
||||
num_field(ui, "w", Some(1234.0), Unit::Points, 80.0);
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
// The field takes focus, and all of its text is selected.
|
||||
ctx.memory_mut(|m| m.request_focus(id.get()));
|
||||
frame(&ctx, 0.1, vec![], &mut add);
|
||||
assert!(ctx.memory(|m| m.has_focus(id.get())), "{brightness:?}: the field has focus");
|
||||
let len = Unit::Points.format(1234.0).chars().count();
|
||||
let mut state = egui::TextEdit::load_state(&ctx, id.get()).unwrap_or_default();
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(len))));
|
||||
state.store(&ctx, id.get());
|
||||
let shapes = frame(&ctx, 0.2, vec![], &mut add);
|
||||
let colours = glyph_colours(&shapes);
|
||||
assert!(!colours.is_empty(), "{brightness:?}: the number is drawn");
|
||||
let mut used = colours.clone();
|
||||
used.dedup();
|
||||
assert_eq!(used, [t.text_strong], "{brightness:?}: selected text in {used:?}");
|
||||
assert_ne!(t.text_strong, t.accent);
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #1483: the theme's widget fill is the panel's colour, so a slider in a
|
||||
// dialog showed only its handle. `slider` draws the rail in the buttons' border colour and
|
||||
// fills it up to the handle in the accent.
|
||||
#[test]
|
||||
fn a_slider_shows_its_rail_filled_up_to_the_handle() {
|
||||
for brightness in theme::Brightness::ALL {
|
||||
let ctx = themed(brightness);
|
||||
let t = Tokens::get(&ctx);
|
||||
let mut value = 30.0_f64;
|
||||
let mut add = |ui: &mut Ui| {
|
||||
slider(ui, egui::Slider::new(&mut value, 0.0..=100.0).show_value(false));
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
let shapes = frame(&ctx, 0.1, vec![], &mut add);
|
||||
let rects: Vec<(Rect, Color32)> =
|
||||
shapes.iter().filter_map(|s| if let egui::Shape::Rect(r) = s { Some((r.rect, r.fill)) } else { None }).collect();
|
||||
let rail = rects.iter().find(|(_, c)| *c == t.button_border).map(|(r, _)| *r);
|
||||
let filled = rects.iter().find(|(_, c)| *c == t.accent).map(|(r, _)| *r);
|
||||
let (Some(rail), Some(filled)) = (rail, filled) else {
|
||||
panic!("{brightness:?}: the rail ({:?}) and its fill ({:?}) are drawn: {rects:?}", t.button_border, t.accent);
|
||||
};
|
||||
assert!(filled.width() > 1.0 && filled.width() < rail.width(), "{brightness:?}: filled {filled:?} of the rail {rail:?}");
|
||||
assert!((filled.min.x - rail.min.x).abs() < 1.0, "{brightness:?}: the fill starts at the rail's start");
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #2083: the rows of the panels' menus didn't light up under the pointer, as
|
||||
// the menu bar's items do.
|
||||
#[test]
|
||||
fn a_panel_menu_row_lights_up_under_the_pointer() {
|
||||
let ctx = themed(Default::default());
|
||||
let row_at = std::cell::Cell::new(Rect::NOTHING);
|
||||
let mut add = |ui: &mut Ui| {
|
||||
row_at.set(
|
||||
ui.scope(|ui| {
|
||||
menu_item_name(ui, "Rename", true, false);
|
||||
})
|
||||
.response
|
||||
.rect,
|
||||
);
|
||||
};
|
||||
// A filled rectangle behind the row's text.
|
||||
let lit = |shapes: &[egui::Shape], row: Rect| {
|
||||
shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.fill != Color32::TRANSPARENT && r.rect.contains(row.center())))
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
let row = row_at.get();
|
||||
let at_rest = frame(&ctx, 0.1, vec![], &mut add);
|
||||
assert!(!lit(&at_rest, row), "no frame at rest");
|
||||
frame(&ctx, 0.2, vec![egui::Event::PointerMoved(row.center())], &mut add);
|
||||
let hovered = frame(&ctx, 0.3, vec![], &mut add);
|
||||
assert!(lit(&hovered, row), "the row under the pointer is lit: {row:?}");
|
||||
}
|
||||
|
||||
// Regression test for #3440: the Fill/Stroke chip's popover closed on the click that ended a
|
||||
// drag between its proxies. It stays open for a click on its own anchor and while a panel
|
||||
// drag is on; a click elsewhere still closes it.
|
||||
#[test]
|
||||
fn a_popover_stays_open_for_a_click_on_its_anchor_or_during_a_panel_drag() {
|
||||
let press = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// Opens the popover, then clicks at `click` (with `drag` as the panel drag under way).
|
||||
let open_after_click = |click: Option<Pos2>, drag: Option<PanelDrag>| -> bool {
|
||||
let ctx = themed(Default::default());
|
||||
let toggle = std::cell::Cell::new(true);
|
||||
let shown = std::cell::Cell::new(false);
|
||||
let anchor = std::cell::Cell::new(Rect::NOTHING);
|
||||
let mut add = |ui: &mut Ui| {
|
||||
let resp = ui.allocate_response(vec2(40.0, 24.0), Sense::hover());
|
||||
anchor.set(resp.rect);
|
||||
shown.set(popover(&resp, toggle.replace(false), |ui| ui.label("Colour")).is_some());
|
||||
};
|
||||
frame(&ctx, 0.0, vec![], &mut add);
|
||||
assert!(shown.get(), "the toggle opens it");
|
||||
frame(&ctx, 0.2, vec![], &mut add);
|
||||
assert!(shown.get(), "it stays open");
|
||||
if let Some(d) = drag {
|
||||
egui::DragAndDrop::set_payload(&ctx, d);
|
||||
}
|
||||
let pos = click.unwrap_or_else(|| anchor.get().center());
|
||||
frame(&ctx, 0.3, vec![egui::Event::PointerMoved(pos), press(pos, true)], &mut add);
|
||||
frame(&ctx, 0.4, vec![press(pos, false)], &mut add);
|
||||
frame(&ctx, 0.5, vec![], &mut add);
|
||||
shown.get()
|
||||
};
|
||||
let far = Some(pos2(500.0, 350.0));
|
||||
let panel_drag = || Some(PanelDrag::Symbol("s".into()));
|
||||
// Whether it is open after: a click elsewhere; a click on its anchor that doesn't toggle it;
|
||||
// a panel drag released elsewhere.
|
||||
let open = [open_after_click(far, None), open_after_click(None, None), open_after_click(far, panel_drag())];
|
||||
assert_eq!(open, [false, true, true]);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user