From 815c772a46ab02e470d321a3b7efb3e2fa4d75dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:13:52 -0800 Subject: [PATCH 01/33] Image Trace: presets trace at Paths 50 with new Corners and Noise Every built-in preset other than Auto Color and Flat Logo now traces at Paths 50. Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline, and 50 in the others. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, 6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and Black and White Logo, and 90 in Silhouettes. Palettes, color counts and the other options are unchanged. This changes the output of every preset but Default, Auto Color and Flat Logo. The traces take fewer anchors (High Fidelity Photo 5,494 to 3,136 and Black and White Logo 27 to 14 in crates/trace/tests/quality), and outlines on flat art lie further from the true edge (16 Colors 0.100 to 0.123 px off on average). Docs: docs/image-trace-adjustments.md, docs/image-trace-quality.md, docs/target-app-parity.md. --- crates/engine/src/cmd/buildcmds/trace.rs | 7 +++-- crates/trace/src/params.rs | 24 +++++++-------- crates/trace/src/tests.rs | 29 ++++++++++++++++++ docs/image-trace-adjustments.md | 10 +++++- docs/image-trace-quality.md | 39 ++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 94 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 11519b84be..024ae851f5 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -288,8 +288,9 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); } diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 9c430dd19d..156d6fbef2 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -241,19 +241,19 @@ pub fn preset(name: &str) -> Option { // many as its tones need where it is not. // (Color detail 85: a colour on a hundredth of the picture is still one of its colours.) "auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) }, - "high fidelity photo" => color(64, 90.0, 25.0, 4, Method::Overlapping), - "low fidelity photo" => color(20, 60.0, 50.0, 12, Method::Overlapping), - "3 colors" => color(3, 60.0, 60.0, 20, Method::Abutting), - "6 colors" => color(6, 65.0, 60.0, 16, Method::Abutting), - "16 colors" => color(16, 70.0, 55.0, 10, Method::Abutting), - "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 60.0, corners: 50.0, noise: 10, method: Method::Overlapping, ..d }, - "black and white logo" => bw(128, 95.0, 80.0, 8, true), - "sketched art" => bw(150, 50.0, 50.0, 100, false), - "silhouettes" => bw(200, 40.0, 60.0, 30, false), - "line art" => bw(128, 80.0, 70.0, 10, false), - "technical drawing" => bw(128, 95.0, 90.0, 4, true), + "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), + "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), + "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), + "6 colors" => color(6, 50.0, 50.0, 15, Method::Abutting), + "16 colors" => color(16, 50.0, 50.0, 15, Method::Abutting), + "shades of gray" => TraceParams { mode: Mode::Grayscale, colors: 8, paths: 50.0, corners: 50.0, noise: 15, method: Method::Overlapping, ..d }, + "black and white logo" => bw(128, 50.0, 75.0, 25, true), + "sketched art" => bw(150, 50.0, 50.0, 20, false), + "silhouettes" => bw(200, 50.0, 50.0, 90, false), + "line art" => bw(128, 50.0, 75.0, 20, false), + "technical drawing" => bw(128, 50.0, 100.0, 1, true), // Black outlines: lines as stroked centre lines, wider areas as stroked outlines. - "outline" => TraceParams { fills: false, strokes: true, ..bw(128, 80.0, 70.0, 10, false) }, + "outline" => TraceParams { fills: false, strokes: true, ..bw(128, 50.0, 75.0, 20, false) }, // Flat-colour logos: colours found automatically, edges placed to a fraction of a pixel. "flat logo" => TraceParams { mode: Mode::Logo, colors: 8, paths: 60.0, corners: 50.0, noise: 6, snap_curves_to_lines: true, ..d }, _ => return None, diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index fbedb07e29..e8d9fab828 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -892,6 +892,35 @@ fn presets_resolve() { assert!(preset("nope").is_none()); } +#[test] +fn presets_have_their_paths_corners_and_noise() { + let expected: &[(&str, f64, f64, u32)] = &[ + ("Default", 50.0, 75.0, 25), + ("High Fidelity Photo", 50.0, 50.0, 5), + ("Low Fidelity Photo", 50.0, 50.0, 10), + ("3 Colors", 50.0, 50.0, 15), + ("6 Colors", 50.0, 50.0, 15), + ("16 Colors", 50.0, 50.0, 15), + ("Shades of Gray", 50.0, 50.0, 15), + ("Black and White Logo", 50.0, 75.0, 25), + ("Sketched Art", 50.0, 50.0, 20), + ("Silhouettes", 50.0, 50.0, 90), + ("Line Art", 50.0, 75.0, 20), + ("Technical Drawing", 50.0, 100.0, 1), + ("Outline", 50.0, 75.0, 20), + ]; + for &(name, paths, corners, noise) in expected { + let p = preset(name).unwrap(); + assert_eq!((p.paths, p.corners, p.noise), (paths, corners, noise), "{name}"); + } + // The color counts stay as they were. + let colors: Vec = ["High Fidelity Photo", "Low Fidelity Photo", "3 Colors", "6 Colors", "16 Colors", "Shades of Gray"] + .iter() + .map(|n| preset(n).unwrap().colors) + .collect(); + assert_eq!(colors, [64, 20, 3, 6, 16, 8]); +} + #[test] fn params_json_roundtrip_and_partial() { let p = preset("6 Colors").unwrap(); diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index f1c0b7d3dd..e35fe5453b 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -18,6 +18,13 @@ its current location. Opening the controls does not add a document undo step. | Create | Fills / Strokes | Creates filled areas, stroked lines, or both. | | Ignore Color | Color picker | Leaves out the selected color (white by default). | +The built-in presets other than Auto Color and Flat Logo all use Paths 50. Corners is 100 in +Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline, and 50 in the others. +Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, +6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and +Black and White Logo, and 90 in Silhouettes (see +[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). + Sliders apply on release, and their numeric fields can be edited directly. Each committed adjustment re-traces the selected object as one undo step and changes the preset to Custom. While dragging, the preset and Enhanced row stay in place until release so the @@ -123,7 +130,8 @@ color is averaged down further: the factor doubles until at most 150,000 remain most 16,384 pixels (at most six times). A trace that would make more than 8,000,000 anchor points (2,000,000 on the web) is refused to protect memory, with advice: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset. A trace keeps -about 90 bytes an anchor; a 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million. +about 90 bytes an anchor; a 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 +makes about 1.9 million. **Tracing in the background.** On the desktop a trace runs on a thread of its own, so the window keeps answering while a photo or a large image is traced (#3098). Make, Make and Expand, the task bar's Image Trace and the panel's Trace and presets start it. The status bar says "Tracing the diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 40f6fe43b9..2b2b363433 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -82,6 +82,9 @@ gradient, texture, sensor noise): (The last two rows were measured without a limit; they are refused now.) The 4000 × 3000 High Fidelity Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing. +The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25 +and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10 +(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)). ## Collapsed loops keep few segments A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths @@ -225,6 +228,42 @@ in a smooth area), `a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_kee `a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch`, `a_run_of_two_steps_keeps_its_corners`, `a_junction_on_a_step_ends_the_staircase_there` and `a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there`. +## Preset Paths, Corners and Noise +Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Corners and Noise are: + +| preset | Paths | Corners | Noise | before | +|:--|--:|--:|--:|:--| +| Default | 50 | 75 | 25 | unchanged | +| High Fidelity Photo | 50 | 50 | 5 | 90, 25, 4 | +| Low Fidelity Photo | 50 | 50 | 10 | 60, 50, 12 | +| 3 Colors | 50 | 50 | 15 | 60, 60, 20 | +| 6 Colors | 50 | 50 | 15 | 65, 60, 16 | +| 16 Colors | 50 | 50 | 15 | 70, 55, 10 | +| Shades of Gray | 50 | 50 | 15 | 60, 50, 10 | +| Black and White Logo | 50 | 75 | 25 | 95, 80, 8 | +| Sketched Art | 50 | 50 | 20 | 50, 50, 100 | +| Silhouettes | 50 | 50 | 90 | 40, 60, 30 | +| Line Art | 50 | 75 | 20 | 80, 70, 10 | +| Technical Drawing | 50 | 100 | 1 | 95, 90, 4 | +| Outline | 50 | 75 | 20 | 80, 70, 10 | + +The palettes, color counts, thresholds and other options of the presets did not change. + +Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: +anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 +(16 Colors), 27 to 14 (Black and White Logo) and 43 to 28 (Line Art); Silhouettes rises from 13 to 15 and +Sketched Art does not change. Outlines on flat art lie further from the true edge: off mean 0.100 to 0.123 +px (16 Colors), 0.101 to 0.119 (6 Colors), 0.104 to 0.129 (3 Colors), 0.064 to 0.092 (Black and White Logo) +and 0.056 to 0.074 (Line Art), and off max 1.00 to 1.16 px in 6 Colors and 16 Colors. Technical Drawing +leaves 1.4 specks (was 0.5), and Outline's stroked centre lines lie 0.095 px off (was 0.086) with 2.7 +anchors a stroke (was 3.0). ΔE changes by 0.01 or less except Line Art and Outline (2.62 and 2.61 to 2.66 +and 2.67); edge ΔE rises in 8 of the 12, for example 4.79 to 5.25 (16 Colors), 3.98 to 4.46 (3 Colors) and 9.46 to 10.03 +(Black and White Logo). On synthetic shapes and photos of 300 to 4,000 px traced outside this harness, +High Fidelity Photo makes 41% fewer anchors and 16 Colors 15% fewer; the mean pixel difference of each +trace changes by −0.23 to +0.25 of a level; 16 Colors leaves 91 staircases of steps of 2 px or more where it left 85, and High +Fidelity Photo 473 where it left 461. The tables below are the previous measurement, not a rerun. +Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. + ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 26681e5b7f..4cecc0dc06 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1397,6 +1397,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges:** in Color and Grayscale, a semi-transparent pixel (alpha 128 to 254) on the edge of a cut-out image, beside a pixel that is less than half opaque, traces as a color of the fully opaque pixels within two pixels of it when its own color is that color or a darker shade of it, and of several such colors, as the one the most of those pixels have (art across a transparent gap does not count), so a darkened edge tone no longer traces as a 1 px sliver of an unrelated palette color, while a thin semi-transparent outline of another color keeps its own; code-drawn cut-out, opaque-edge and thin-outline tests in `crates/trace`. - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. +- **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50; Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the others; Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. From 257d45d99479ee6f972456e8ad863525dca56b25 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:18:02 -0800 Subject: [PATCH 02/33] i18n: Turkish has a row for 1,811 of the messages the untranslated report lists The Turkish catalog had no row for 1,852 of the status and error messages that the untranslated report finds in the sources, so the status bar showed those messages in English. - tr.tsv gains 1,811 `@msg` rows: the errors of commands and their parameter checks, scripts, file import and export, printing, plug-ins and Banner Hems and Grommets. The translations are VectorCraft's own, written from the English meaning with the catalog's terms and its existing feature names. Placeholders, parameter names, command ids and literal values stay as the English writes them. - The 38 listed messages that open #7211, #7116 and #7330 add tr.tsv rows for are left out, so the catalog has no duplicate key when they merge. - Three messages that open #7353 rewrites are left out: the unknown parameter error and the PDF setting range error, which have two placeholders in a row that no row can match, and the unknown parameter error for a format's settings. - The row for `{k} has control characters{_1}` does not match the message for a multi-line File Info field, where the last placeholder is empty. - The Turkish row of docs/localization-parity.md gives the catalog's current counts and what still falls back to English. Docs: docs/target-app-parity.md, docs/localization-parity.md. --- crates/ui-egui/src/i18n/tr.tsv | 1812 ++++++++++++++++++++++++++++++++ docs/localization-parity.md | 2 +- docs/target-app-parity.md | 1 + 3 files changed, 1814 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d22c3b961f..c64b7dc6b2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4741,6 +4741,7 @@ axis Both Her İkisi @msg workspace name can't be empty çalışma alanı adı boş olamaz @msg {C}: no effect at index {from} {C}: {from} endeksinde etkisi yok @msg {_1} failed: {e} {_1} başarısız oldu: {e} +@msg {saving} failed: {e} {saving} başarısız oldu: {e} @msg {_1} files can be opened but not written (see document.formats) {_1} dosyaları açılabilir ancak yazılamaz (bkz. document.formats) @msg {_1} font families available {_1} yazı tipi aileleri mevcut @msg {_1} is a live effect (Effect › Plug-ins) {_1} canlı bir efekttir (Efekt › Eklentiler) @@ -6597,6 +6598,1808 @@ axis Y Axis Y ekseni @msg no menu item that can be inserted runs this command eklenebilen hiçbir menü öğesi bu komutu çalıştırmaz @msg the action already has 10,000 steps eylemde zaten 10.000 adım var @msg the action set would be larger than 8 MiB eylem seti 8 MiB'tan büyük olurdu +# Status and error messages of commands and their parameter checks, scripts, file import and export, printing and plug-ins. +@msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions katı kip işlevlerinde 'caller', 'callee' ve 'arguments' kullanılamaz +@msg Alignment must be one of the choices Hizalama, seçeneklerden biri olmalıdır +@msg Boolean.prototype.{name} was called on a value that is not a Boolean Boolean.prototype.{name}, Boolean olmayan bir değer üzerinde çağrıldı +@msg CMYK images whose samples couldn't be read in CMYK were imported in RGB Örnekleri CMYK olarak okunamayan CMYK görüntüler RGB olarak içe aktarıldı +@msg Cannot write to the location of “{name}”; choose where to save it “{name}” konumuna yazılamıyor; nereye kaydedileceğini seçin +@msg DCS files can only be placed linked: use File › Place with Link on DCS dosyaları yalnızca bağlantılı olarak yerleştirilebilir: Dosya › Yerleştir komutunu Bağlantı açıkken kullanın +@msg Date.prototype method called on a value that is not a Date object Date.prototype yöntemi, Date nesnesi olmayan bir değer üzerinde çağrıldı +@msg Error.prototype.toString was called on a value that is not an object Error.prototype.toString, nesne olmayan bir değer üzerinde çağrıldı +@msg Function.prototype.toString was called on a value that is not a function Function.prototype.toString, işlev olmayan bir değer üzerinde çağrıldı +@msg Import SVG Filter reads SVG files, not SVGZ SVG Filtresini İçe Aktar, SVGZ dosyalarını okumaz; SVG dosyalarını okur +@msg JSON.parse: {why} (at offset {at}) JSON.parse: {why} (konum: {at}) +@msg JSON.stringify cannot write a structure that contains itself JSON.stringify kendini içeren bir yapıyı yazamaz +@msg Line Gap must be a number Satır Boşluğu bir sayı olmalıdır +@msg Namespace.prototype.toString needs a Namespace Namespace.prototype.toString için bir Namespace gerekir +@msg New Document profiles need the preferences folder, which this run doesn't have Yeni Belge profilleri için tercihler klasörü gerekir; bu çalıştırmada o klasör yok +@msg Number.prototype.{name} was called on a value that is not a number Number.prototype.{name}, sayı olmayan bir değer üzerinde çağrıldı +@msg Object.create's prototype must be an object or null Object.create için prototip bir nesne veya null olmalıdır +@msg Object.{function} was given a value that is not an object Object.{function} işlevine nesne olmayan bir değer verildi +@msg QName.prototype.toString needs a QName QName.prototype.toString için bir QName gerekir +@msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name}, RegExp nesnesi olmayan bir değer üzerinde çağrıldı +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Şablon Köprüleri: seçili resim köprülenemeyecek kadar büyük veya ayrıntılı +@msg String.prototype.toString was called on a value that is not a string String.prototype.toString, dize olmayan bir değer üzerinde çağrıldı +@msg The {name} profile could not be read, so the new document has the default settings: {reason} {name} profili okunamadı, bu yüzden yeni belge varsayılan ayarları kullanıyor: {reason} +@msg Trap: more than {_1} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time Tuzak: {_1} çiftten fazla nesne tuzaklanacak kadar yakın duruyor veya çok fazla nesne aynı yatay aralığı paylaşıyor; bir seferde daha az nesne tuzaklayın +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ayıklama Kutusu ve Çizgileri: resmin dışına sığan bir ayıklama çizgisi yok ve ayıklama kutusu kapalı +@msg \\ at end of pattern desenin sonunda \\ +@msg `alignOn` cannot be empty `alignOn` boş olamaz +@msg `alignOn` must be a string `alignOn` bir dize olmalıdır +@msg `align` must be a string `align` bir dize olmalıdır +@msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} +@msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var +@msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük +@msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır +@msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır +@msg `artboardsAt` must be [x, y] `artboardsAt` [x, y] olmalıdır +@msg `artboards` names an artboard the document does not have `artboards`, belgede olmayan bir çalışma yüzeyini belirtiyor +@msg `artboards` names an artboard twice `artboards` bir çalışma yüzeyini iki kez belirtiyor +@msg `at` must be [x, y] (got {at}) `at` [x, y] olmalıdır (verilen: {at}) +@msg `at` must be a point [x, y] `at` bir [x, y] noktası olmalıdır +@msg `beside` needs `side` `beside` için `side` gerekir +@msg `code` must be a whole number `code` bir tam sayı olmalıdır +@msg `colorMode` must be one of rgb, cmyk `colorMode` şunlardan biri olmalıdır: rgb, cmyk +@msg `colors` does not apply to the {name} reduction `colors`, {name} azaltması için geçerli değildir +@msg `colors` must be a whole number from 2 to 256 `colors` 2 ile 256 arasında bir tam sayı olmalıdır +@msg `colors` must be at least 9 for the uniform reduction tekdüze azaltma için `colors` en az 9 olmalıdır +@msg `colors` must be between 1 and {MAX_THEME_COLORS} (got {n}) `colors` 1 ile {MAX_THEME_COLORS} arasında olmalıdır (verilen: {n}) +@msg `count` must be a whole number from 0 to {MAX_COUNT} `count` 0 ile {MAX_COUNT} arasında bir tam sayı olmalıdır +@msg `ditherAmount` must be a number from 0 to 100 `ditherAmount` 0 ile 100 arasında bir sayı olmalıdır +@msg `fidelity` must be from {lo} to {hi} pt `fidelity` {lo} ile {hi} pt arasında olmalıdır +@msg `focal` and `radius` cannot be used together `focal` ve `radius` birlikte kullanılamaz +@msg `focal` must be an array of [subpath, anchor] pairs `focal`, [subpath, anchor] çiftlerinden oluşan bir dizi olmalıdır +@msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal`, yolun bir bağlantı noktası olmayan [{si}, {ai}] çiftini belirtiyor +@msg `glyphAlternate` takes only null, which takes a glyph choice away (text.setGlyphAlternate makes one) `glyphAlternate` yalnızca null alır; null bir glif seçimini kaldırır (seçimi text.setGlyphAlternate yapar) +@msg `group` must be one of {_1} `group` şunlardan biri olmalıdır: {_1} +@msg `group` must be the Objects on Path group of `member` and `target` `group`, `member` ve `target` nesnelerinin Yol Üzerindeki Nesneler grubu olmalıdır +@msg `id` is an object id, not {v} `id` bir nesne kimliğidir, {v} değil +@msg `item` needs `index` `item` için `index` gerekir +@msg `kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it) `kerningBefore` bir karakter stiline değil, satırın ilk karakterine aittir (text.setRangeStyle ayarlar) +@msg `kinsokuType` must be "pushInFirst", "pushOutFirst" or "pushOutOnly" `kinsokuType` "pushInFirst", "pushOutFirst" veya "pushOutOnly" olmalıdır +@msg `leader` must be a string `leader` bir dize olmalıdır +@msg `max` must be 1 to {MAX_SUGGESTIONS} `max` 1 ile {MAX_SUGGESTIONS} arasında olmalıdır +@msg `name` must be a name that is not empty `name` boş olmayan bir ad olmalıdır +@msg `name` must not be empty `name` boş olmamalıdır +@msg `origin` must be [x, y] in points `origin` punto cinsinden [x, y] olmalıdır +@msg `picks` must be an array (got {v}) `picks` bir dizi olmalıdır (verilen: {v}) +@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` 1 ile {MAX_PICKS} arasında seçim içermelidir (verilen: {_1}) +@msg `points` must hold from 2 to 100000 points `points` 2 ile 100000 arasında nokta içermelidir +@msg `radius` must be 0 or more `radius` 0 veya daha büyük olmalıdır +@msg `rect` must be [x, y, width, height] `rect` [x, y, width, height] olmalıdır +@msg `rect` must be [x0, y0, x1, y1] (got {r}) `rect` [x0, y0, x1, y1] olmalıdır (verilen: {r}) +@msg `replace` must be a string `replace` bir dize olmalıdır +@msg `rows` must be lists of numbers or nulls, not {r} `rows`, sayı veya null listeleri olmalıdır, {r} değil +@msg `scale` must be a number from 0.001 to 1000 `scale` 0.001 ile 1000 arasında bir sayı olmalıdır +@msg `scope.{key}` must be a non-empty array `scope.{key}` boş olmayan bir dizi olmalıdır +@msg `scope` must be "document", {artboards} or {layers} `scope` "document", {artboards} veya {layers} olmalıdır +@msg `side` must be "left", "right", "top" or "bottom" `side` "left", "right", "top" veya "bottom" olmalıdır +@msg `side` places the artboard: leave out x, y, width and height `side` çalışma yüzeyini yerleştirir: x, y, width ve height değerlerini vermeyin +@msg `source` is the only path in series group `target` `source`, `target` seri grubundaki tek yoldur +@msg `spacing` makes more than {MAX_COUNT} lines across the box `spacing`, kutu boyunca {MAX_COUNT} taneden fazla çizgi oluşturuyor +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` 0'dan büyük ve en fazla {MAX_DISTANCE} pt olmalıdır +@msg `target` must be an object of the same Objects on Path group as `member` `target`, `member` ile aynı Yol Üzerindeki Nesneler grubundaki bir nesne olmalıdır +@msg `tolerance` must be from 0 to 100 pt `tolerance` 0 ile 100 pt arasında olmalıdır +@msg `version` must be 0 or {_1} `version` 0 veya {_1} olmalıdır +@msg `version` must be 0 or {newest} `version` 0 veya {newest} olmalıdır +@msg `warichuAlign` must be one of {_1} `warichuAlign` şunlardan biri olmalıdır: {_1} +@msg `warichuLines` must be a whole number from {_1} to {_2} `warichuLines` {_1} ile {_2} arasında bir tam sayı olmalıdır +@msg `weight` must be from 0.01 to 1000 pt `weight` 0.01 ile 1000 pt arasında olmalıdır +@msg `weights` must be a list of {_1} numbers, one per row (got {v}) `weights`, her satır için bir tane olmak üzere {_1} sayıdan oluşan bir liste olmalıdır (verilen: {v}) +@msg `xml` must be a string `xml` bir dize olmalıdır +@msg `{KEY}` entry {n} gives the paragraph at byte {start} of {_1} other indents than an entry before it `{KEY}` içindeki {n} numaralı girdi, {_1} nesnesinin {start} numaralı baytındaki paragrafa önceki bir girdiden farklı girintiler veriyor +@msg `{KEY}` entry {n} must be an object `{KEY}` içindeki {n} numaralı girdi bir nesne olmalıdır +@msg `{KEY}` entry {n} sets neither `leftIndent` nor `firstLineIndent` `{KEY}` içindeki {n} numaralı girdi ne `leftIndent` ne de `firstLineIndent` ayarlıyor +@msg `{KEY}` entry {n}: `id` must be an object id `{KEY}` girdi {n}: `id` bir nesne kimliği olmalıdır +@msg `{KEY}` entry {n}: `start` must be a byte offset `{KEY}` girdi {n}: `start` bir bayt konumu olmalıdır +@msg `{KEY}` entry {n}: `{k}` must be a number from -{MAX_PARA} to {MAX_PARA} pt `{KEY}` girdi {n}: `{k}` -{MAX_PARA} ile {MAX_PARA} pt arasında bir sayı olmalıdır +@msg `{KEY}` entry {n}: no paragraph of {_1} starts at byte {start} `{KEY}` girdi {n}: {_1} nesnesinin hiçbir paragrafı {start} numaralı baytta başlamıyor +@msg `{KEY}` entry {n}: unknown key `{k}` `{KEY}` girdi {n}: bilinmeyen anahtar `{k}` +@msg `{KEY}` entry {n}: {_1} is not a type object `{KEY}` girdi {n}: {_1} bir metin nesnesi değil +@msg `{KEY}` is empty `{KEY}` boş +@msg `{KEY}` must be a list `{KEY}` bir liste olmalıdır +@msg `{KEY}` takes at most {MAX_PARAGRAPH_INDENTS} entries (got {_1}) `{KEY}` en fazla {MAX_PARAGRAPH_INDENTS} girdi alır (verilen: {_1}) +@msg `{KEY}` takes no `{other}` beside it `{KEY}` yanında `{other}` alamaz +@msg `{base}` is larger than {_1} MB `{base}` {_1} MB'tan büyük +@msg `{base}` is not in the DCS file's folder `{base}` DCS dosyasının klasöründe değil +@msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS} taneden fazla sözcük içeriyor +@msg `{key}` must be 0 or more `{key}` 0 veya daha büyük olmalıdır +@msg `{key}` must be [x, y] numbers `{key}` [x, y] sayıları olmalıdır +@msg `{key}` must be a list of words `{key}` bir sözcük listesi olmalıdır +@msg `{key}` must be a list, not {v} `{key}` bir liste olmalıdır, {v} değil +@msg `{key}` must be a number or null, not {v} `{key}` bir sayı veya null olmalıdır, {v} değil +@msg `{key}` must be a whole number of 0 or more `{key}` 0 veya daha büyük bir tam sayı olmalıdır +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` 0 ile {MAX_DISTANCE} pt arasında olmalıdır +@msg `{key}` must be from {lo} to {hi}, not {v} `{key}` {lo} ile {hi} arasında olmalıdır, {v} değil +@msg `{key}` must be one of auto, always, never `{key}` şunlardan biri olmalıdır: auto, always, never +@msg `{key}` must be one of miter, round, bevel `{key}` şunlardan biri olmalıdır: miter, round, bevel +@msg `{key}` must be one word of at most {_1} characters `{key}` en fazla {_1} karakterlik tek bir sözcük olmalıdır +@msg `{key}` must hold single words of at most {_1} characters `{key}` en fazla {_1} karakterlik tek sözcükler içermelidir +@msg `{key}` must name an object attached to the path of an Objects on Path group `{key}`, bir Yol Üzerindeki Nesneler grubunun yoluna iliştirilmiş bir nesneyi belirtmelidir +@msg `{key}` names an object that is hidden or locked `{key}` gizli veya kilitli bir nesneyi belirtiyor +@msg `{name}` is a file of its own, which can only be found next to the DCS file's path `{name}` ayrı bir dosyadır ve yalnızca DCS dosyasının yolunun yanında bulunabilir +@msg `{name}`: {_1}: {e} `{name}`: {_1}: {e} +@msg `{u}` is no Unicode character `{u}` bir Unicode karakteri değil +@msg `{word}` isn't in the custom dictionary `{word}` özel sözlükte yok +@msg a CMap has too many mappings bir CMap çok fazla eşleme içeriyor +@msg a \\u escape needs four hexadecimal digits bir \\u kaçışı için dört onaltılık basamak gerekir +@msg a comma in an XPath expression must separate function arguments XPath ifadesindeki bir virgül, işlev bağımsız değişkenlerini ayırmalıdır +@msg a document holds at most {_1} SVG filters bir belge en fazla {_1} SVG filtresi içerir +@msg a document with unsaved changes has no recovery copy kaydedilmemiş değişiklikleri olan bir belgenin kurtarma kopyası yok +@msg a font's data is too large bir yazı tipinin verileri çok büyük +@msg a font's subroutines are too large bir yazı tipinin alt yordamları çok büyük +@msg a function declaration without a name adı olmayan bir işlev bildirimi +@msg a host value has too many entries bir ana bilgisayar değeri çok fazla girdi içeriyor +@msg a host value is nested too deep bir ana bilgisayar değeri çok derin iç içe geçmiş +@msg a namespace declaration uses a reserved prefix or URI bir ad alanı bildirimi ayrılmış bir önek veya URI kullanıyor +@msg a namespace qualifier is undefined bir ad alanı niteleyicisi tanımlı değil +@msg a namespace with an empty URI cannot have a prefix URI'si boş olan bir ad alanının öneki olamaz +@msg a number has no digits bir sayının rakamı yok +@msg a number's exponent has no digits bir sayının üssünde rakam yok +@msg a number's fraction has no digits bir sayının kesir kısmında rakam yok +@msg a property descriptor cannot have both a value or writable and a get or set bir özellik tanımlayıcısı hem value veya writable hem de get veya set içeremez +@msg a property descriptor must be an object bir özellik tanımlayıcısı bir nesne olmalıdır +@msg a property's {name} must be a function or undefined bir özelliğin {name} değeri bir işlev veya undefined olmalıdır +@msg a stream in it would decode to more than 256 MB, or its decode parameters can't be applied içindeki bir akışın kodu çözülünce 256 MB'ı aşıyor veya kod çözme parametreleri uygulanamıyor +@msg a string holds a control character bir dize denetim karakteri içeriyor +@msg a string holds an escape sequence JSON does not have bir dize JSON'da olmayan bir kaçış dizisi içeriyor +@msg a string is not closed bir dize kapatılmamış +@msg an SVG filter is named by its id: give `xml` with `name` bir SVG filtresi kimliğiyle adlandırılır: `xml` değerini `name` ile birlikte verin +@msg an XML element has two attributes with the same name bir XML öğesinde aynı ada sahip iki öznitelik var +@msg an XML value cannot be inserted into itself or its descendants bir XML değeri kendisine veya alt öğelerine eklenemez +@msg an XML value's children cannot be assigned by position bir XML değerinin alt öğeleri konuma göre atanamaz +@msg an XML value's children cannot be deleted by position bir XML değerinin alt öğeleri konuma göre silinemez +@msg an XMLList converts to XML only when it has one item bir XMLList yalnızca tek öğesi olduğunda XML'e dönüşür +@msg an XPath node test is missing bir XPath düğüm testi eksik +@msg an XPath operand is missing bir XPath işleneni eksik +@msg an XPath operator is missing bir XPath işleci eksik +@msg an XPath predicate or step cannot follow here burada bir XPath yüklemi veya adımı gelemez +@msg an XPath predicate or step follows a value that is not a node-set bir XPath yüklemi veya adımı, düğüm kümesi olmayan bir değerin ardından geliyor +@msg an XPath step is missing bir XPath adımı eksik +@msg an image couldn't be decoded and is missing from the picture bir görüntünün kodu çözülemedi ve resimde eksik +@msg an image of {w} × {h} pixels is too large to convert (at most {_1} pixels) {w} × {h} piksellik bir görüntü dönüştürülemeyecek kadar büyük (en fazla {_1} piksel) +@msg apply was called on a value that is not a function apply, işlev olmayan bir değer üzerinde çağrıldı +@msg area type in a thread cannot use Dynamic Text: {frames} zincirli metindeki alan metni Dinamik Metin kullanamaz: {frames} +@msg array literal too long dizi değişmezi çok uzun +@msg assignment to a constant binding sabit bir bağlamaya atama +@msg at least one row that isn't excluded needs a weight above 0 hariç tutulmayan en az bir satırın ağırlığı 0'dan büyük olmalıdır +@msg bad point {v}: expected [x, y] hatalı nokta {v}: [x, y] bekleniyordu +@msg blend must be a mode name blend bir mod adı olmalıdır +@msg both sides of an XPath | must select nodes bir XPath | işlecinin iki tarafı da düğüm seçmelidir +@msg canceled iptal edildi +@msg cannot convert the object to a primitive value nesne ilkel bir değere dönüştürülemiyor +@msg cannot convert undefined or null to an object undefined veya null bir nesneye dönüştürülemez +@msg character dimensions cannot be represented with the source text transform karakter boyutları kaynak metin dönüşümüyle ifade edilemiyor +@msg character dimensions cannot be represented with the target text transform karakter boyutları hedef metin dönüşümüyle ifade edilemiyor +@msg continuation must be an array of path chunks continuation, yol parçalarından oluşan bir dizi olmalıdır +@msg continuation requires points continuation için points gerekir +@msg each path chunk must contain 1 to 4096 points her yol parçası 1 ile 4096 arasında nokta içermelidir +@msg each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v}) her seçim {{at: [x, y]}} veya {{rect: [x0, y0, x1, y1]}} biçimindedir (verilen: {v}) +@msg each weight must be a number of 0 or more (got {v}) her ağırlık 0 veya daha büyük bir sayı olmalıdır (verilen: {v}) +@msg finally table {t} out of range finally tablosu {t} aralık dışında +@msg flags cannot be given with a RegExp object RegExp nesnesiyle birlikte bayrak verilemez +@msg function declaration index out of range işlev bildirimi dizini aralık dışında +@msg give `char`, `text`, `code` or `unicode` `char`, `text`, `code` veya `unicode` verin +@msg give `count` or `spacing`, not both `count` veya `spacing` verin, ikisini birden değil +@msg give `name`, an SVG filter's name bir SVG filtresinin adı olan `name` değerini verin +@msg give `path`, an SVG file, or `svg`, SVG text bir SVG dosyası olan `path` veya SVG metni olan `svg` verin +@msg give `xml`, one SVG element tek bir SVG öğesi olan `xml` değerini verin +@msg give exactly one of `at`, `rect` and `points` `at`, `rect` ve `points` değerlerinden tam olarak birini verin +@msg give exactly one of `path`, `data` and `dataBase64` `path`, `data` ve `dataBase64` değerlerinden tam olarak birini verin +@msg give index or indexes, not both index veya indexes verin, ikisini birden değil +@msg give one element tek bir öğesi verin +@msg give opacity or blend opacity veya blend verin +@msg handler at {_1} expects {_2} values but its range starts with {d} {_1} konumundaki işleyici {_2} değer bekliyor, ancak aralığı {d} ile başlıyor +@msg handler depth too large işleyici derinliği çok büyük +@msg handler range {_1}..{_2} out of range işleyici aralığı {_1}..{_2} aralık dışında +@msg hiddenLayers must be true or false hiddenLayers true veya false olmalıdır +@msg hvcC hvcC +@msg images in a spot ink whose samples couldn't be read were imported in RGB örnekleri okunamayan spot mürekkepli görüntüler RGB olarak içe aktarıldı +@msg images past the most pixels one file may hold were left out bir dosyanın tutabileceği en fazla piksel sayısını aşan görüntüler dışarıda bırakıldı +@msg images too large to read were left out okunamayacak kadar büyük görüntüler dışarıda bırakıldı +@msg indexes may hold at most {MAX_GUIDE_INDEXES} entries indexes en fazla {MAX_GUIDE_INDEXES} girdi içerebilir +@msg indexes must be an array of guide indexes indexes, kılavuz dizinlerinden oluşan bir dizi olmalıdır +@msg instruction out of range yönerge aralık dışında +@msg instruction {pc} ({op}) pops below the stack {pc} numaralı yönerge ({op}) yığının altına iniyor +@msg instruction {pc} reached with stack depths {seen} and {d} {pc} numaralı yönergeye {seen} ve {d} yığın derinlikleriyle ulaşıldı +@msg invalid array length geçersiz dizi uzunluğu +@msg invalid group geçersiz grup +@msg invalid object id {v}: expected a non-negative integer geçersiz nesne kimliği {v}: negatif olmayan bir tam sayı bekleniyordu +@msg invalid regular expression flag '{_1}' geçersiz düzenli ifade bayrağı '{_1}' +@msg invalid regular expression: {m} geçersiz düzenli ifade: {m} +@msg invalid time value geçersiz zaman değeri +@msg is a confirm's answer, whose `value` must be true or false bir confirm yanıtıdır ve `value` değeri true veya false olmalıdır +@msg is a prompt's answer, whose `value` must be a string or null bir prompt yanıtıdır ve `value` değeri bir dize veya null olmalıdır +@msg is an alert's answer, whose `value` must be "ok" bir alert yanıtıdır ve `value` değeri "ok" olmalıdır +@msg is longer than 16 KiB 16 KiB'tan uzun +@msg it draws its image through a clipping path görüntüsünü bir kırpma yolu içinden çiziyor +@msg it draws no image hiçbir görüntü çizmiyor +@msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes {MAX_DICTIONARY_FILE_BYTES} bayttan büyük +@msg it isn't a file bir dosya değil +@msg it names {_1} plates, and at most {MAX_PLATES} are read {_1} kalıp belirtiyor ve en fazla {MAX_PLATES} tanesi okunuyor +@msg its art is too long or too detailed for a head resmi bir ok ucu için çok uzun veya çok ayrıntılı +@msg its art paints nothing resmi hiçbir şey boyamıyor +@msg its image is too large to read görüntüsü okunamayacak kadar büyük +@msg its plates are too large: more than {MAX_SAMPLES} pixels together kalıpları çok büyük: toplamda {MAX_SAMPLES} pikselden fazla +@msg its plates are too large: {_1} plates of {w} × {h} pixels kalıpları çok büyük: {w} × {h} piksellik {_1} kalıp +@msg its plates can't be kept together kalıpları bir arada tutulamıyor +@msg its shapes could not be combined into one şekilleri tek bir şekilde birleştirilemedi +@msg jump to {pc}, past the end sonun ötesindeki {pc} konumuna atlama +@msg legacyNameEncoding must be one of {_1} legacyNameEncoding şunlardan biri olmalıdır: {_1} +@msg localize: the first argument must be a localization object or a string localize: ilk bağımsız değişken bir yerelleştirme nesnesi veya bir dize olmalıdır +@msg missing `picks` `picks` eksik +@msg missing `word` `word` eksik +@msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır +@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir +@msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir +@msg needs a name bir ad gerekir +@msg needs a name of at most 64 bytes en fazla 64 baytlık bir ad gerekir +@msg needs a name of letters, digits and _, or a quoted name harf, rakam ve _ karakterlerinden oluşan bir ad veya tırnak içinde bir ad gerekir +@msg needs a name without control characters denetim karakteri içermeyen bir ad gerekir +@msg nesting too deep iç içe geçme çok derin +@msg no HP-GL format HP-GL biçimi yok +@msg no New Document profile called `{shown}` ({_1}) `{shown}` adlı bir Yeni Belge profili yok ({_1}) +@msg no SVG filter at index {k} {k} dizininde SVG filtresi yok +@msg no arrowheads file here burada ok uçları dosyası yok +@msg no character has code {code} hiçbir karakterin kodu {code} değil +@msg no custom arrowhead {name} (see stroke.arrowheads.list) {name} adlı özel ok ucu yok (bkz. stroke.arrowheads.list) +@msg no file to open açılacak dosya yok +@msg no instructions yönerge yok +@msg no layer to rename yeniden adlandırılacak katman yok +@msg no random numbers ({e}) rastgele sayı yok ({e}) +@msg no selected or given object has a visible 3D effect seçili veya verilen nesnelerin hiçbirinde görünür bir 3D efekti yok +@msg no such artboard {v} böyle bir çalışma yüzeyi yok: {v} +@msg no symbol named `{_1}` `{_1}` adlı bir sembol yok +@msg node {_1} already has the text variable `{_2}` {_1} düğümünde `{_2}` metin değişkeni zaten var +@msg not a DCS file bir DCS dosyası değil +@msg not a RegExp object bir RegExp nesnesi değil +@msg not a regular expression bir düzenli ifade değil +@msg not an action set: the text doesn't start with /version and a number bir eylem seti değil: metin /version ve bir sayıyla başlamıyor +@msg nothing to repeat yinelenecek bir şey yok +@msg numbers out of order in {_1} quantifier {_1} niceleyicisinde sayılar sırasız +@msg object {_1} needs a 3D effect {_1} nesnesinde bir 3D efekti olmalıdır +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Kalıp Çıkarma ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın +@msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front nesne {_1}: derinlik 0 olduğunda nesnenin tek yüzü vardır: grafiklerini ön yüze eşleyin +@msg object {_1}: {_2} nesne {_1}: {_2} +@msg object {_1}: {e} nesne {_1}: {e} +@msg object {_1}: {name} at index {index} has no lighting presets; set its lights with effect.setParams nesne {_1}: {index} dizinindeki {name} için ışık ön ayarı yok; ışıklarını effect.setParams ile ayarlayın +@msg opacity must be a number opacity bir sayı olmalıdır +@msg operand too large işlenen çok büyük +@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayıdır, `{v}` değil +@msg path chunks must share their boundary point yol parçaları sınır noktalarını paylaşmalıdır +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false, useArtboards false olduğunda düzenlenebilir resmi korumak için çalışma yüzeylerine ihtiyaç duyar +@msg point x must be a number noktanın x değeri bir sayı olmalıdır +@msg point y must be a number noktanın y değeri bir sayı olmalıdır +@msg points must be [x,y] pairs points [x,y] çiftleri olmalıdır +@msg points must be finite canvas points points sonlu tuval noktaları olmalıdır +@msg range out of order in character class karakter sınıfında aralık sırasız +@msg reduce of an empty array with no initial value başlangıç değeri olmadan boş bir dizide reduce +@msg regular expression flag '{_1}' given twice düzenli ifade bayrağı '{_1}' iki kez verildi +@msg sampled text would exceed the canvas (coordinates out of range) örneklenen metin tuvali aşacaktır (koordinatlar aralık dışındadır) +@msg select an SVG filter bir SVG filtresi seçin +@msg select an object with a 3D effect 3D efekti olan bir nesne seçin +@msg select an object with a 3D effect, or give its id in ids 3D efekti olan bir nesne seçin veya kimliğini ids içinde verin +@msg select one layer, group or object to rename yeniden adlandırmak için tek bir katman, grup veya nesne seçin +@msg select the art to weed ayıklanacak resmi seçin +@msg select type on a path or area type yol üzerindeki yazıyı veya alan metnini seçin +@msg side is left or right, not `{v}` side left veya right olur, `{v}` değil +@msg source text transform is collapsed or unrepresentable kaynak metin dönüşümü çökmüş veya ifade edilemiyor +@msg table must be true or false table true veya false olmalıdır +@msg takes one name tek bir ad alır +@msg target text transform is collapsed or unrepresentable hedef metin dönüşümü çökmüş veya ifade edilemiyor +@msg that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer bu çok fazla parça (en fazla 100000) veya kesik çizgi adımı oluşturuyor: çizgi desenini basitleştirin veya kesik çizgileri uzatın +@msg the Layers panel is not shown Katmanlar paneli gösterilmiyor +@msg the Layers panel's search, filter or Show Layers Only hides its row Katmanlar panelinin araması, filtresi veya Yalnızca Katmanları Göster seçeneği bu satırı gizliyor +@msg the Objects on Path group is hidden or locked Yol Üzerindeki Nesneler grubu gizli veya kilitli +@msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG dosyası {MAX_IMPORT_BYTES} bayttan büyük +@msg the XML operation needs an XML or XMLList value XML işlemi için bir XML veya XMLList değeri gerekir +@msg the XPath expression does not evaluate to a node-set XPath ifadesinin sonucu bir düğüm kümesi değil +@msg the XPath expression ends early XPath ifadesi erken bitiyor +@msg the XPath expression has an unmatched ) XPath ifadesinde eşleşmeyen bir ) var +@msg the XPath expression has an unmatched ] XPath ifadesinde eşleşmeyen bir ] var +@msg the XPath expression has an unmatched closing bracket XPath ifadesinde eşleşmeyen bir kapanış ayracı var +@msg the XPath expression selects a namespace node, which is not an XML value XPath ifadesi bir ad alanı düğümü seçiyor; bu bir XML değeri değildir +@msg the XPath expression selects the root node, which is not an XML value XPath ifadesi kök düğümü seçiyor; bu bir XML değeri değildir +@msg the XPath function {name} needs a node-set {name} XPath işlevi için bir düğüm kümesi gerekir +@msg the XPath function {name} takes the wrong number of arguments {name} XPath işlevine yanlış sayıda bağımsız değişken verildi +@msg the XPath name functions need a node-set XPath ad işlevleri için bir düğüm kümesi gerekir +@msg the XPath prefix {shown} is not bound to a namespace {shown} XPath öneki bir ad alanına bağlı değil +@msg the XPath variable ${shown} is not bound ${shown} XPath değişkeni bağlı değil +@msg the argument list is not an object bağımsız değişken listesi bir nesne değil +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it bir grafik serisindeki grafik tasarımının çizimi tasarımdan yeniden çizilir: değiştirmek için tasarımı düzenleyin +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out resim EPS için çok büyük: 256 MB'lık PostScript'ten sonrası dışarıda bırakıldı +@msg the bitmaps hold more pixels than one file may bitmapler bir dosyanın tutabileceğinden fazla piksel içeriyor +@msg the code runs past its last instruction kod son yönergesinin ötesine geçiyor +@msg the curve tolerance must be from 0.01 to 10 points eğri toleransı 0.01 ile 10 punto arasında olmalıdır +@msg the custom dictionary couldn't be saved to {_1}: {e} özel sözlük şuraya kaydedilemedi: {_1}: {e} +@msg the custom dictionary {_1} can't be read ({why}), so it is left as it is özel sözlük {_1} okunamıyor ({why}), bu yüzden olduğu gibi bırakıldı +@msg the document already has an SVG filter named {name} belgede {name} adlı bir SVG filtresi zaten var +@msg the document has another SVG filter named {name}: use svgFilter.apply, or svgFilter.define with `replace` to edit it belgede {name} adlı başka bir SVG filtresi var: svgFilter.apply kullanın veya düzenlemek için svgFilter.define komutunu `replace` ile kullanın +@msg the document has no SVG filter named {name} belgede {name} adlı bir SVG filtresi yok +@msg the document has no SVG filter named {r} belgede {r} adlı bir SVG filtresi yok +@msg the document has no color swatches belgede renk örneği yok +@msg the document's swatches hold {_1} colors; the document reduction takes at most 255 belgenin renk örnekleri {_1} renk içeriyor; belge azaltması en fazla 255 renk alır +@msg the file isn't valid SVG: {e} dosya geçerli bir SVG değil: {e} +@msg the file names no plate dosya hiçbir kalıp belirtmiyor +@msg the function's prototype is not an object işlevin prototipi bir nesne değil +@msg the guide is hidden or locked kılavuz gizli veya kilitli +@msg the library's file is outside the read roots kütüphanenin dosyası okuma köklerinin dışında +@msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında +@msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla +@msg the method needs an XML value yöntem için bir XML değeri gerekir +@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) +@msg the parameters or body do not form one function parametreler veya gövde tek bir işlev oluşturmuyor +@msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it yapıştırılan {name} SVG filtresi belgedeki aynı adlı filtreden farklı çiziyor ve ona uyan boş bir ad yok +@msg the paths are too many or too tangled to find where they cross yollar, kesiştikleri yerler bulunamayacak kadar çok veya karışık +@msg the pen table holds more than 255 pens kalem tablosu 255 taneden fazla kalem içeriyor +@msg the plates can't be kept kalıplar korunamıyor +@msg the position table does not match the instructions konum tablosu yönergelerle eşleşmiyor +@msg the prompt's text is longer than {MAX_PROMPT_BYTES} bytes istem metni {MAX_PROMPT_BYTES} bayttan uzun +@msg the radix must be between 2 and 36 taban 2 ile 36 arasında olmalıdır +@msg the rectangle or line reaches too many paths to check dikdörtgen veya çizgi denetlenemeyecek kadar çok yola ulaşıyor +@msg the right side of 'in' is not an object 'in' işlecinin sağ tarafı bir nesne değil +@msg the right side of 'instanceof' is not a function 'instanceof' işlecinin sağ tarafı bir işlev değil +@msg the selected art is nested more than {MAX_DEPTH} levels deep seçili resim {MAX_DEPTH} düzeyden daha derin iç içe geçmiş +@msg the selected art is too large to measure seçili resim ölçülemeyecek kadar büyük +@msg the selection has no outlines to weed around seçimde çevresi ayıklanacak anahat yok +@msg the value bind was called on is not a function bind'ın çağrıldığı değer bir işlev değil +@msg the value is not a constructor değer bir oluşturucu değil +@msg the value is not a function değer bir işlev değil +@msg the value is not a valid XML name değer geçerli bir XML adı değil +@msg the value is not an XML attribute name değer bir XML öznitelik adı değil +@msg the value is not an XML name değer bir XML adı değil +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines ayıklama çizgileri resmin anahatlarını ölçülemeyecek kadar çok kez kesiyor; daha az çizgi kullanın +@msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap ayıklama çizgileri ölçülemeyecek kadar çok anahat parçasının çok yakınından geçiyor; daha az çizgi veya daha küçük bir boşluk kullanın +@msg the weeding lines would be more than {max_pieces} pieces ayıklama çizgileri {max_pieces} parçadan fazla olurdu +@msg the {_1} plate lies outside the file {_1} kalıbı dosyanın dışında +@msg this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that bu ikili bir DXF dosyası ve okunamıyor: CAD uygulamasından ASCII DXF olarak kaydedip onu açın +@msg this warp's points can't be edited: use Reset with Mesh first bu çarpıtmanın noktaları düzenlenemez: önce Ağ ile Sıfırla komutunu kullanın +@msg toExponential() digits must be between 0 and 20 toExponential() basamak sayısı 0 ile 20 arasında olmalıdır +@msg toFixed() digits must be between 0 and 20 toFixed() basamak sayısı 0 ile 20 arasında olmalıdır +@msg toISOString is not a function toISOString bir işlev değil +@msg toPrecision() argument must be between 1 and 21 toPrecision() bağımsız değişkeni 1 ile 21 arasında olmalıdır +@msg toSource: a getter cannot be written as source toSource: bir alıcı kaynak olarak yazılamaz +@msg toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source toSource: öğelerinin yanında özellikleri, numaralandırılamayan bir özelliği veya başka bir prototipi olan bir dizi kaynak olarak yazılamaz +@msg toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source toSource: numaralandırılamayan bir özelliği olan veya prototipi Object.prototype olmayan bir nesne kaynak olarak yazılamaz +@msg toSource: the source is too long toSource: kaynak çok uzun +@msg toSource: the value contains itself toSource: değer kendini içeriyor +@msg toSource: the value has too many entries toSource: değer çok fazla girdi içeriyor +@msg toSource: the value is nested too deep toSource: değer çok derin iç içe geçmiş +@msg toString is not a function toString bir işlev değil +@msg too many arguments çok fazla bağımsız değişken +@msg too many quantifiers çok fazla niceleyici +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; prefix - to turn off; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take an alternate's number as `tag=N` with N from 0 to {_1}, as `salt=2`) bilinmeyen OpenType özelliği `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom, aalt; kapatmak için başına - koyun; swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom ve aalt bir alternatifin numarasını `tag=N` biçiminde alır, N 0 ile {_1} arasındadır, örneğin `salt=2`) +@msg unknown dither `{d}` (diffusion, pattern, noise or none) bilinmeyen renk taklidi `{d}` (diffusion, pattern, noise veya none) +@msg unknown panel `{panel}` bilinmeyen panel `{panel}` +@msg unknown parameter `{key}` bilinmeyen parametre `{key}` +@msg unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document) bilinmeyen azaltma `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform veya document) +@msg unmatched ')' eşleşmeyen ')' +@msg unterminated character class sonlandırılmamış karakter sınıfı +@msg unterminated group sonlandırılmamış grup +@msg wordGap and lineGap need area type in the selection wordGap ve lineGap için seçimde alan metni olmalıdır +@msg xpath needs its variables as an object xpath, değişkenlerini bir nesne olarak ister +@msg xpath needs the expression as a string xpath, ifadeyi bir dize olarak ister +@msg {GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {_1} to {_2}: {e} {GRANT_NOT_REMOVED}; ayrıca ayarları ve önbelleği {_1} konumundan {_2} konumuna geri taşınamıyor: {e} +@msg {_1} is not a folder: {e} {_1} bir klasör değil: {e} +@msg {_1}: {_2} and {_3} are in the way {_1}: {_2} ve {_3} engel oluyor +@msg {code}: {0} {code}: {0} +@msg {dir}: {e} {dir}: {e} +@msg {file} names more than one linked JavaScript file {file} birden fazla bağlantılı JavaScript dosyası belirtiyor +@msg {k}: a custom arrowhead's path needs an area to fill and at most {most} anchors and {most} subpaths, each anchor within {far} head units of its tip {k}: özel bir ok ucunun yolunda doldurulacak bir alan, en fazla {most} bağlantı noktası ve {most} alt yol olmalı, her bağlantı noktası ucundan en fazla {far} ok ucu birimi uzakta bulunmalıdır +@msg {k}: bad custom arrowhead path: {e} {k}: hatalı özel ok ucu yolu: {e} +@msg {k}: bad custom arrowhead: {e} {k}: hatalı özel ok ucu: {e} +@msg {k}: custom must be a name {k}: custom bir ad olmalıdır +@msg {name} must be a number {name} bir sayı olmalıdır +@msg {path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are {path}: copy bir DCS dosyasını yalnızca kalıpları içindeyse alır; kalıp dosyalarının bulunduğu yerde ona yeniden bağlayın +@msg {path}: larger than {_1} MB {path}: {_1} MB'tan büyük +@msg {shown} is not an XPath 1.0 function {shown} bir XPath 1.0 işlevi değil +@msg {v} names no layer or sublayer {v} hiçbir katmanı veya alt katmanı belirtmiyor +@msg {what} is not a function {what} bir işlev değil +@msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what} bir yaprağa {MAX_COPIES_PER_SHEET} taneden fazla kopya yazdırırdı: ölçeğini büyütün +@msg {what} {i} out of range {what} {i} aralık dışında +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. Bir profil tek bir Döndürme efektini destekler. Bunun yerine mevcut efektin seçeneklerini düzenleyin. +@msg Add Points at Crossings: a path went missing Kesişimlere Nokta Ekle: bir yol kayboldu +@msg CSS options: {e} CSS seçenekleri: {e} +@msg CSV has a header but no data rows CSV'de bir başlık var ama veri satırı yok +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark CSV, NUL baytları içeriyor: UTF-8 olarak veya bayt sırası işaretiyle UTF-16 olarak kaydedin +@msg CSV is empty CSV boş +@msg CSV is larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bayttan büyük +@msg CSV is not UTF-16 CSV, UTF-16 değil +@msg CSV is not UTF-8 CSV, UTF-8 değil +@msg CSV would be larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bayttan büyük olurdu +@msg Choose original artwork, not a dimension's generated paths Bir boyutun oluşturduğu yolları değil, özgün resmi seçin +@msg Contour: select paths or shapes Kontur: yolları veya şekilleri seçin +@msg Contour: the Offset Path effect is not available Kontur: Ofset Yolu efekti kullanılamıyor +@msg Create needs fills, strokes or both Oluştur için dolgular, konturlar veya her ikisi gerekir +@msg DXF options: {e} DXF seçenekleri: {e} +@msg DXF scale must be a positive number up to {_1}, not {scale} DXF ölçeği en fazla {_1} olan pozitif bir sayı olmalıdır, {scale} değil +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg Dimension is locked or hidden Boyut kilitli veya gizli +@msg Dimension mode does not match its source Boyut modu kaynağıyla eşleşmiyor +@msg Draw Inside needs exactly one selected path, compound path or text İçine Çiz için tam olarak bir seçili yol, bileşik yol veya metin gerekir +@msg EPS Save writes all artwork: use document.export for selected-only EPS EPS Kaydet tüm resmi yazar: yalnızca seçili resmi içeren EPS için document.export kullanın +@msg EPS flattener: {e} EPS düzleştirici: {e} +@msg EPS options: {e} EPS seçenekleri: {e} +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft Ekranlar için Dışa Aktar şunları yazar: png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai veya vectorcraft +@msg Flare click coordinates must be finite numbers Mercek parlaması tıklama koordinatları sonlu sayılar olmalıdır +@msg HTML Text applies to object slices of type only HTML Metni yalnızca metin nesnesi dilimlerine uygulanır +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) Nesneleri Tanımlama Ölçütü XML Kimliği: ad geçerli bir XML kimliği olmalıdır (harf, alt çizgi veya iki nokta ile başlar; boşluk içermez) +@msg Image Trace failed: internal error: its thread stopped (please report this bug) Görüntü İzleme başarısız oldu: iç hata: iş parçacığı durdu (lütfen bu hatayı bildirin) +@msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e} +@msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin +@msg Invalid dimension offset Geçersiz boyut ofseti +@msg Invalid point Geçersiz nokta +@msg Join: a subpath went missing Birleştir: bir alt yol kayboldu +@msg Lock Workspace is not available in VectorCraft Çalışma Alanını Kilitle, VectorCraft'ta kullanılamaz +@msg Move Panel to New Window is not available: floating panels stay in the main window Paneli Yeni Pencereye Taşı kullanılamaz: yüzen paneller ana pencerede kalır +@msg Offset Path: the path is too complex to offset Ofset Yolu: yol ofsetlenemeyecek kadar karmaşık +@msg Offset Path: {e} Ofset Yolu: {e} +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported PDF içeriği eksik veya okuyucunun sınırlarını aşıyor; hiçbir belge içe aktarılmadı +@msg PDF flattener: {e} PDF düzleştirici: {e} +@msg PDF options: {e} PDF seçenekleri: {e} +@msg Recolor Artwork is no longer open Resmi Yeniden Renklendir artık açık değil +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 SVG; UTF-8, UTF-16 veya ISO 8859-1 değil +@msg Save writes one artboard: name one, or export several with document.export Kaydet tek bir çalışma yüzeyi yazar: birini belirtin veya birkaçını document.export ile dışa aktarın +@msg Select a dimension first Önce bir boyut seçin +@msg Select dimensions to update Güncellenecek boyutları seçin +@msg Select only dimensions Yalnızca boyutları seçin +@msg Select two or more objects, or a group İki veya daha fazla nesne ya da bir grup seçin +@msg Shaper needs 1–64 source paths Şekillendirici için 1–64 kaynak yol gerekir +@msg Switch x/y is for scatter graphs x/y Değiştir dağılım grafikleri içindir +@msg Text options: {e} Metin seçenekleri: {e} +@msg `align` is start, center or end `align` start, center veya end olur +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors`, [subpath, anchor] çiftlerinden oluşan bir dizi olmalıdır +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {k} değil +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {v} değil +@msg `artboards` must be a list of artboard indices `artboards` bir çalışma yüzeyi dizinleri listesi olmalıdır +@msg `asset` is the asset id (see assets.list) `asset` varlık kimliğidir (bkz. assets.list) +@msg `at` must be a byte offset `at` bir bayt konumu olmalıdır +@msg `autoLeading` must be a number `autoLeading` bir sayı olmalıdır +@msg `background` must be "", "matte" or #rrggbb `background` "", "matte" veya #rrggbb olmalıdır +@msg `burasagari` must be "none", "standard" or "forced" `burasagari` "none", "standard" veya "forced" olmalıdır +@msg `center` must be [x, y] `center` [x, y] olmalıdır +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign` "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" veya "icfBottom" olmalıdır +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection` "default", "leftToRight" veya "rightToLeft" olmalıdır +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke` için `stroke: false`, `ids: []` gerekir ve `stop` verilmemelidir +@msg `clear` must be a list of type object ids, not {v} `clear` bir metin nesnesi kimlikleri listesi olmalıdır, {v} değil +@msg `clear` must list type objects; {_1} is not one `clear` metin nesnelerini listelemelidir; {_1} bir metin nesnesi değil +@msg `clear` must not list `id` `clear` içinde `id` yer almamalıdır +@msg `color` needs a `rule` to make the theme from `color` için temanın oluşturulacağı bir `rule` gerekir +@msg `colors` is empty `colors` boş +@msg `columnType` is vertical, uniform, repeating or sliding `columnType` vertical, uniform, repeating veya sliding olur +@msg `columns` must be a whole number 1..50 `columns` 1..50 arasında bir tam sayı olmalıdır +@msg `commands` must not be empty `commands` boş olmamalıdır +@msg `contents` goes with `to` `contents`, `to` ile birlikte kullanılır +@msg `corners` must be sharp, round or square, not `{other}` `corners` sharp, round veya square olmalıdır, `{other}` değil +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners` bağlantı noktası dizinlerini (0, 1, 2…) listelemelidir, {v} değil +@msg `count` must be a whole number from 1 to 100 `count` 1 ile 100 arasında bir tam sayı olmalıdır +@msg `dataBase64` is larger than the module limit `dataBase64` modül sınırından büyük +@msg `dataBase64` is not valid base64 `dataBase64` geçerli bir base64 değil +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`; `ids`, `reverse` veya `append` ile birleştirilemez +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` ve `childLimit` özeti dilimler: `summary: true` verin +@msg `design` is a design name, or null for plain columns `design` bir tasarım adıdır veya düz sütunlar için null olur +@msg `design` is a design name, or null for the default marker `design` bir tasarım adıdır veya varsayılan işaretçi için null olur +@msg `destinationFolder` is required when destination is `folder` destination `folder` olduğunda `destinationFolder` gereklidir +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination` `none`, `saveAndClose` veya `folder` olmalıdır +@msg `diameter` must be from 0.1 to 2500 pt `diameter` 0.1 ile 2500 pt arasında olmalıdır +@msg `digits` must be one of {_1} `digits` şunlardan biri olmalıdır: {_1} +@msg `dimImages` is a percentage or false `dimImages` bir yüzde veya false olur +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction` "auto", "leftToRight" veya "rightToLeft" olmalıdır +@msg `each` is the value one design stands for, more than 0 `each`, bir tasarımın temsil ettiği değerdir ve 0'dan büyüktür +@msg `end` must be "start" or "end" `end` "start" veya "end" olmalıdır +@msg `ends` applies to joining exactly two paths `ends` tam olarak iki yolun birleştirilmesi için geçerlidir +@msg `event` must be one of {_1} `event` şunlardan biri olmalıdır: {_1} +@msg `every` must be "all", "odd" or "even", not {v} `every` "all", "odd" veya "even" olmalıdır, {v} değil +@msg `expand` must be true or false `expand` true veya false olmalıdır +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files`, son text.findFontFiles aramasının bulduğu yazı tipi dosyalarının 1 ile 1000 arasında yolu olmalıdır +@msg `folder` must be an absolute folder path `folder` mutlak bir klasör yolu olmalıdır +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes`, eksen etiketleri ve değerlerinden oluşan bir nesne olmalıdır, örneğin {"wght"} +@msg `format` must be a string `format` bir dize olmalıdır +@msg `format` must be one of {_1} `format` şunlardan biri olmalıdır: {_1} +@msg `fractions` is chop or scale `fractions` chop veya scale olur +@msg `from` and `to` must differ `from` ve `to` farklı olmalıdır +@msg `from` has an empty frame `from` boş bir çerçeveye sahip +@msg `from` must be a non-negative integer `from` negatif olmayan bir tam sayı olmalıdır +@msg `from` must be area type or type on a path `from` alan metni veya yol üzerindeki yazı olmalıdır +@msg `gid` must be a glyph id, not {v} `gid` bir glif kimliği olmalıdır, {v} değil +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate` bir karakter stiline değil, tek bir karaktere aittir (text.setGlyphAlternate ayarlar) +@msg `guide` must be a guide index (guide.list) `guide` bir kılavuz dizini olmalıdır (guide.list) +@msg `hAlign` must be default, left, center or right `hAlign` default, left, center veya right olmalıdır +@msg `id` must be a node id `id` bir düğüm kimliği olmalıdır +@msg `id` must be an object id, not {v} `id` bir nesne kimliği olmalıdır, {v} değil +@msg `ids` must name Objects on Path groups or objects in them `ids`, Yol Üzerindeki Nesneler gruplarını veya bunların içindeki nesneleri belirtmelidir +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids` en fazla {MAX_INSPECT_IDS} kimlik alır +@msg `imageMap` must be none, rectangle or polygon `imageMap` none, rectangle veya polygon olmalıdır +@msg `includeArtboardFill` must be true or false `includeArtboardFill` true veya false olmalıdır +@msg `includeSubdirs` must be true or false `includeSubdirs` true veya false olmalıdır +@msg `index` must be a point index `index` bir nokta dizini olmalıdır +@msg `index` must be a whole number or null `index` bir tam sayı veya null olmalıdır +@msg `indices` must be a non-empty array of item indices `indices`, öğe dizinlerinden oluşan boş olmayan bir dizi olmalıdır +@msg `items` is a list of {kind, item} `items` bir {kind, item} listesidir +@msg `items` is empty `items` boş +@msg `items` must be a list of {id, points} `items` bir {id, points} listesi olmalıdır +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` bir {{id, anchors?}} listesi olmalıdır, {v} değil +@msg `items` must be an array of {id, anchors} `items` bir {id, anchors} dizisi olmalıdır +@msg `items` must be an array of {{id, corners?}}, not {v} `items` bir {{id, corners?}} dizisi olmalıdır, {v} değil +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida` "none", "short", "medium", "long" veya "stylistic" olmalıdır +@msg `kind` is one of {_1} `kind` şunlardan biridir: {_1} +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind` "round", "invertedRound" veya "chamfer" olmalıdır, {v} değil +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind` `text`, `visibility`, `image` veya `graph` olmalıdır +@msg `kind` must be a string `kind` bir dize olmalıdır +@msg `kind` must be image, noImage or htmlText `kind` image, noImage veya htmlText olmalıdır +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku` "none", "hard" veya "soft" olmalıdır +@msg `label` must be a non-empty name of at most 200 characters `label` en fazla 200 karakterlik, boş olmayan bir ad olmalıdır +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language` bir dil adı veya etiketi olmalıdır, örneğin "Turkish" veya "tr" +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel` "romanBaseline" veya "emBoxTop" olmalıdır +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading` 0.1 ile 5000 arasında veya Otomatik için null olmalıdır +@msg `length` must be a number of at most 1000000 pt either way `length` her iki yönde en fazla 1000000 pt olan bir sayı olmalıdır +@msg `line` must be true or false `line` true veya false olmalıdır +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°), `maxAngle` ({max_angle}°) değerinden büyük olamaz +@msg `mode` must be "handles", "straight" or "smooth" `mode` "handles", "straight" veya "smooth" olmalıdır +@msg `mode` must be "straight", "bezier" or "arc" `mode` "straight", "bezier" veya "arc" olmalıdır +@msg `mode` must be one of {_1} `mode` şunlardan biri olmalıdır: {_1} +@msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" veya "lineEndHalf" olmalıdır +@msg `names` is a list of preset names `names` bir ön ayar adları listesidir +@msg `names` lists preset names `names` ön ayar adlarını listeler +@msg `names` must be a list of names `names` bir ad listesi olmalıdır +@msg `names` must be a list of swatch names `names` bir renk örneği adları listesi olmalıdır +@msg `names` must be an array of style names `names` bir stil adları dizisi olmalıdır +@msg `new` is a design name, or true `new` bir tasarım adı veya true olur +@msg `path` must be a folder `path` bir klasör olmalıdır +@msg `path` must be a path object `path` bir yol nesnesi olmalıdır +@msg `pivot` must be a whole number from 0 to 8 `pivot` 0 ile 8 arasında bir tam sayı olmalıdır +@msg `points` must be a list of [x, y] points `points` bir [x, y] noktaları listesi olmalıdır +@msg `points` must be a list of point indexes `points` bir nokta dizinleri listesi olmalıdır +@msg `points` must be an array of point indices `points` bir nokta dizinleri dizisi olmalıdır +@msg `points` must be point indexes `points` nokta dizinleri olmalıdır +@msg `port` must be "in" or "out" `port` "in" veya "out" olmalıdır +@msg `position` is above or below `position` above veya below olur +@msg `preset` must be a string `preset` bir dize olmalıdır +@msg `ratio` must be from 0.1 to 0.5 `ratio` 0.1 ile 0.5 arasında olmalıdır +@msg `rect` must be [x, y, width, height] with a positive size `rect` pozitif boyutlu [x, y, width, height] olmalıdır +@msg `relation` must be overlap, inside or outside `relation` overlap, inside veya outside olmalıdır +@msg `reversed` must be true or false `reversed` true veya false olmalıdır +@msg `rotate` must be a finite number `rotate` sonlu bir sayı olmalıdır +@msg `rule` must be nonZero or evenOdd `rule` nonZero veya evenOdd olmalıdır +@msg `scale` must be a number in (0, 100] `scale` (0, 100] aralığında bir sayı olmalıdır +@msg `scope` must be "selection" or "document", not {other} `scope` "selection" veya "document" olmalıdır, {other} değil +@msg `script` must be a string `script` bir dize olmalıdır +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`, seri dizinlerinden oluşan boş olmayan bir listedir +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes` için bir `type` veya bir `valueAxis` gerekir +@msg `shift` must be a number of points `shift` punto cinsinden bir sayı olmalıdır +@msg `showCenter` must be true or false `showCenter` true veya false olmalıdır +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification` "fullJustify", "alignLeft", "alignCenter" veya "alignRight" olmalıdır +@msg `size` is a percentage of the base text's size, 1 to 100 `size`, temel metnin boyutunun yüzdesidir ve 1 ile 100 arasındadır +@msg `source` and `target` are the same object `source` ve `target` aynı nesne +@msg `source` must be `folder` or `datasets` `source` `folder` veya `datasets` olmalıdır +@msg `spacing` must be a number `spacing` bir sayı olmalıdır +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` punto cinsinden 0 veya daha büyük bir sayı ya da "auto" olmalıdır +@msg `start` must be a finite number `start` sonlu bir sayı olmalıdır +@msg `starts` must be an array of anchor indices (or nulls) `starts`, bağlantı noktası dizinlerinden (veya null değerlerinden) oluşan bir dizi olmalıdır +@msg `status` must be linked, embedded, missing or modified, or a list of them `status` linked, embedded, missing veya modified ya da bunların bir listesi olmalıdır +@msg `stop` must be a stop index `stop` bir durak dizini olmalıdır +@msg `story` styles the whole story: give no `start` or `end` `story` tüm metin akışına stil verir: `start` veya `end` vermeyin +@msg `story` takes the whole story: give no `start` or `end` `story` tüm metin akışını alır: `start` veya `end` vermeyin +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode` konturlar için geçerlidir (stroke: true) +@msg `style` must be roman or japanese `style` roman veya japanese olmalıdır +@msg `subpaths` must be two integer indices `subpaths` iki tam sayı dizini olmalıdır +@msg `symbol` must be a symbol name `symbol` bir sembol adı olmalıdır +@msg `target` must be "object" or "contents", not {v} `target` "object" veya "contents" olmalıdır, {v} değil +@msg `tint` applies to global and spot colours `tint` genel ve spot renkler için geçerlidir +@msg `tint` goes with a global or spot `swatch` `tint`, genel veya spot bir `swatch` ile birlikte kullanılır +@msg `tint` must be a number (%) `tint` bir sayı (%) olmalıdır +@msg `tint` needs a global or spot colour `tint` için genel veya spot bir renk gerekir +@msg `to` is already threaded `to` zaten zincirlenmiş +@msg `to` is the design's new name `to` tasarımın yeni adıdır +@msg `to` must be [x, y] `to` [x, y] olmalıdır +@msg `to` must be a closed path, area type or type on a path other than `from` `to`, `from` dışında kapalı bir yol, alan metni veya yol üzerindeki yazı olmalıdır +@msg `to` must be a whole number `to` bir tam sayı olmalıdır +@msg `to` takes the rows of one object's stack, not aligned rows `to` hizalanmış satırları değil, tek bir nesnenin yığınındaki satırları alır +@msg `useLab` must be true or false `useLab` true veya false olmalıdır +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign` default, top, middle, baseline veya bottom olmalıdır +@msg `values` must be a list `values` bir liste olmalıdır +@msg `values` must be an object `values` bir nesne olmalıdır +@msg `values` must name hex, rgb, cmyk, lab or gray `values` hex, rgb, cmyk, lab veya gray belirtmelidir +@msg `values` names a kind twice `values` bir türü iki kez belirtiyor +@msg `{_1}` can't be edited or removed `{_1}` düzenlenemez veya kaldırılamaz +@msg `{_1}` is built in and always listed `{_1}` yerleşiktir ve her zaman listelenir +@msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}`, son text.findFontFiles aramasının bulduğu bir yazı tipi dosyası değil +@msg `{_1}` would be overwritten by the package: choose a different folder or name paket `{_1}` üzerine yazardı: farklı bir klasör veya ad seçin +@msg `{file}` has no art to place `{file}` içinde yerleştirilecek resim yok +@msg `{file}` is over {_1} MB `{file}` {_1} MB'tan büyük +@msg `{f}` belongs to a VectorCraft that is running `{f}` çalışmakta olan bir VectorCraft'a ait +@msg `{f}` is the copy of a document open now `{f}` şu anda açık olan bir belgenin kopyası +@msg `{id}` is no writable format (see document.formats) `{id}` yazılabilir bir biçim değil (bkz. document.formats) +@msg `{id}` isn't a loaded library `{id}` yüklenmiş bir kütüphane değil +@msg `{key}` has no colours `{key}` renk içermiyor +@msg `{key}` is a design name `{key}` bir tasarım adıdır +@msg `{key}` is a design name or a list of them `{key}` bir tasarım adı veya tasarım adları listesidir +@msg `{key}` is longer than {MAX_NAME} characters `{key}` {MAX_NAME} karakterden uzun +@msg `{key}` is out of range `{key}` aralık dışında +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` yüzde cinsinden [min, desired, max] veya {{min?, desired?, max?}} olmalıdır +@msg `{key}` must be a non-negative integer `{key}` negatif olmayan bir tam sayı olmalıdır +@msg `{key}` must be a number {_1}..{_2} `{key}` {_1}..{_2} aralığında bir sayı olmalıdır +@msg `{key}` must be a whole number of at least 0, not {n} `{key}` en az 0 olan bir tam sayı olmalıdır, {n} değil +@msg `{key}` must be an appearance item index (paint order) or null `{key}` bir görünüm öğesi dizini (boyama sırası) veya null olmalıdır +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` bir varlık kimlikleri dizisi olmalıdır (bkz. assets.list) +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}` 0 ile 180 derece arasında olmalıdır, {a} değil +@msg `{key}` must be from {_1} to {shift_max} `{key}` {_1} ile {shift_max} arasında olmalıdır +@msg `{key}`: not a colour: {v} `{key}`: bir renk değil: {v} +@msg `{k}.family` is required `{k}.family` gereklidir +@msg `{k}` is a number 0..1 `{k}` 0..1 aralığında bir sayıdır +@msg `{k}` is true or false `{k}` true veya false olur +@msg `{k}` isn't an export setting: {_1} `{k}` bir dışa aktarma ayarı değil: {_1} +@msg `{k}` must be a byte offset `{k}` bir bayt konumu olmalıdır +@msg `{k}` must be a number `{k}` bir sayı olmalıdır +@msg `{k}` must be a number of points `{k}` punto cinsinden bir sayı olmalıdır +@msg `{k}` must be a string `{k}` bir dize olmalıdır +@msg `{k}` must be a whole number `{k}` bir tam sayı olmalıdır +@msg `{k}` must be from {lo} to {hi} for {key} {key} için `{k}` {lo} ile {hi} arasında olmalıdır +@msg `{k}` must be {what}, not {v} `{k}` {what} olmalıdır, {v} değil +@msg `{l}` isn't a global or spot colour `{l}` genel veya spot bir renk değil +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText `{m}` bir bitmap değil: clipboard.importSvg, importPdf veya importText kullanın +@msg `{name}` can't be deleted `{name}` silinemez +@msg `{name}` can't be duplicated `{name}` çoğaltılamaz +@msg `{name}` can't be edited `{name}` düzenlenemez +@msg `{name}` can't be edited this way `{name}` bu şekilde düzenlenemez +@msg `{name}` can't be renamed `{name}` yeniden adlandırılamaz +@msg `{name}` can't name a folder `{name}` bir klasörü belirtemez +@msg `{name}` has no art to place `{name}` içinde yerleştirilecek resim yok +@msg `{name}` has no text to place `{name}` içinde yerleştirilecek metin yok +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text Word belgesindeki `{name}`, UTF-8 veya UTF-16 metni değil +@msg `{name}` in the Word document is not well-formed XML: {e} Word belgesindeki `{name}` iyi biçimlendirilmiş bir XML değil: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep Word belgesindeki `{name}`, öğeleri {MAX_NESTING} düzeyden daha derin iç içe yerleştiriyor +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` yerleşik bir ön ayardır ve salt okunurdur: başka bir adla kaydedin +@msg `{name}` is a built-in preset: save under another name `{name}` yerleşik bir ön ayardır: başka bir adla kaydedin +@msg `{name}` is a built-in profile and stays `{name}` yerleşik bir profildir ve kalır +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}`, `{base}` renginin bir tonudur: `{base}` örneğini düzenleyin (bir ton renk örneği yalnızca yeni bir ad alır) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` bir çalışma alanıdır: önce edit.colorSettings ile başka birini seçin +@msg `{name}` is built in and stays `{name}` yerleşiktir ve kalır +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` kendi türünde bir boya alır (renk, degrade veya desen) +@msg `{n}` can't be deleted `{n}` silinemez +@msg `{n}` can't be merged `{n}` birleştirilemez +@msg `{n}` can't be moved `{n}` taşınamaz +@msg `{n}` is not a colour swatch `{n}` bir renk örneği değil +@msg `{n}` isn't a solid colour `{n}` düz bir renk değil +@msg `{n}`: colour groups hold solid colours only `{n}`: renk grupları yalnızca düz renkler içerir +@msg `{other}` doesn't trace an image `{other}` bir görüntüyü izlemez +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: adımın başvuruları {_1} MB'tan fazla değer kopyalıyor +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" `{tag}` bir eksen etiketi değil: bir etiket dört karakterdir, örneğin "wght" +@msg `{to}` is empty or already used `{to}` boş veya zaten kullanılıyor +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` {MAX_TEXT} bayttan uzun +@msg `{what}` must be text `{what}` metin olmalıdır +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard bir DXF çiziminin tek bir başlangıç noktası vardır: çalışma yüzeyi başına bir çizim için useArtboards: true verin +@msg a PDF presets file with over {_1} presets {_1} taneden fazla ön ayar içeren bir PDF ön ayarları dosyası +@msg a batch preview cannot switch documents bir toplu önizleme belge değiştiremez +@msg a brush named `{nn}` exists `{nn}` adlı bir fırça var +@msg a container of the listed objects is gone listelenen nesnelerin bir kapsayıcısı artık yok +@msg a content stream can't be read bir içerik akışı okunamıyor +@msg a content stream isn't a stream bir içerik akışı bir akış değil +@msg a design holds at most {_1} objects bir tasarım en fazla {_1} nesne içerir +@msg a design needs a name bir tasarımın adı olmalıdır +@msg a dictionary grew too large bir sözlük çok büyüdü +@msg a document keeps at most {_1} graph designs bir belge en fazla {_1} grafik tasarımı tutar +@msg a document keeps at most {_1} saved selections bir belge en fazla {_1} kayıtlı seçim tutar +@msg a document keeps at most {_1} views bir belge en fazla {_1} görünüm tutar +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files bir belge en fazla {MAX_SVG_SCRIPTS} JavaScript dosyasına bağlanır +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes bir feConvolveMatrix filtresinin order değeri {x}×{y}; bu, usvg'nin yaptığı çekirdek boyutu çarpımını taşırıyor +@msg a gradient preset is already called {n} {n} adlı bir degrade ön ayarı zaten var +@msg a graph has at most {_1} series, so it transposes with at most that many categories bir grafikte en fazla {_1} seri bulunur, bu yüzden en fazla o kadar kategoriyle yer değiştirir +@msg a layer can't be merged into its own sublayer bir katman kendi alt katmanıyla birleştirilemez +@msg a layer's form box isn't an array bir katmanın form kutusu bir dizi değil +@msg a layer's form can't be read bir katmanın formu okunamıyor +@msg a layer's form has no box bir katmanın formunda kutu yok +@msg a layer's form has no dictionary bir katmanın formunda sözlük yok +@msg a legend draws at most {MAX_CHIPS} swatches bir gösterge en fazla {MAX_CHIPS} renk örneği çizer +@msg a name names one asset: give multiple: false, or one object bir ad tek bir varlığı belirtir: multiple: false veya tek bir nesne verin +@msg a page can't be read bir sayfa okunamıyor +@msg a page object is used by something else bir sayfa nesnesi başka bir şey tarafından kullanılıyor +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) bir sayfa küçük resmi, kenar başına 1 ile {THUMBNAIL_SIZE} arasında RGB pikseller olmalıdır (verilen: {w} × {h}) +@msg a pattern layer doesn't end what it starts bir desen katmanı başlattığını bitirmiyor +@msg a pattern layer's colors hold something else bir desen katmanının renkleri başka bir şey içeriyor +@msg a pattern named `{n}` exists `{n}` adlı bir desen var +@msg a plug-in with id {_1} is already installed {_1} kimlikli bir eklenti zaten kurulu +@msg a preset named `{n}` exists `{n}` adlı bir ön ayar var +@msg a print presets file with over {_1} presets {_1} taneden fazla ön ayar içeren bir yazdırma ön ayarları dosyası +@msg a profile is already called {n} {n} adlı bir profil zaten var +@msg a row can't go into itself bir satır kendi içine giremez +@msg a series goes on the left or the right value axis bir seri sol veya sağ değer eksenine yerleşir +@msg a start must be an anchor index ≥ 0 or null bir başlangıç, ≥ 0 olan bir bağlantı noktası dizini veya null olmalıdır +@msg a style named `{name}` already exists `{name}` adlı bir stil zaten var +@msg a style named `{to}` already exists `{to}` adlı bir stil zaten var +@msg a swatch needs a colour, gradient or pattern bir renk örneği için renk, degrade veya desen gerekir +@msg a symbol named `{n}` already exists `{n}` adlı bir sembol zaten var +@msg a theme has 1 to {THEME_SIZE} colours bir temada 1 ile {THEME_SIZE} arasında renk bulunur +@msg a theme is already called {name} (replace: "{name}" overwrites it) {name} adlı bir tema zaten var (replace: "{name}" üzerine yazar) +@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter içerir +@msg a view named `{_1}` exists `{_1}` adlı bir görünüm var +@msg a view named `{name}` exists `{name}` adlı bir görünüm var +@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar +@msg a {_1} series can't go in a {_2} graph {_1} türünde bir seri {_2} türünde bir grafiğe konulamaz +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF uyumlu, varsayılan) veya "7" (eski .ai, sürüm 7) +@msg already editing an opacity mask zaten bir opaklık maskesi düzenleniyor +@msg already editing another object's opacity mask zaten başka bir nesnenin opaklık maskesi düzenleniyor +@msg already in pattern editing mode zaten desen düzenleme modunda +@msg an artboard is listed twice bir çalışma yüzeyi iki kez listelenmiş +@msg an empty artboard has no width or height to scale to boş bir çalışma yüzeyinin ölçeklenecek genişliği veya yüksekliği yoktur +@msg an image is too large for DXF and was left out bir görüntü DXF için çok büyük olduğundan dışarıda bırakıldı +@msg an image of {_1} MB, at most {_2} MB {_1} MB'lık bir görüntü, en fazla {_2} MB +@msg an image of {declared_w} × {declared_h} pixels is too large to draw {declared_w} × {declared_h} piksellik bir görüntü çizilemeyecek kadar büyük +@msg an image of {width} × {height} pixels is too large to draw {width} × {height} piksellik bir görüntü çizilemeyecek kadar büyük +@msg an index must be a whole number bir dizin tam sayı olmalıdır +@msg an inline graphic has no glyphs satır içi bir grafikte glif yok +@msg an invisible text form can't be read görünmez bir metin formu okunamıyor +@msg an object is missing bir nesne eksik +@msg an object's header is missing bir nesnenin üst bilgisi eksik +@msg an overprinting form can't be read üst baskılı bir form okunamıyor +@msg an unread object has no readable bounds okunmamış bir nesnenin okunabilir sınırları yok +@msg an unread object holds a frame of threaded type okunmamış bir nesne zincirli metnin bir çerçevesini içeriyor +@msg an unread object is missing from its layer okunmamış bir nesne katmanında eksik +@msg anchor `smooth` must be true or false bağlantı noktasının `smooth` değeri true veya false olmalıdır +@msg anchor `{key}` must be [x, y] bağlantı noktasının `{key}` değeri [x, y] olmalıdır +@msg anchor `{key}` must be a number bağlantı noktasının `{key}` değeri bir sayı olmalıdır +@msg angle and roundness must be finite açı ve yuvarlaklık sonlu olmalıdır +@msg angles must be a list as long as pins (degrees or null) angles, pins ile aynı uzunlukta bir liste olmalıdır (derece veya null) +@msg appearance must be flat|center|edge appearance flat|center|edge olmalıdır +@msg apply is "fill" or "stroke", not `{other}` apply "fill" veya "stroke" olur, `{other}` değil +@msg area must be a closed polygon of 3 to 100000 [x, y] points area, 3 ile 100000 arasında [x, y] noktasından oluşan kapalı bir çokgen olmalıdır +@msg area type needs a path that encloses an area alan metni için bir alanı çevreleyen bir yol gerekir +@msg area type {_1} is named twice alan metni {_1} iki kez belirtilmiş +@msg arrowAlign must be extend|tip, got {o} arrowAlign extend|tip olmalıdır, verilen: {o} +@msg arrowScale must be [start, end] arrowScale [start, end] olmalıdır +@msg artboard is a 0-based index artboard 0 tabanlı bir dizindir +@msg artboard must be a 0-based index artboard 0 tabanlı bir dizin olmalıdır +@msg artboard {i} doesn't print {i} numaralı çalışma yüzeyi yazdırılmıyor +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout {layout?, columns?, spacing?, rightToLeft?} olmalıdır +@msg artboardLayout.columns must be 1 or more artboardLayout.columns 1 veya daha büyük olmalıdır +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout gridByRow, gridByColumn, row veya column olmalıdır +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft true veya false olmalıdır +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing 0–{MAX_SPACING} pt olmalıdır +@msg artboards must be a non-empty list artboards boş olmayan bir liste olmalıdır +@msg artboards must be a number artboards bir sayı olmalıdır +@msg asset `{_1}` has no art to export `{_1}` varlığında dışa aktarılacak resim yok +@msg at most {MAX_KEYWORDS} keywords en fazla {MAX_KEYWORDS} anahtar sözcük +@msg at most {MAX_MATCHES} matches are kept en fazla {MAX_MATCHES} eşleşme tutulur +@msg at most {MAX_POINTS} points en fazla {MAX_POINTS} nokta +@msg at most {MAX_QUEUE} files en fazla {MAX_QUEUE} dosya +@msg at must be [x, y] at [x, y] olmalıdır +@msg at/rect lie outside the canvas at/rect tuvalin dışında kalıyor +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute size|leading|tracking|kerning|baselineShift olmalıdır +@msg attrs must be an object attrs bir nesne olmalıdır +@msg automation path rejected: the folder's name isn't valid text otomasyon yolu reddedildi: klasörün adı geçerli bir metin değil +@msg automation path rejected: {_1} isn't valid text otomasyon yolu reddedildi: {_1} geçerli bir metin değil +@msg automation path rejected: {why}: {path} otomasyon yolu reddedildi: {why}: {path} +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis "vertical", "horizontal" veya derece cinsinden bir açı olmalıdır, `{given}` değil +@msg backgroundContents must be transparent or white backgroundContents transparent veya white olmalıdır +@msg bad AES key hatalı AES anahtarı +@msg bad `runs`: {e} hatalı `runs`: {e} +@msg bad arrowScale hatalı arrowScale +@msg bad base64 hatalı base64 +@msg bad color {c} hatalı renk {c} +@msg bad colour hatalı renk +@msg bad colour in `colors` `colors` içinde hatalı renk +@msg bad colour {v} hatalı renk {v} +@msg bad colour {v} in groupColors groupColors içinde hatalı renk {v} +@msg bad cross-reference entry hatalı çapraz başvuru girdisi +@msg bad cross-reference table hatalı çapraz başvuru tablosu +@msg bad current colour {v} hatalı geçerli renk {v} +@msg bad dataBase64 hatalı dataBase64 +@msg bad edit hatalı düzenleme +@msg bad fill {v} hatalı dolgu {v} +@msg bad fit: {e} hatalı fit: {e} +@msg bad model {other} (keep, new or document) hatalı model {other} (keep, new veya document) +@msg bad new colour {v} hatalı yeni renk {v} +@msg bad object hatalı nesne +@msg bad object number hatalı nesne numarası +@msg bad offset hatalı konum +@msg bad path data: {e} hatalı yol verisi: {e} +@msg bad point {v}: expected [x, y] or [x, y, pressure] hatalı nokta {v}: [x, y] veya [x, y, pressure] bekleniyordu +@msg bad reference hatalı başvuru +@msg bad trailer size hatalı trailer boyutu +@msg bad {k} colour hatalı {k} rengi +@msg batches cannot nest toplu işlemler iç içe olamaz +@msg bind something to a variable first önce bir şeyi bir değişkene bağlayın +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed 0–{MAX_BLEED} pt olmalıdır: bir sayı, [top, bottom, left, right] veya {{top, bottom, left, right}} +@msg brush must be a name or null brush bir ad veya null olmalıdır +@msg by must be a number by bir sayı olmalıdır +@msg can't add page thumbnails: {why} sayfa küçük resimleri eklenemiyor: {why} +@msg can't add the editing data for other apps: {why} diğer uygulamalar için düzenleme verileri eklenemiyor: {why} +@msg can't edit the written PDF: {why} yazılan PDF düzenlenemiyor: {why} +@msg can't encrypt the PDF: {why} PDF şifrelenemiyor: {why} +@msg can't linearise the PDF: {why} PDF doğrusallaştırılamıyor: {why} +@msg can't open `{_1}`: {_2} `{_1}` açılamıyor: {_2} +@msg can't open `{_1}`: {e} `{_1}` açılamıyor: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) `{name}` açılamıyor: VectorCraft'ın okuduğu bir biçim değil (bkz. document.formats) +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) `{name}` yerleştirilemiyor: VectorCraft'ın okuduğu bir biçim değil (bkz. document.formats) +@msg can't read back the written PDF: {e} yazılan PDF geri okunamıyor: {e} +@msg can't read this Word document: {why} bu Word belgesi okunamıyor: {why} +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp .{e} görüntüleri yazılamıyor: .png, .jpg, .gif, .webp, .tif veya .bmp kullanın +@msg can't write PDF layers, overprint or invisible text: {why} PDF katmanları, üst baskı veya görünmez metin yazılamıyor: {why} +@msg can't write the file's copyright: {why} dosyanın telif hakkı yazılamıyor: {why} +@msg can't write the file's modification date: {why} dosyanın değiştirilme tarihi yazılamıyor: {why} +@msg can't write the pages' user units: {why} sayfaların kullanıcı birimleri yazılamıyor: {why} +@msg cannot distort a zero-size or non-finite bounding box sıfır boyutlu veya sonlu olmayan bir sınırlayıcı kutu çarpıtılamaz +@msg cannot move an object into itself bir nesne kendi içine taşınamaz +@msg case must be upper|lower|title|sentence case upper|lower|title|sentence olmalıdır +@msg category `{c}`: one of {_1} kategori `{c}`: şunlardan biri: {_1} +@msg center must be [x, y] center [x, y] olmalıdır +@msg choose at least one artboard en az bir çalışma yüzeyi seçin +@msg choose at least one status en az bir durum seçin +@msg clip must be true or false clip true veya false olmalıdır +@msg clippingMask must be true or false clippingMask true veya false olmalıdır +@msg closed must be a boolean closed bir mantıksal değer olmalıdır +@msg collapsed must be true or false collapsed true veya false olmalıdır +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: “{profile}” adlı bir RGB veya CMYK profili yok +@msg colorMode must be rgb or cmyk, not `{m}` colorMode rgb veya cmyk olmalıdır, `{m}` değil +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel {own} (belgenin modu), grayscale veya bitmap olmalıdır +@msg colour groups can't go into colour groups renk grupları renk gruplarının içine konulamaz +@msg colour, mode and spot apply to solid-colour swatches only colour, mode ve spot yalnızca düz renkli renk örnekleri için geçerlidir +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sütun {column}: `{cell}`, grafik veri dosyalarının bir `%` sütunudur ve bu dosyalar okunmaz +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sütun {column}: `{cell}`, {_1} türünde bir değişken olan `{name}` değişkenini belirtiyor +@msg column {column}: `{cell}` names no variable sütun {column}: `{cell}` hiçbir değişkeni belirtmiyor +@msg column {column}: the variable name is longer than {MAX_NAME} characters sütun {column}: değişken adı {MAX_NAME} karakterden uzun +@msg column: true floats the whole column and takes no onto, above or below column: true tüm sütunu yüzdürür ve onto, above veya below almaz +@msg command must be a shape.* command command bir shape.* komutu olmalıdır +@msg commands[{i}]: missing `command` commands[{i}]: `command` eksik +@msg composer must be "singleLine" or "everyLine" composer "singleLine" veya "everyLine" olmalıdır +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes bileşik şekiller yolları, bileşik yolları, grupları, bileşik şekilleri, metni, karışımları ve zarfları alır +@msg compound {_1} must contain exactly one open path to join bileşik {_1}, birleştirilecek tam olarak bir açık yol içermelidir +@msg connect needs a path other than the one extended connect için uzatılan yoldan başka bir yol gerekir +@msg connect needs id connect için id gerekir +@msg connect path has no open end connect yolunun açık ucu yok +@msg copy needs path: the file to copy into the document's folder copy için path gerekir: belgenin klasörüne kopyalanacak dosya +@msg copy takes images only: relink placed documents where their files are copy yalnızca görüntüleri alır: yerleştirilmiş belgeleri dosyalarının bulunduğu yerde yeniden bağlayın +@msg copying a file isn't available on the web dosya kopyalama web'de kullanılamaz +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus unknown, copyrighted veya publicDomain olmalıdır +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl bir URL olmalıdır (boşluksuz, en fazla 2048 karakter) +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners 4 adet [x, y] noktası olmalıdır (TL, TR, BR, BL) +@msg counterPer `{c}`: item or file counterPer `{c}`: item veya file +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" crop `{_1}`: yalnızca PDF sayfalarında art, trim, bleed ve media kutuları bulunur; "crop" veya "bounding" kullanın +@msg crop rectangle doesn't overlap the image kırpma dikdörtgeni görüntüyle örtüşmüyor +@msg cross-reference and object streams aren't supported çapraz başvuru ve nesne akışları desteklenmiyor +@msg damaged compressed data: {e} hasarlı sıkıştırılmış veri: {e} +@msg dash lengths must be numbers, got {v} kesik çizgi uzunlukları sayı olmalıdır, verilen: {v} +@msg dash must be a list of lengths or null, got {v} dash bir uzunluk listesi veya null olmalıdır, verilen: {v} +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) veri anahtarı `{k}`: harfler, rakamlar, -, _ ve . (name veya vc-… olamaz) +@msg data must be an object of key: value, not {v} data bir key: value nesnesi olmalıdır, {v} değil +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare `{name}` veri kümesi, kütüphanenin bildirmediği `{var}` için bir değer içeriyor +@msg data set `{name}` holds two values for `{var}` `{name}` veri kümesi `{var}` için iki değer içeriyor +@msg data set `{name}` is declared twice `{name}` veri kümesi iki kez bildirilmiş +@msg data takes at most {MAX_DATA} keys at once data bir seferde en fazla {MAX_DATA} anahtar alır +@msg dataset `{name}` already exists `{name}` veri kümesi zaten var +@msg dataset `{to}` already exists `{to}` veri kümesi zaten var +@msg date `{d}`: YYYY-MM-DD tarih `{d}`: YYYY-MM-DD +@msg decoded data is too large kodu çözülen veri çok büyük +@msg define a variable first önce bir değişken tanımlayın +@msg detect must be true or false detect true veya false olmalıdır +@msg direct-select anchor points of a path bir yolun bağlantı noktalarını doğrudan seçin +@msg distance must be > 0 distance > 0 olmalıdır +@msg dx and dy give the arrow's direction dx ve dy okun yönünü verir +@msg dx and dy must be numbers dx ve dy sayı olmalıdır +@msg dxf fitTo must be [width, height], positive dxf fitTo pozitif [width, height] olmalıdır +@msg dxf must be an object of DXF import options dxf, DXF içe aktarma seçeneklerinden oluşan bir nesne olmalıdır +@msg dxf scale must be a positive number up to {_1}, not {s} dxf scale en fazla {_1} olan pozitif bir sayı olmalıdır, {s} değil +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf unit `{u}`: mm, cm, in veya pt gibi bir birim +@msg dxf: {e} dxf: {e} +@msg each format is an object {format, scale?, suffix?} her biçim bir {format, scale?, suffix?} nesnesidir +@msg each item needs an id her öğe için bir id gerekir +@msg each match needs `kind` her eşleşme için `kind` gerekir +@msg each match needs a `name` her eşleşme için bir `name` gerekir +@msg each of `fonts` is {family, style?}; 1 to 1000 of them `fonts` öğelerinin her biri {family, style?} biçimindedir; 1 ile 1000 arasında öğe +@msg each of `items` is {kind, item} `items` öğelerinin her biri {kind, item} biçimindedir +@msg each of `items` is {{id, corners?}} with an object id, not {it} `items` öğelerinin her biri nesne kimliği içeren {{id, corners?}} biçimindedir, {it} değil +@msg each row needs `from` her satır için `from` gerekir +@msg each stop needs a position her durak için bir konum gerekir +@msg each subpath needs an anchors array her alt yol için bir anchors dizisi gerekir +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType easeIn, easeOut, easeInOut veya easeOutIn olmalıdır +@msg editingData must be true or false editingData true veya false olmalıdır +@msg editingData must be true, false or "always" editingData true, false veya "always" olmalıdır +@msg edits overlap düzenlemeler çakışıyor +@msg effects of objects whose appearances differ can't be moved together görünümleri farklı olan nesnelerin efektleri birlikte taşınamaz +@msg empty header in column {_1} {_1} sütununda boş başlık +@msg encoding `{_1}`: utf8 or utf16 encoding `{_1}`: utf8 veya utf16 +@msg ends must be two of "first" and "last" ends, "first" ve "last" değerlerinden iki tane olmalıdır +@msg every numbered name for the result is taken sonuç için numaralı adların tümü kullanılıyor +@msg expanded SVG styles exceed the import size limit genişletilmiş SVG stilleri içe aktarma boyut sınırını aşıyor +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes dışa aktarma ön ayarları dosyası {MAX_PRESET_FILE_BYTES} bayttan büyük +@msg exportText must be editable or appearance exportText editable veya appearance olmalıdır +@msg exportType must be movieClip or graphic, not `{s}` exportType movieClip veya graphic olmalıdır, `{s}` değil +@msg extend needs id extend için id gerekir +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges en fazla {MAX_FEATURE_CHANGES} etiket listeler +@msg featureChanges must be a list of tags featureChanges bir etiket listesi olmalıdır +@msg features must be a list of tags features bir etiket listesi olmalıdır +@msg fidelity must be 0..100 fidelity 0..100 olmalıdır +@msg files must be {name, dataBase64} files {name, dataBase64} olmalıdır +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit none|autoHeight|shrinkText|block olmalıdır, verilen: {id} +@msg flattener: {e} düzleştirici: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low veya kayıtlı bir ön ayar (bkz. flattener.presets.list) +@msg flipProfile must be along|across, got {o} flipProfile along|across olmalıdır, verilen: {o} +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none, rows, format, item veya itemFormat +@msg folders deeper than {MAX_BATCH_DEPTH} levels {MAX_BATCH_DEPTH} düzeyden daha derin klasörler +@msg folders deeper than {MAX_DEPTH} levels {MAX_DEPTH} düzeyden daha derin klasörler +@msg font family `{family}` is not available `{family}` yazı tipi ailesi kullanılamıyor +@msg font family `{tf}` is not available `{tf}` yazı tipi ailesi kullanılamıyor +@msg format `{f}`: pdf or postscript format `{f}`: pdf veya postscript +@msg format `{f}`: text or json format `{f}`: text veya json +@msg format is `{format}` format `{format}` +@msg formats must be an array of rows, not {v} formats bir satır dizisi olmalıdır, {v} değil +@msg frequency must be between 1 and 300 lines per inch frequency inç başına 1 ile 300 çizgi arasında olmalıdır +@msg from and to must be finite from ve to sonlu olmalıdır +@msg from must be [x0, y0, x1, y1] from [x0, y0, x1, y1] olmalıdır +@msg give `before` or `after`, not both `before` veya `after` verin, ikisini birden değil +@msg give `colors`, or `color` and `rule` `colors` verin ya da `color` ve `rule` verin +@msg give `event`, such as onclick onclick gibi bir `event` verin +@msg give `file`, the JavaScript file's path or URL JavaScript dosyasının yolu veya URL'si olan `file` değerini verin +@msg give `fill` and/or `stroke` `fill` ve/veya `stroke` verin +@msg give `fill`, `stroke` or both `fill`, `stroke` veya her ikisini verin +@msg give `folder` `folder` verin +@msg give `fonts`, or open a document `fonts` verin veya bir belge açın +@msg give `from` or `indices`, not both `from` veya `indices` verin, ikisini birden değil +@msg give `id` (no text is being edited) `id` verin (düzenlenen bir metin yok) +@msg give `id` and `anchors`, or `items`, not both `id` ve `anchors` ya da `items` verin, ikisini birden değil +@msg give `id` or `guide`, not both `id` veya `guide` verin, ikisini birden değil +@msg give `length` or `to` `length` veya `to` verin +@msg give `matches`: [{kind, name, target}] `matches` verin: [{kind, name, target}] +@msg give `name` (or edit a pattern) `name` verin (veya bir deseni düzenleyin) +@msg give `name` or `names` `name` veya `names` verin +@msg give `path` (a .wasm file) or `dataBase64` (the module) `path` (bir .wasm dosyası) veya `dataBase64` (modül) verin +@msg give `path`, `data` or `dataBase64` `path`, `data` veya `dataBase64` verin +@msg give `path`, `data`, `dataBase64` or `csv` `path`, `data`, `dataBase64` veya `csv` verin +@msg give `path`, `xml` or `dataBase64` `path`, `xml` veya `dataBase64` verin +@msg give `script`, the JavaScript the event runs ("" removes the event) olayın çalıştırdığı JavaScript olan `script` değerini verin ("" olayı kaldırır) +@msg give `text` (the reading) or `remove` `text` (okunuş) veya `remove` verin +@msg give `x` and `y` (and a `tolerance` of 0 or more) `x` ve `y` verin (ve 0 veya daha büyük bir `tolerance`) +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments bir mod ya da r/g/b, c/m/y/k, gray veya tint ayarlamaları verin +@msg give a name, or paint the active proxy with a saved preset bir ad verin veya etkin vekili kayıtlı bir ön ayarla boyayın +@msg give a name, or select a stroke with a saved profile bir ad verin veya kayıtlı profili olan bir kontur seçin +@msg give a pattern name or select an object painted with a pattern bir desen adı verin veya desenle boyanmış bir nesne seçin +@msg give at least one of clip, invert, disabled, linked şunlardan en az birini verin: clip, invert, disabled, linked +@msg give color, none, swatch or gradient color, none, swatch veya gradient verin +@msg give dataBase64 dataBase64 verin +@msg give either at (a click) or area (a path drawn around the overlaps) at (bir tıklama) veya area (çakışmaların çevresine çizilen bir yol) verin +@msg give formats or a preset, not both formats veya bir ön ayar verin, ikisini birden değil +@msg give newName or delete newName veya delete verin +@msg give offset or by offset veya by verin +@msg give one of `to`, `rect` or `at` `to`, `rect` veya `at` değerlerinden birini verin +@msg give one of assets, layers, selection or fullDocument assets, layers, selection veya fullDocument değerlerinden birini verin +@msg give only one of onto, above, below, icon and a column place onto, above, below, icon ve bir sütun yerinden yalnızca birini verin +@msg give origin: [x, y], or reset: true origin: [x, y] veya reset: true verin +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note overprintFill, overprintStroke, showCenter, imageMap, url veya note verin +@msg give path (a file) or folder path (bir dosya) veya folder verin +@msg give path, or name and dataBase64 path ya da name ve dataBase64 verin +@msg give paths or files paths veya files verin +@msg give rows, rowHeight, columns or columnWidth rows, rowHeight, columns veya columnWidth verin +@msg give svg, or dataBase64 of an SVG or SVGZ file svg ya da bir SVG veya SVGZ dosyasının dataBase64 değerini verin +@msg give text text verin +@msg give the asset a name varlığa bir ad verin +@msg give the preset a `name` ön ayara bir `name` verin +@msg give the preset a name ön ayara bir ad verin +@msg give the preset a name (1–64 characters) ön ayara bir ad verin (1–64 karakter) +@msg give the settings to change, e.g. {"formats"}]} değiştirilecek ayarları verin, örneğin {"formats"}]} +@msg give the style a name stile bir ad verin +@msg give two or more style `names` iki veya daha fazla stil için `names` verin +@msg give two or more swatches iki veya daha fazla renk örneği verin +@msg give x, y, or a handle's length or angle x, y ya da bir tutamacın uzunluğunu veya açısını verin +@msg give {key, value} or {values} {key, value} veya {values} verin +@msg global must be true or false global true veya false olmalıdır +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) {_1} glifi, karakterin stiliyle (Tümü Büyük Harf, Küçük Büyük Harf veya bir rakam sistemi gibi) {ch} için çizilmiyor +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} {g} glifi, {_1} {_2} içinde {ch} karakterinin bir alternatifi değil +@msg gradient must be "objects" or "mesh" gradient "objects" veya "mesh" olmalıdır +@msg grays must be "profile" or "black", not `{g}` grays "profile" veya "black" olmalıdır, `{g}` değil +@msg gridColors must be a preset name or two colours gridColors bir ön ayar adı veya iki renk olmalıdır +@msg gridSize must be small, medium or large gridSize small, medium veya large olmalıdır +@msg guide {g} is not selected {g} numaralı kılavuz seçili değil +@msg handle must be 0..3 handle 0..3 olmalıdır +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (varsayılan), "omit" veya "visible" +@msg highlight a layer to merge into içine birleştirilecek bir katmanı vurgulayın +@msg highlight two or more rows in one layer or group tek bir katman veya gruptaki iki veya daha fazla satırı vurgulayın +@msg highlight two or more rows to merge birleştirmek için iki veya daha fazla satırı vurgulayın +@msg icon docks a panel in the icon column: use window.panel.dock icon bir paneli simge sütununa yerleştirir: window.panel.dock kullanın +@msg id must be a dimension id id bir boyut kimliği olmalıdır +@msg image has no bounds görüntünün sınırları yok +@msg image {_1} is linked already {_1} görüntüsü zaten bağlantılı +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client veya server +@msg index out of range dizin aralık dışında +@msg instances must be 1..1000 instances 1..1000 olmalıdır +@msg invalid `color` geçersiz `color` +@msg invalid anchor index {v}: expected a non-negative integer geçersiz bağlantı noktası dizini {v}: negatif olmayan bir tam sayı bekleniyordu +@msg invalid anchor reference {v}: expected [subpath, anchor] geçersiz bağlantı noktası başvurusu {v}: [subpath, anchor] bekleniyordu +@msg invalid angle geçersiz açı +@msg invalid brush: {e} geçersiz fırça: {e} +@msg invalid color geçersiz renk +@msg invalid colour {c} geçersiz renk {c} +@msg invalid delta geçersiz delta +@msg invalid point geçersiz nokta +@msg invalid size geçersiz boyut +@msg invalid t geçersiz t +@msg invalid tolerance geçersiz tolerans +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) çalışma yüzeylerinin tümü tuvalin dışında kalıyor (başlangıç noktasından {_1} pt'den uzak) +@msg its clipping masks are nested too deeply kırpma maskeleri çok derin iç içe geçmiş +@msg its metadata has no description meta verilerinde açıklama yok +@msg its metadata has no direct length meta verilerinde doğrudan bir uzunluk yok +@msg join two different paths iki farklı yolu birleştirin +@msg justify must be auto|left|center|right|justifyAll justify auto|left|center|right|justifyAll olmalıdır +@msg kbps must be a positive number, not {kbps} kbps pozitif bir sayı olmalıdır, {kbps} değil +@msg keywords must be a list of words or a comma-separated string keywords bir sözcük listesi veya virgülle ayrılmış bir dize olmalıdır +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters anahtar sözcükler en fazla {MAX_KEYWORD} karakter olmalı ve denetim karakteri içermemelidir +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind 1, 2 veya 3 olmalıdır ya da bir ön ayar için `name` verin (bkz. perspective.presets.list) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle veya paraStyle olmalıdır +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout "on", "off", "neutral" veya bir mantıksal değer olmalıdır, {v} değil +@msg layer `{name}` has no art to export `{name}` katmanında dışa aktarılacak resim yok +@msg layer must name a layer or sublayer layer bir katmanı veya alt katmanı belirtmelidir +@msg layers can't be intertwined: select the objects in them katmanlar iç içe geçirilemez: içlerindeki nesneleri seçin +@msg layers go only at the top level or in layers, objects in layers and groups katmanlar yalnızca en üst düzeye veya katmanların içine, nesneler ise katmanların ve grupların içine yerleşir +@msg layers must be true or false layers true veya false olmalıdır +@msg layout must be gridByRow, gridByColumn, row or column layout gridByRow, gridByColumn, row veya column olmalıdır +@msg leading must be a number or "auto" leading bir sayı veya "auto" olmalıdır +@msg left/right must be non-negative widths left/right negatif olmayan genişlikler olmalıdır +@msg level `{t}`: 2 or 3 level `{t}`: 2 veya 3 +@msg line {line}: more than {MAX_CSV_COLS} columns satır {line}: {MAX_CSV_COLS} taneden fazla sütun +@msg line {line}: unclosed quote satır {line}: kapatılmamış tırnak +@msg line {line}: value for `{var}` must match its variable kind satır {line}: `{var}` değeri değişkeninin türüyle eşleşmelidir +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf veya crlf +@msg loading profiles from disk isn't available in the browser diskten profil yükleme tarayıcıda kullanılamaz +@msg margin: a {m} pt margin leaves no imageable area on the paper margin: {m} pt'lik bir kenar boşluğu kâğıtta yazdırılabilir alan bırakmıyor +@msg matrix must be finite and invertible, depth finite matrix sonlu ve tersinir, depth ise sonlu olmalıdır +@msg matte: {e} matte: {e} +@msg member is for order front, forward, backward or back member; order değeri front, forward, backward veya back olduğunda kullanılır +@msg missing `artboards` `artboards` eksik +@msg missing `at` [x, y] `at` [x, y] eksik +@msg missing `attrs` `attrs` eksik +@msg missing `color` or `opacity` `color` veya `opacity` eksik +@msg missing `colors` `colors` eksik +@msg missing `commands` `commands` eksik +@msg missing `destinationFolder` `destinationFolder` eksik +@msg missing `effect` id `effect` kimliği eksik +@msg missing `family` `family` eksik +@msg missing `find` `find` eksik +@msg missing `gid` (a glyph id, or null for the default glyph) `gid` eksik (bir glif kimliği veya varsayılan glif için null) +@msg missing `group` `group` eksik +@msg missing `id` `id` eksik +@msg missing `id`: give one, or select one type object `id` eksik: bir tane verin veya tek bir metin nesnesi seçin +@msg missing `index` (a point index, or null to clear) `index` eksik (bir nokta dizini veya temizlemek için null) +@msg missing `index` (a stop index, or null to clear) `index` eksik (bir durak dizini veya temizlemek için null) +@msg missing `index` (an item index or null) `index` eksik (bir öğe dizini veya null) +@msg missing `item` `item` eksik +@msg missing `library` `library` eksik +@msg missing `library` (see graphicStyle.libraries) `library` eksik (bkz. graphicStyle.libraries) +@msg missing `library` (see swatch.library.list) `library` eksik (bkz. swatch.library.list) +@msg missing `map` (rows [{from, to}] or {current}) `map` eksik (satırlar [{from, to}] veya {current}) +@msg missing `matrix` [a,b,c,d,e,f] `matrix` [a,b,c,d,e,f] eksik +@msg missing `name` (see gradient.presets.list) `name` eksik (bkz. gradient.presets.list) +@msg missing `offset` (a distance in points) `offset` eksik (punto cinsinden bir uzaklık) +@msg missing `path` `path` eksik +@msg missing `path` (a path object id) `path` eksik (bir yol nesnesi kimliği) +@msg missing `rule` `rule` eksik +@msg missing `source` id `source` kimliği eksik +@msg missing `start` (the byte offset of a character) `start` eksik (bir karakterin bayt konumu) +@msg missing `status`: linked, embedded, missing or modified `status` eksik: linked, embedded, missing veya modified +@msg missing `target` id `target` kimliği eksik +@msg missing `text` `text` eksik +@msg missing `to` `to` eksik +@msg missing `to` (an index) `to` eksik (bir dizin) +@msg missing `to`: a non-negative integer `to` eksik: negatif olmayan bir tam sayı +@msg missing `type` `type` eksik +@msg missing `value` `value` eksik +@msg missing `{key}` `{key}` eksik +@msg missing `{k}` `{k}` eksik +@msg missing anchor bağlantı noktası eksik +@msg missing anchors bağlantı noktaları eksik +@msg missing anchors [[subpath, anchor]…] anchors [[subpath, anchor]…] eksik +@msg missing array `{key}` `{key}` dizisi eksik +@msg missing case case eksik +@msg missing color renk eksik +@msg missing commands komutlar eksik +@msg missing destination folder hedef klasör eksik +@msg missing from from eksik +@msg missing group grup eksik +@msg missing id or ids id veya ids eksik +@msg missing ids ids eksik +@msg missing indexes indexes eksik +@msg missing matrix [a,b,c,d,e,f] matrix [a,b,c,d,e,f] eksik +@msg missing name ad eksik +@msg missing op op eksik +@msg missing or invalid `color` `color` eksik veya geçersiz +@msg missing or unknown `tool` `tool` eksik veya bilinmiyor +@msg missing point nokta eksik +@msg missing point [x,y] [x,y] noktası eksik +@msg missing point `{key}` ([x, y]) `{key}` noktası eksik ([x, y]) +@msg missing points noktalar eksik +@msg missing points [[x,y]…] points [[x,y]…] eksik +@msg missing segment parça eksik +@msg missing stops duraklar eksik +@msg missing subpaths alt yollar eksik +@msg missing target hedef eksik +@msg missing to to eksik +@msg missing x, y x, y eksik +@msg mode is set, add or toggle, not `{other}` mode set, add veya toggle olur, `{other}` değil +@msg mode must be "cmyk" or "rgb" mode "cmyk" veya "rgb" olmalıdır +@msg mode must be area|onPath, got {o} mode area|onPath olmalıdır, verilen: {o} +@msg more than 10000 linked files: package dependencies in smaller parts 10000 taneden fazla bağlantılı dosya: bağımlılıkları daha küçük parçalar hâlinde paketleyin +@msg more than 256 commands 256 taneden fazla komut +@msg more than {MAX_BATCH_FILES} data sets {MAX_BATCH_FILES} taneden fazla veri kümesi +@msg more than {MAX_BATCH_FILES} files {MAX_BATCH_FILES} taneden fazla dosya +@msg more than {MAX_CSV_ROWS} data rows {MAX_CSV_ROWS} taneden fazla veri satırı +@msg more than {MAX_FILES} images {MAX_FILES} taneden fazla görüntü +@msg more than {MAX_IMPORT} presets {MAX_IMPORT} taneden fazla ön ayar +@msg moved must be [[x,y]…] moved [[x,y]…] olmalıdır +@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gereklidir +@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır +@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır +@msg names is empty names boş +@msg names must be an array of symbol names names bir sembol adları dizisi olmalıdır +@msg need `anchor` or `segment` + `t` `anchor` veya `segment` + `t` gerekir +@msg need at least one anchor en az bir bağlantı noktası gerekir +@msg need at least one point en az bir nokta gerekir +@msg need at least two points en az iki nokta gerekir +@msg needs points noktalar gerekir +@msg nineSlice must be true or false nineSlice true veya false olmalıdır +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides, her biri -16..16 aralığında, left + right < 1 ve top + bottom < 1 olacak şekilde [left, top, right, bottom] olmalıdır +@msg no PDF preset named `{n}` `{n}` adlı bir PDF ön ayarı yok +@msg no action set is current geçerli bir eylem seti yok +@msg no active data set etkin veri kümesi yok +@msg no appearance item {index} {index} numaralı görünüm öğesi yok +@msg no artboard {_1} {_1} numaralı çalışma yüzeyi yok +@msg no artboard {artboard} (0-based; the document has {_1}) {artboard} numaralı çalışma yüzeyi yok (0 tabanlı; belgede {_1} tane var) +@msg no asset {id} {id} kimlikli varlık yok +@msg no asset {id} (see assets.list) {id} kimlikli varlık yok (bkz. assets.list) +@msg no assets to export dışa aktarılacak varlık yok +@msg no assets yet: collect art for export first (assets.add) henüz varlık yok: önce dışa aktarılacak resmi toplayın (assets.add) +@msg no brush named `{n}` `{n}` adlı bir fırça yok +@msg no character at byte {start} {start} numaralı baytta karakter yok +@msg no colour renk yok +@msg no colour group `{group}` `{group}` renk grubu yok +@msg no colour group `{name}` `{name}` renk grubu yok +@msg no data sets veri kümesi yok +@msg no dataset named `{from}` `{from}` adlı bir veri kümesi yok +@msg no dataset named `{name}` `{name}` adlı bir veri kümesi yok +@msg no datasets veri kümesi yok +@msg no design named `{name}` `{name}` adlı bir tasarım yok +@msg no design named `{n}` `{n}` adlı bir tasarım yok +@msg no design named `{old}` `{old}` adlı bir tasarım yok +@msg no encoder for {_1} yet {_1} için henüz bir kodlayıcı yok +@msg no export preset `{name}` (see document.exportPresets.list) `{name}` adında dışa aktarma ön ayarı yok (bkz. document.exportPresets.list) +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder klasör yok: `path` verin veya Tercihler › Eklentiler ve Çalışma Diskleri › Ek Eklentiler Klasörü ayarını yapın +@msg no fonts to look for: they are all available aranacak yazı tipi yok: tümü kullanılabilir +@msg no formats to export dışa aktarılacak biçim yok +@msg no gradient preset `{name}` (see gradient.presets.list) `{name}` degrade ön ayarı yok (bkz. gradient.presets.list) +@msg no graphic style `{n}` in `{_1}` `{_1}` içinde `{n}` grafik stili yok +@msg no graphic style library `{key}` (see graphicStyle.libraries) `{key}` grafik stili kütüphanesi yok (bkz. graphicStyle.libraries) +@msg no guide selected seçili kılavuz yok +@msg no guide selected (or give an index) seçili kılavuz yok (veya bir dizin verin) +@msg no guide {i} {i} numaralı kılavuz yok +@msg no images in the folder klasörde görüntü yok +@msg no item at index {_1} {_1} dizininde öğe yok +@msg no item at index {from} {from} dizininde öğe yok +@msg no item at one of the indices {idx} {idx} dizinlerinden birinde öğe yok +@msg no layer katman yok +@msg no layer {id} (see layer.list) {id} kimlikli katman yok (bkz. layer.list) +@msg no layers to export dışa aktarılacak katman yok +@msg no library `{key}` `{key}` kütüphanesi yok +@msg no metafile format meta dosya biçimi yok +@msg no object {_1} {_1} nesnesi yok +@msg no objects nesne yok +@msg no parent layer üst katman yok +@msg no perspective grid preset named `{b}` (see perspective.presets.list) `{b}` adlı bir perspektif ızgarası ön ayarı yok (bkz. perspective.presets.list) +@msg no perspective grid preset named `{n}` `{n}` adlı bir perspektif ızgarası ön ayarı yok +@msg no point selected (give `index`) seçili nokta yok (`index` verin) +@msg no preset called `{from}` (see file.newPresets) `{from}` adlı bir ön ayar yok (bkz. file.newPresets) +@msg no preset called `{name}` (see file.newPresets) `{name}` adlı bir ön ayar yok (bkz. file.newPresets) +@msg no preset named `{n}` `{n}` adlı bir ön ayar yok +@msg no print preset named `{b}` (see print.presets.list) `{b}` adlı bir yazdırma ön ayarı yok (bkz. print.presets.list) +@msg no print preset named `{name}` (presets: {_1}) `{name}` adlı bir yazdırma ön ayarı yok (ön ayarlar: {_1}) +@msg no print preset named `{n}` `{n}` adlı bir yazdırma ön ayarı yok +@msg no profile named `{name}` `{name}` adlı bir profil yok +@msg no readable files in the folder klasörde okunabilir dosya yok +@msg no recovery copy `{f}` (see file.recovery.list) `{f}` kurtarma kopyası yok (bkz. file.recovery.list) +@msg no rows satır yok +@msg no saved PDF preset named `{name}` `{name}` adlı kayıtlı bir PDF ön ayarı yok +@msg no saved export preset `{name}` `{name}` adlı kayıtlı bir dışa aktarma ön ayarı yok +@msg no saved gradient preset called {name} {name} adlı kayıtlı bir degrade ön ayarı yok +@msg no saved gradient presets kayıtlı degrade ön ayarı yok +@msg no saved preset called `{name}` `{name}` adlı kayıtlı bir ön ayar yok +@msg no saved presets to export (name [Default] in `names` to export it) dışa aktarılacak kayıtlı ön ayar yok ([Default] ön ayarını dışa aktarmak için `names` içinde belirtin) +@msg no saved presets to export (name built-in ones in `names`) dışa aktarılacak kayıtlı ön ayar yok (yerleşik olanları `names` içinde belirtin) +@msg no saved print preset named `{name}` `{name}` adlı kayıtlı bir yazdırma ön ayarı yok +@msg no saved profile called {name} {name} adlı kayıtlı bir profil yok +@msg no saved selection `{name}` `{name}` adlı kayıtlı bir seçim yok +@msg no saved theme called {name} (see colorTheme.list) {name} adlı kayıtlı bir tema yok (bkz. colorTheme.list) +@msg no saved views kayıtlı görünüm yok +@msg no series {i} {i} numaralı seri yok +@msg no slice {n} in the image (see slice.list) görüntüde {n} numaralı dilim yok (bkz. slice.list) +@msg no source art kaynak resim yok +@msg no stop {i} (the gradient has {n}) {i} numaralı durak yok (degradede {n} tane var) +@msg no style `{name}` `{name}` stili yok +@msg no such assets (see assets.list) böyle varlıklar yok (bkz. assets.list) +@msg no such frame anchor, or the frame would reach past the canvas böyle bir çerçeve bağlantı noktası yok veya çerçeve tuvalin dışına taşardı +@msg no such objects böyle nesneler yok +@msg no such path anchor, or the path would reach past the canvas böyle bir yol bağlantı noktası yok veya yol tuvalin dışına taşardı +@msg no such rows böyle satırlar yok +@msg no swatch `{keep}` `{keep}` renk örneği yok +@msg no swatch `{n}` `{n}` renk örneği yok +@msg no swatch `{n}` (swatches and colour groups move separately) `{n}` renk örneği yok (renk örnekleri ve renk grupları ayrı ayrı taşınır) +@msg no swatch library `{key}` (see swatch.library.list) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list; "document": belgenin renk örnekleri) +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) `{key}` renk örneği kütüphanesi yok (bkz. swatch.library.list; "{DOCUMENT_SWATCHES}": belgenin renk örnekleri) +@msg no swatch named `{n}` `{n}` adlı bir renk örneği yok +@msg no swatch or colour group `{n}` `{n}` adlı bir renk örneği veya renk grubu yok +@msg no swatch or colour group `{n}` in `{_1}` `{_1}` içinde `{n}` adlı bir renk örneği veya renk grubu yok +@msg no symbol named `{name}` `{name}` adlı bir sembol yok +@msg no text objects selected seçili metin nesnesi yok +@msg no toolbar named `{_1}` `{_1}` adlı bir araç çubuğu yok +@msg no toolbar named `{name}` `{name}` adlı bir araç çubuğu yok +@msg no tracing preset `{preset}` (see imageTrace.presets) `{preset}` izleme ön ayarı yok (bkz. imageTrace.presets) +@msg no user library folder here (save with a path, or without one to get the data) burada kullanıcı kütüphanesi klasörü yok (bir yolla kaydedin veya verileri almak için yol vermeden kaydedin) +@msg no variable named `{from}` `{from}` adlı bir değişken yok +@msg no variable named `{name}` `{name}` adlı bir değişken yok +@msg no variable named `{var}` `{var}` adlı bir değişken yok +@msg no variable named `{v}` `{v}` adlı bir değişken yok +@msg no view named `{name}` `{name}` adlı bir görünüm yok +@msg node {_1} is not a graph {_1} düğümü bir grafik değil +@msg node {_1} is not an image {_1} düğümü bir görüntü değil +@msg node {_1} is not type {_1} düğümü metin değil +@msg not a PDF presets file (format `{_1}`) bir PDF ön ayarları dosyası değil (biçim `{_1}`) +@msg not a PDF presets file: {e} bir PDF ön ayarları dosyası değil: {e} +@msg not a Word document: its WordDocument stream doesn't start with a file information block bir Word belgesi değil: WordDocument akışı bir dosya bilgi bloğuyla başlamıyor +@msg not a Word document: its compound file has no WordDocument stream bir Word belgesi değil: bileşik dosyasında WordDocument akışı yok +@msg not a Word document: its main part is not a WordprocessingML document bir Word belgesi değil: ana bölümü bir WordprocessingML belgesi değil +@msg not a Word document: its package has no main document part bir Word belgesi değil: paketinde ana belge bölümü yok +@msg not a closed path kapalı bir yol değil +@msg not a flattener presets file (format `{_1}`) bir düzleştirici ön ayarları dosyası değil (biçim `{_1}`) +@msg not a flattener presets file: {e} bir düzleştirici ön ayarları dosyası değil: {e} +@msg not a layer or group bir katman veya grup değil +@msg not a library file: {e} bir kütüphane dosyası değil: {e} +@msg not a mesh envelope point bir ağ zarfı noktası değil +@msg not a perspective grid presets file (format `{_1}`) bir perspektif ızgarası ön ayarları dosyası değil (biçim `{_1}`) +@msg not a perspective grid presets file: {e} bir perspektif ızgarası ön ayarları dosyası değil: {e} +@msg not a print presets file (format `{_1}`) bir yazdırma ön ayarları dosyası değil (biçim `{_1}`) +@msg not a print presets file: {e} bir yazdırma ön ayarları dosyası değil: {e} +@msg not a stored or deflated central record saklanmış veya deflate ile sıkıştırılmış bir merkezi kayıt değil +@msg not a valid SVGZ file: {e} geçerli bir SVGZ dosyası değil: {e} +@msg not an image VectorCraft reads (see document.formats) VectorCraft'ın okuduğu bir görüntü değil (bkz. document.formats) +@msg not area type (text in a frame) outside perspective perspektif dışında alan metni (çerçeve içindeki metin) değil +@msg not editing an opacity mask bir opaklık maskesi düzenlenmiyor +@msg not type on a path outside perspective perspektif dışında yol üzerindeki yazı değil +@msg nothing prints hiçbir şey yazdırılmıyor +@msg nothing to bind bağlanacak bir şey yok +@msg nothing to change değiştirilecek bir şey yok +@msg nothing to change: give dx, dy, hScale, vScale or rotation değiştirilecek bir şey yok: dx, dy, hScale, vScale veya rotation verin +@msg nothing to crop kırpılacak bir şey yok +@msg nothing to export dışa aktarılacak bir şey yok +@msg nothing to export: the document has no visible art dışa aktarılacak bir şey yok: belgede görünür resim yok +@msg nothing to mark işaretlenecek bir şey yok +@msg nothing to print: every artboard picked is blank yazdırılacak bir şey yok: seçilen her çalışma yüzeyi boş +@msg nothing to print: the document has no art that prints yazdırılacak bir şey yok: belgede yazdırılan resim yok +@msg object is not a path nesne bir yol değil +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object nesne saydamlığı vurgulanan karakterlere örneklenemez; Damlalık Seçenekleri'nde Saydamlık seçeneğini kapatın veya nesnenin tamamını seçin +@msg object {_1} can't be set as point type {_1} nesnesi nokta metni olarak ayarlanamaz +@msg object {_1} has lost its file's contents: relink it {_1} nesnesi dosyasının içeriğini kaybetti: yeniden bağlayın +@msg object {_1} has no path {_1} nesnesinin yolu yok +@msg object {_1} has no size {_1} nesnesinin boyutu yok +@msg object {_1} is hidden or locked, or on a locked artboard {_1} nesnesi gizli veya kilitli ya da kilitli bir çalışma yüzeyinde +@msg object {_1} is not a placed document {_1} nesnesi yerleştirilmiş bir belge değil +@msg object {_1} is not an Intertwine group {_1} nesnesi bir İç İçe Geçme grubu değil +@msg object {_1} is not an image {_1} nesnesi bir görüntü değil +@msg object {_1} is not an image or a linked file {_1} nesnesi bir görüntü veya bağlantılı bir dosya değil +@msg object {_1} is not an image or a placed document {_1} nesnesi bir görüntü veya yerleştirilmiş bir belge değil +@msg object {_1} is not in this Intertwine group {_1} nesnesi bu İç İçe Geçme grubunda değil +@msg object {_1} needs a 3D effect at index {index} {_1} nesnesinin {index} dizininde bir 3D efekti olmalıdır +@msg object {id} has anchors 0–{_1} for `corners`, not {past} {id} nesnesinde `corners` için 0–{_1} bağlantı noktaları var, {past} yok +@msg object {id} has {n} anchors, so no anchor {past} {id} nesnesinde {n} bağlantı noktası var, bu yüzden {past} numaralı bağlantı noktası yok +@msg objects must be none, move or copy objects none, move veya copy olmalıdır +@msg objects were left out nesneler dışarıda bırakıldı +@msg offset out of range konum aralık dışında +@msg on must be true or false on true veya false olmalıdır +@msg only groups, layers, type and images have a Contents (Characters) row yalnızca grupların, katmanların, metnin ve görüntülerin bir İçerik (Karakterler) satırı vardır +@msg only interior mesh lines can be deleted yalnızca iç ağ çizgileri silinebilir +@msg only solid colours can be added (not gradients or patterns) yalnızca düz renkler eklenebilir (degradeler veya desenler eklenemez) +@msg only solid-colour swatches can be spot colours yalnızca düz renkli renk örnekleri spot renk olabilir +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi: uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın veya önce Affinity'den SVG ya da PDF olarak dışa aktarın +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi; uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto, above, below, icon ve bir sütun yeri window.panel.float ve window.panel.dock komutlarına aittir +@msg onto, above, below, icon and a column place take no anchor, side, zone or before onto, above, below, icon ve bir sütun yeri anchor, side, zone veya before almaz +@msg onto, above, below, icon and a column place take no x, y, width or height onto, above, below, icon ve bir sütun yeri x, y, width veya height almaz +@msg open a document to look for its linked files bağlantılı dosyalarını aramak için bir belge açın +@msg options must be an object (see file.formatOptions) options bir nesne olmalıdır (bkz. file.formatOptions) +@msg order must be leftToRight or rightToLeft order leftToRight veya rightToLeft olmalıdır +@msg orientation must be portrait or landscape, not `{o}` orientation portrait veya landscape olmalıdır, `{o}` değil +@msg outlineText {v}: true or false outlineText {v}: true veya false +@msg output intent profile: {e} çıktı amacı profili: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: “{name}” adlı bir RGB veya CMYK profili yok +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} dosyaları CMYK'dir ve “{name}” bir RGB profilidir +@msg output.destination: {e} output.destination: {e} +@msg output.inks: no ink is set to print output.inks: yazdırılmak üzere ayarlanmış mürekkep yok +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: “{name}” adlı bir profil yok ve bir {std} çıktı amacı profilini gömer +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: “{name}” adlı bir profil yok: bir {std} çıktı amacı bir profil gömer veya kayıtlı bir baskı koşulunu belirtir (outputConditionId ve registry) +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std} dosyaları CMYK olarak yazdırılır ve “{name}” bir RGB profilidir +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: “{name}” bir gri profildir ve bir {std} çıktı amacı olamaz +@msg overlap: {o} pt is half a tile or more overlap: {o} pt bir döşemenin yarısı veya daha fazlası +@msg overlapping Shaper paths must be in the same layer or group çakışan Şekillendirici yolları aynı katmanda veya grupta olmalıdır +@msg overlapping edits çakışan düzenlemeler +@msg page art conflicts with image data for {key} sayfa resmi {key} için görüntü verileriyle çakışıyor +@msg page art conflicts with pattern {name} sayfa resmi {name} deseniyle çakışıyor +@msg page art conflicts with swatch {name} sayfa resmi {name} renk örneğiyle çakışıyor +@msg page art is missing image data for {key} sayfa resminde {key} için görüntü verileri eksik +@msg page art is missing pattern {name} sayfa resminde {name} deseni eksik +@msg page art is missing swatch {name} sayfa resminde {name} renk örneği eksik +@msg page must be a whole number from 1 page 1'den başlayan bir tam sayı olmalıdır +@msg page thumbnail: {e} sayfa küçük resmi: {e} +@msg page {page} of the PDF has no objects PDF'nin {page} numaralı sayfasında nesne yok +@msg page {page}: `{file}` has {n} {artboards} sayfa {page}: `{file}` içinde {n} {artboards} var +@msg page {page}: `{name}` has {n} {pages} sayfa {page}: `{name}` içinde {n} {pages} var +@msg pages must be a range such as "2-3" or a page number, not {v} pages "2-3" gibi bir aralık veya bir sayfa numarası olmalıdır, {v} değil +@msg pages: {e} pages: {e} +@msg panel position must be finite panel konumu sonlu olmalıdır +@msg parameters must be an object parametreler bir nesne olmalıdır +@msg params must be an object params bir nesne olmalıdır +@msg passwords can have up to {MAX_PASSWORD} bytes parolalar en fazla {MAX_PASSWORD} bayt olabilir +@msg path has no open end yolun açık ucu yok +@msg paths must be strings paths dizelerden oluşmalıdır +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false, düzenlenebilir resmi korumak için her çalışma yüzeyine ihtiyaç duyar +@msg pdfs `{m}`: single or multiple pdfs `{m}`: single veya multiple +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom "artwork" veya "swatches" olur, {v} değil +@msg pins and moved must be non-empty lists of the same length pins ve moved aynı uzunlukta, boş olmayan listeler olmalıdır +@msg pins must be [[x,y]…] pins [[x,y]…] olmalıdır +@msg pins must be finite pins sonlu olmalıdır +@msg place is above, below or inside, not `{other}` place above, below veya inside olur, `{other}` değil +@msg plane must be left|right|ground plane left|right|ground olmalıdır +@msg plane must be left|right|ground|none plane left|right|ground|none olmalıdır +@msg point is outside the mesh nokta ağın dışında +@msg points must be [t, left, right] with non-negative widths points, negatif olmayan genişliklerle [t, left, right] olmalıdır +@msg points must be a non-empty [[x,y,pressure?]…] list points boş olmayan bir [[x,y,pressure?]…] listesi olmalıdır +@msg points must be a non-empty list of finite [x,y] points, sonlu [x,y] değerlerinden oluşan boş olmayan bir liste olmalıdır +@msg points must be an array or null points bir dizi veya null olmalıdır +@msg points must be finite points sonlu olmalıdır +@msg points must be finite [x,y] pairs points sonlu [x,y] çiftleri olmalıdır +@msg points must contain 1–4096 coordinates points 1–4096 koordinat içermelidir +@msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır +@msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır +@msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır +@msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil +@msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil +@msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır +@msg preset `{id}`: mobile or density preset `{id}`: mobile veya density +@msg preset must be standard, diffuse, topLeft or right preset standard, diffuse, topLeft veya right olmalıdır +@msg preset must be the name of a print preset preset bir yazdırma ön ayarının adı olmalıdır +@msg previewMode must be default, pixel or overprint previewMode default, pixel veya overprint olmalıdır +@msg print settings: {e} yazdırma ayarları: {e} +@msg procedures nest too deeply yordamlar çok derin iç içe geçiyor +@msg procedures nested too deeply yordamlar çok derin iç içe geçmiş +@msg quotes must be {double?, single?} quotes {double?, single?} olmalıdır +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" quotes.{k} bir açılış ve bir kapanış tırnağı olmalıdır, örneğin "“”" +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi 1–2400 olmalıdır (72 ekran, 150 orta, 300 yüksek) +@msg rating must be a whole number from 0 to {MAX_RATING} rating 0 ile {MAX_RATING} arasında bir tam sayı olmalıdır +@msg rect and {k} contradict each other: give the area or the artboards rect ve {k} birbiriyle çelişiyor: alanı veya çalışma yüzeylerini verin +@msg rect applies to raster formats, not {_1} rect raster biçimler için geçerlidir, {_1} için değil +@msg rect is [x, y, width, height] in points rect punto cinsinden [x, y, width, height] olur +@msg rect must be [x, y, width, height] rect [x, y, width, height] olmalıdır +@msg rect must be [x, y, width, height] with a positive width and height rect, pozitif genişlik ve yükseklikle [x, y, width, height] olmalıdır +@msg rect needs finite numbers and a positive width and height rect için sonlu sayılar ile pozitif bir genişlik ve yükseklik gerekir +@msg redraw needs id redraw için id gerekir +@msg redraw within must be a finite distance of 0 or more redraw within 0 veya daha büyük sonlu bir uzaklık olmalıdır +@msg registration must be 0..8 registration 0..8 olmalıdır +@msg release a layer or a group bir katmanı veya grubu serbest bırakın +@msg replace keeps the replaced object's place and transform: drop template, at and rect replace, değiştirilen nesnenin yerini ve dönüşümünü korur: template, at ve rect değerlerini çıkarın +@msg replace: select the one object to replace replace: değiştirilecek tek nesneyi seçin +@msg resolution must be a number or screen|medium|high resolution bir sayı veya screen|medium|high olmalıdır +@msg resolution must be between 1 and 2400 ppi resolution 1 ile 2400 ppi arasında olmalıdır +@msg rotation must be a number of degrees rotation derece cinsinden bir sayı olmalıdır +@msg rotation must be finite rotation sonlu olmalıdır +@msg rows and cols must be 1..50 rows ve cols 1..50 olmalıdır +@msg rows and columns must be 1..500 rows ve columns 1..500 olmalıdır +@msg rows of objects whose appearances differ can't be reordered together görünümleri farklı olan nesnelerin satırları birlikte yeniden sıralanamaz +@msg save the document first: Package collects a saved document önce belgeyi kaydedin: Paket kayıtlı bir belgeyi toplar +@msg save the document first: copy puts the file in its folder önce belgeyi kaydedin: copy dosyayı belgenin klasörüne koyar +@msg savedPreset: {e} savedPreset: {e} +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) scale `{s}`: 2x gibi bir çarpan, bir genişlik (100w), bir yükseklik (100h) veya bir çözünürlük (72ppi) +@msg scale must be a number above 0, at most 64 scale 0'dan büyük, en fazla 64 olan bir sayı olmalıdır +@msg scale must be non-zero scale sıfırdan farklı olmalıdır +@msg scope must be selection or all (got {other}) scope selection veya all olmalıdır (verilen: {other}) +@msg scribble is too long karalama çok uzun +@msg segment does not exist parça yok +@msg select a Shaper group bir Şekillendirici grubu seçin +@msg select a blend to set easing or color shift yumuşatmayı veya renk kaymasını ayarlamak için bir karışım seçin +@msg select a compound shape bir bileşik şekil seçin +@msg select a graph bir grafik seçin +@msg select a group or layer with visible, unlocked members görünür ve kilitli olmayan üyeleri olan bir grup veya katman seçin +@msg select a layer bir katman seçin +@msg select a text object bir metin nesnesi seçin +@msg select an image (or an Image Trace group) bir görüntü (veya bir Görüntü İzleme grubu) seçin +@msg select an image, or pass id bir görüntü seçin veya id verin +@msg select an object (or pass `id`) bir nesne seçin (veya `id` verin) +@msg select an object with a freeform gradient serbest biçimli degradesi olan bir nesne seçin +@msg select an object with an opacity mask opaklık maskesi olan bir nesne seçin +@msg select area type alan metni seçin +@msg select area type (text in a frame) alan metni (çerçeve içindeki metin) seçin +@msg select area type and closed paths (at least one area type object) alan metni ve kapalı yollar seçin (en az bir alan metni nesnesi) +@msg select area type whose first line can fit its frame ilk satırı çerçevesine sığabilen alan metni seçin +@msg select artwork to add its colours renklerini eklemek için resim seçin +@msg select artwork to make a group of its colours renklerinden bir grup oluşturmak için resim seçin +@msg select artwork to recolour, or give a colour `group` yeniden renklendirilecek resmi seçin veya bir renk için `group` verin +@msg select exactly two path ends to join birleştirmek için tam olarak iki yol ucu seçin +@msg select members of a compound shape bir bileşik şeklin üyelerini seçin +@msg select objects or give ids nesneleri seçin veya ids verin +@msg select objects to align to the guide kılavuza hizalanacak nesneleri seçin +@msg select one Intertwine group tek bir İç İçe Geçme grubu seçin +@msg select one image or pass id tek bir görüntü seçin veya id verin +@msg select paths yolları seçin +@msg select paths or compound paths yolları veya bileşik yolları seçin +@msg select rows or objects to collect toplanacak satırları veya nesneleri seçin +@msg select something to export dışa aktarılacak bir şey seçin +@msg select something to export (or turn off selectedOnly) dışa aktarılacak bir şey seçin (veya selectedOnly seçeneğini kapatın) +@msg select text to redefine the style from stilin yeniden tanımlanacağı metni seçin +@msg select the art and, on top of it, the mask object resmi ve onun üstündeki maske nesnesini seçin +@msg select the art for the design tasarım için resmi seçin +@msg select the art for the pattern tile desen döşemesi için resmi seçin +@msg select the art to add first önce eklenecek resmi seçin +@msg select the art to collect (or give its ids) toplanacak resmi seçin (veya kimliklerini verin) +@msg select the content and a path on top içeriği ve üstteki bir yolu seçin +@msg select the images to relink, or pass ids yeniden bağlanacak görüntüleri seçin veya ids verin +@msg select the images, or pass ids görüntüleri seçin veya ids verin +@msg select the linked images or placed documents, or pass ids bağlantılı görüntüleri veya yerleştirilmiş belgeleri seçin ya da ids verin +@msg select the object to copy from kopyalanacak kaynak nesneyi seçin +@msg select the objects (or give their ids) nesneleri seçin (veya kimliklerini verin) +@msg select the objects to attach to the path yola iliştirilecek nesneleri seçin +@msg select the objects to bind bağlanacak nesneleri seçin +@msg select two or more objects to intertwine iç içe geçirmek için iki veya daha fazla nesne seçin +@msg select two or more slices to combine birleştirmek için iki veya daha fazla dilim seçin +@msg select type on a path yol üzerindeki yazıyı seçin +@msg selection `{m}`: one or each selection `{m}`: one veya each +@msg settings is an object of document.exportForScreens params settings, document.exportForScreens parametrelerinden oluşan bir nesnedir +@msg settings must be an object settings bir nesne olmalıdır +@msg show `{show}`: all, missing, modified or embedded show `{show}`: all, missing, modified veya embedded +@msg show must be true or false show true veya false olmalıdır +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size "small", "medium", "large" veya 0'dan büyük, en fazla {_1} olan punto cinsinden bir sayı olmalıdır +@msg size must be positive size pozitif olmalıdır +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode "fixed" veya "pressure" olur, `{other}` değil +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode "fixed" veya "pressure" olur, {other} değil +@msg sizeVariation must be 0 or more sizeVariation 0 veya daha büyük olmalıdır +@msg smallCaps must be true or false smallCaps true veya false olmalıdır +@msg sort `{x}`: name, kind or status sort `{x}`: name, kind veya status +@msg source paths are too large for Shaper kaynak yollar Şekillendirici için çok büyük +@msg spot, mode and group apply to solid colours only spot, mode ve group yalnızca düz renkler için geçerlidir +@msg status `{s}`: linked, embedded, missing or modified status `{s}`: linked, embedded, missing veya modified +@msg steps must be 1..1000 steps 1..1000 olmalıdır +@msg steps must be 1..{MAX_STEPS} steps 1..{MAX_STEPS} olmalıdır +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) durak {i}: `plates` 0 ile 1 arasında dört sayı olmalıdır (C, M, Y, K) +@msg stopped before the archive was finished arşiv tamamlanmadan önce durduruldu +@msg strokeMode must be within|along|across, got {m} strokeMode within|along|across olmalıdır, verilen: {m} +@msg strokeOptions must be an object of stroke.set options strokeOptions, stroke.set seçeneklerinden oluşan bir nesne olmalıdır +@msg strokeWidth must be a positive number of pixels strokeWidth piksel cinsinden pozitif bir sayı olmalıdır +@msg subpath {si} is not an open subpath {si} numaralı alt yol açık bir alt yol değil +@msg subpaths required when joining the same path aynı yol birleştirilirken subpaths gereklidir +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict "merge" veya "add" olmalıdır, {v} değil +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} olmalıdır +@msg text transform is collapsed or unrepresentable metin dönüşümü çökmüş veya ifade edilemiyor +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces 2 ile 100 arasında bir tam sayı olmalıdır +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: "{_1}" veya "{_2}" kullanın +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: bir görüntü dosyasının {path} veya {name, dataBase64} değerini ya da effect.list'in verdiği biçimde bir doku verin +@msg textureImage: {e} textureImage: {e} +@msg that makes more than {MAX_PIECES} slices bu {MAX_PIECES} taneden fazla dilim oluşturuyor +@msg that object is not in the overlap o nesne çakışmanın içinde değil +@msg the Affinity document has no page with a size Affinity belgesinde boyutu olan bir sayfa yok +@msg the CMYK image couldn't be written CMYK görüntü yazılamadı +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF güvenlik ayarları parolaları olmadan kaydedildi: openPassword veya permissionsPassword değerini yeniden verin ya da korumasız dışa aktarmak için passwordRequired olmadan security verin +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) RTF dosyasında metin olarak yerleştirilemeyecek kadar çok paragraf veya biçimlendirme değişikliği var (en fazla {MAX_PARAGRAPHS} paragraf ve {MAX_RUNS} dizi) +@msg the RTF file is too large to place as type (at most {_1} MB) RTF dosyası metin olarak yerleştirilemeyecek kadar büyük (en fazla {_1} MB) +@msg the SVG expands to more than {0} nested SVG images SVG, {0} taneden fazla iç içe SVG görüntüsüne genişliyor +@msg the SVG expands to more than {0} objects SVG, {0} taneden fazla nesneye genişliyor +@msg the SVG has no drawable objects SVG'de çizilebilir nesne yok +@msg the SVGZ file unpacks to more than {_1} MB SVGZ dosyası açılınca {_1} MB'ı aşıyor +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word belgesinde {MAX_PAGES} sayfadan fazla özellik var; yerleştirilemeyecek kadar çok +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place Word belgesinde {MAX_RUNS} taneden fazla karakter veya paragraf özelliği dizisi var; yerleştirilemeyecek kadar çok +@msg the Word document has more than {_1} MB of formatting properties, too many to place Word belgesinde {_1} MB'tan fazla biçimlendirme özelliği var; yerleştirilemeyecek kadar çok +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) Word belgesinde metin olarak yerleştirilemeyecek kadar çok metin veya biçimlendirme var (en fazla {MAX_PARAGRAPHS} paragraf, {MAX_RUNS} dizi ve {_1} MB metin) +@msg the Word document has too much text to place as type (at most {_1} MB) Word belgesinde metin olarak yerleştirilemeyecek kadar çok metin var (en fazla {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it Word belgesi şifrelenmiş veya parolayla korunmuş; yerleştirmek için parolasız kaydedin +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) Word belgesi yerleştirilemeyecek kadar büyük ({name} akışı {_1} MB'tan fazla veri içeriyor) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off Word belgesi son olarak hızlı kaydetme ile kaydedilmiş ve VectorCraft bunu okumaz; hızlı kaydetme kapalıyken yeniden kaydedin +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document Word belgesi Word 6.0 veya Word 95 ile kaydedilmiş ve VectorCraft bunu okumaz; Word 97-2003 belgesi olarak kaydedin +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place Word belgesinin metni {MAX_PIECES} taneden fazla parçadan oluşuyor; yerleştirilemeyecek kadar çok +@msg the action set ids are not a list eylem seti kimlikleri bir liste değil +@msg the active paint is not a gradient etkin boya bir degrade değil +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size çalışma yüzeyleri tuvale sığmıyor: daha az çalışma yüzeyi, daha az aralık veya daha küçük bir boyut kullanın +@msg the character's size can't be measured karakterin boyutu ölçülemiyor +@msg the compound shape is too complex to expand bileşik şekil genişletilemeyecek kadar karmaşık +@msg the container of the listed objects is gone listelenen nesnelerin kapsayıcısı artık yok +@msg the copy `{user_id}` can't be read as a library `{user_id}` kopyası bir kütüphane olarak okunamıyor +@msg the copy would leave the canvas kopya tuvalin dışına çıkardı +@msg the cut cannot be made on this art: {e} bu resimde kesim yapılamıyor: {e} +@msg the data isn't an EMF or WMF picture veri bir EMF veya WMF resmi değil +@msg the data isn't an EPS or PostScript picture veri bir EPS veya PostScript resmi değil +@msg the deferred paste is no longer available ertelenmiş yapıştırma artık kullanılamıyor +@msg the design is too big to draw at every data point of this graph tasarım bu grafiğin her veri noktasında çizilemeyecek kadar büyük +@msg the design is too big to draw in every column of this graph tasarım bu grafiğin her sütununda çizilemeyecek kadar büyük +@msg the dialog it was opened over is no longer open üzerinde açıldığı iletişim kutusu artık açık değil +@msg the dictionary stack overflowed sözlük yığını taştı +@msg the editing data's hash has no place düzenleme verilerinin karması için yer yok +@msg the entities the document declares expand to too much text belgenin bildirdiği varlıklar çok fazla metne genişliyor +@msg the envelope's content has no bounds zarfın içeriğinin sınırları yok +@msg the envelope's mesh is malformed zarfın ağı hatalı biçimlendirilmiş +@msg the file holds no `variableSets` element dosyada `variableSets` öğesi yok +@msg the file is larger than {_1} MB dosya {_1} MB'tan büyük +@msg the file is too large dosya çok büyük +@msg the file was updated or encrypted already dosya zaten güncellenmiş veya şifrelenmiş +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) bir satırın ilk karakterinden önce aralığı ayarlanacak bir karakter yoktur: yalnızca yukarı ve aşağı hareket eder (dy) +@msg the font {_1} is not available {_1} yazı tipi kullanılamıyor +@msg the format has no file extension biçimin dosya uzantısı yok +@msg the graphic can't be read: {e} grafik okunamıyor: {e} +@msg the graphic is empty grafik boş +@msg the graphic's data is damaged grafiğin verileri hasarlı +@msg the graphic's document has no artboard grafiğin belgesinde çalışma yüzeyi yok +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{cell}` başlığı `{other}` değişkeni olarak geri okunurdu: birini yeniden adlandırın +@msg the image `{path}` isn't followed: {r} `{path}` görüntüsü izlenmiyor: {r} +@msg the image has no embedded pixels görüntüde gömülü piksel yok +@msg the image is empty görüntü boş +@msg the image is fully transparent görüntü tamamen saydam +@msg the image is not on an artboard; pass rect görüntü bir çalışma yüzeyinde değil; rect verin +@msg the image's pixels are missing görüntünün pikselleri eksik +@msg the image's pixels aren't in the document görüntünün pikselleri belgede değil +@msg the image's pixels can't be read: {e} görüntünün pikselleri okunamıyor: {e} +@msg the image's transparency doesn't fit it görüntünün saydamlığı görüntüye uymuyor +@msg the job would print more than {MAX_PAGES} pages iş {MAX_PAGES} sayfadan fazla yazdırırdı +@msg the job would print more than {_1} pages iş {_1} sayfadan fazla yazdırırdı +@msg the layers hold no art to mask katmanlarda maskelenecek resim yok +@msg the layout moved düzen taşındı +@msg the library has a group `{name}` already kütüphanede `{name}` grubu zaten var +@msg the library has no group `{name}` kütüphanede `{name}` grubu yok +@msg the library has no item `{item}` kütüphanede `{item}` öğesi yok +@msg the library has no item `{other}` kütüphanede `{other}` öğesi yok +@msg the library holds {MAX_GROUPS} groups already kütüphanede zaten {MAX_GROUPS} grup var +@msg the library holds {MAX_ITEMS} items of this kind already kütüphanede bu türden zaten {MAX_ITEMS} öğe var +@msg the name is empty ad boş +@msg the object has no fill, stroke or effect nesnenin dolgusu, konturu veya efekti yok +@msg the object has no graphic style (pass `name`) nesnenin grafik stili yok (`name` verin) +@msg the objects don't match the plan nesneler planla eşleşmiyor +@msg the open and permissions passwords must differ açma ve izin parolaları farklı olmalıdır +@msg the operand stack overflowed işlenen yığını taştı +@msg the page has no area sayfanın alanı yok +@msg the page's type in an unread object's box isn't in its page art okunmamış bir nesnenin kutusundaki sayfa metni, sayfa resminde yok +@msg the paint behind the proxy is not a gradient vekilin arkasındaki boya bir degrade değil +@msg the parent must be a layer or sublayer üst öğe bir katman veya alt katman olmalıdır +@msg the path can't be extended yol uzatılamıyor +@msg the path can't be inside one of the objects to attach yol, iliştirilecek nesnelerden birinin içinde olamaz +@msg the path has no segments to measure yolda ölçülecek parça yok +@msg the path is empty yol boş +@msg the path is too short to shorten that much yol o kadar kısaltılamayacak kadar kısa +@msg the picture has no objects resimde nesne yok +@msg the program runs too long program çok uzun süre çalışıyor +@msg the program uses too much memory program çok fazla bellek kullanıyor +@msg the rectangle must have a width and a height dikdörtgenin bir genişliği ve bir yüksekliği olmalıdır +@msg the rectangle needs a size and must lie on the canvas dikdörtgenin bir boyutu olmalı ve tuvalin üzerinde bulunmalıdır +@msg the selected art has no width seçili resmin genişliği yok +@msg the selection draws nothing seçim hiçbir şey çizmiyor +@msg the selection has no area seçimin alanı yok +@msg the selection has no art to export seçimde dışa aktarılacak resim yok +@msg the selection has no bounds seçimin sınırları yok +@msg the selection has no graphic style seçimin grafik stili yok +@msg the slice would leave the canvas dilim tuvalin dışına çıkardı +@msg the spot colour couldn't be added spot renk eklenemedi +@msg the subpath has no ends to extend (it is closed or a single point) alt yolun uzatılacak ucu yok (kapalı veya tek bir nokta) +@msg the symbols are nested too deeply to expand their instances semboller, örnekleri genişletilemeyecek kadar derin iç içe geçmiş +@msg the text file is too large to place as type (at most {_1} MB) metin dosyası metin olarak yerleştirilemeyecek kadar büyük (en fazla {_1} MB) +@msg the text is empty metin boş +@msg the text is over {_1} MB metin {_1} MB'tan büyük +@msg the top object must be a path üstteki nesne bir yol olmalıdır +@msg the trace was cancelled izleme iptal edildi +@msg the trailer has no size trailer'ın boyutu yok +@msg the type object is flattened to nothing metin nesnesi düzleştirilince hiçbir şey kalmıyor +@msg the value of axis `{tag}` must be a number or null `{tag}` ekseninin değeri bir sayı veya null olmalıdır +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets değişken kütüphanesi {MAX_LIBRARY_DATASETS} taneden fazla veri kümesi bildiriyor +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities değişken kütüphanesi {MAX_LIBRARY_ENTITIES} taneden fazla varlık bildiriyor +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables değişken kütüphanesi {MAX_LIBRARY_VARIABLES} taneden fazla değişken bildiriyor +@msg the variable library declares no variables değişken kütüphanesi hiçbir değişken bildirmiyor +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes değişken kütüphanesi {MAX_LIBRARY_BYTES} bayttan büyük +@msg the variable library is not UTF-8 değişken kütüphanesi UTF-8 değil +@msg the variable library is not well-formed XML: {e} değişken kütüphanesi iyi biçimlendirilmiş bir XML değil: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep değişken kütüphanesi öğeleri {MAX_LIBRARY_NESTING} düzeyden daha derin iç içe yerleştiriyor +@msg the variable library's document type declaration holds something other than entities of plain text değişken kütüphanesinin belge türü bildirimi, düz metin varlıklarından başka bir şey içeriyor +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes değişken kütüphanesinin varlıkları {MAX_LIBRARY_BYTES} bayttan fazlasına genişliyor +@msg the window has no dock pencerede yerleştirme alanı yok +@msg the written PDF has no catalog yazılan PDF'de katalog yok +@msg the written PDF has no cross-reference table yazılan PDF'de çapraz başvuru tablosu yok +@msg the written PDF's metadata can't be edited yazılan PDF'nin meta verileri düzenlenemiyor +@msg there are no colour swatches to draw çizilecek renk örneği yok +@msg there is already a design named `{name}` `{name}` adlı bir tasarım zaten var +@msg there is already a design named `{to}` `{to}` adlı bir tasarım zaten var +@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var +@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var +@msg there is no library: create one first kütüphane yok: önce bir tane oluşturun +@msg these paths are too degenerate for Shaper bu yollar Şekillendirici için fazla yozlaşmış +@msg thumbnail: no page {v} (the {what} has {count}) thumbnail: {v} numaralı sayfa yok ({what} içinde {count} tane var) +@msg tileRange of {what}: {e} {what} için tileRange: {e} +@msg title can't be empty title boş olamaz +@msg to (the new name) is required to (yeni ad) gereklidir +@msg to must be fill or stroke to fill veya stroke olmalıdır +@msg to must be smooth or corner to smooth veya corner olmalıdır +@msg too large for a zip archive: package to a folder bir zip arşivi için çok büyük: bir klasöre paketleyin +@msg too many Shaper edits çok fazla Şekillendirici düzenlemesi +@msg too many `points` (at most 100000) çok fazla `points` (en fazla 100000) +@msg too many characters: at most {MAX_CHARS} çok fazla karakter: en fazla {MAX_CHARS} +@msg too many dots for this size: lower the frequency bu boyut için çok fazla nokta: frekansı düşürün +@msg too many filters over one file tek bir dosya üzerinde çok fazla filtre +@msg too many overlapping paths for Shaper Şekillendirici için çok fazla çakışan yol +@msg too many saved clips çok fazla kayıtlı kırpma +@msg too many saved graphics states çok fazla kayıtlı grafik durumu +@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır +@msg toolbar name can't be empty araç çubuğu adı boş olamaz +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (varsayılan) veya "omit" +@msg two saved selections would be named `{_1}` iki kayıtlı seçimin adı `{_1}` olurdu +@msg type dimension cannot be represented with this text transform metin boyutu bu metin dönüşümüyle ifade edilemiyor +@msg type dimension must be finite metin boyutu sonlu olmalıdır +@msg unexpected resources beklenmeyen kaynaklar +@msg unknown CMYK profile `{name}` bilinmeyen CMYK profili `{name}` +@msg unknown File Info field `{k}` bilinmeyen Dosya Bilgisi alanı `{k}` +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) featureChanges içinde bilinmeyen OpenType özelliği `{t}` (`features` parametresinin aldığı etiketler) +@msg unknown PDF preset `{name}` (presets: {_1}) bilinmeyen PDF ön ayarı `{name}` (ön ayarlar: {_1}) +@msg unknown Warp style bilinmeyen Çarpıtma stili +@msg unknown alignToPath `{a}` bilinmeyen alignToPath `{a}` +@msg unknown arrowhead {v} bilinmeyen ok ucu {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) bilinmeyen artboardLayout anahtarı `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown attribute `{attribute}` bilinmeyen öznitelik `{attribute}` +@msg unknown attribute `{k}` bilinmeyen öznitelik `{k}` +@msg unknown axis `{other}` (vertical|horizontal|free) bilinmeyen eksen `{other}` (vertical|horizontal|free) +@msg unknown blend mode `{b}` bilinmeyen karıştırma modu `{b}` +@msg unknown blend mode {b} bilinmeyen karıştırma modu {b} +@msg unknown brush type `{o}` bilinmeyen fırça türü `{o}` +@msg unknown category `{c}` bilinmeyen kategori `{c}` +@msg unknown category `{c}` ({_1}) bilinmeyen kategori `{c}` ({_1}) +@msg unknown character `{c}` bilinmeyen karakter `{c}` +@msg unknown character style number field bilinmeyen karakter stili sayı alanı +@msg unknown effect `{e}` bilinmeyen efekt `{e}` +@msg unknown end {e} bilinmeyen uç {e} +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) bilinmeyen flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution veya kayıtlı bir ön ayar: bkz. flattener.presets.list) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) bilinmeyen biçim `{f}` (vcswatches, gpl, ase veya css) +@msg unknown from {f} bilinmeyen from {f} +@msg unknown graph type `{t}` bilinmeyen grafik türü `{t}` +@msg unknown grid colours `{name}` (one of {_1}) bilinmeyen ızgara renkleri `{name}` (şunlardan biri: {_1}) +@msg unknown gridType `{t}` bilinmeyen gridType `{t}` +@msg unknown highlight `{v}` bilinmeyen vurgu `{v}` +@msg unknown intent `{i}` bilinmeyen amaç `{i}` +@msg unknown issue kind {id} bilinmeyen sorun türü {id} +@msg unknown issue kind {v} bilinmeyen sorun türü {v} +@msg unknown knockout state {k} bilinmeyen nakavt durumu {k} +@msg unknown language `{language}` (one of {_1}) bilinmeyen dil `{language}` (şunlardan biri: {_1}) +@msg unknown language `{l}` (one of {_1}) bilinmeyen dil `{l}` (şunlardan biri: {_1}) +@msg unknown method `{m}` ({_1}) bilinmeyen yöntem `{m}` ({_1}) +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) bilinmeyen mod `{other}` (gray, rgb, hsb, lab, cmyk veya web) +@msg unknown mode `{other}` (mono|cmyk) bilinmeyen mod `{other}` (mono|cmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) bilinmeyen mod `{other}` (rgb|cmyk|gray|global) +@msg unknown mode `{other}` (set, add, subtract) bilinmeyen mod `{other}` (set, add, subtract) +@msg unknown mode `{o}` bilinmeyen mod `{o}` +@msg unknown mode {m} bilinmeyen mod {m} +@msg unknown model `{other}` bilinmeyen model `{other}` +@msg unknown model `{other}` (keep, new or document) bilinmeyen model `{other}` (keep, new veya document) +@msg unknown op {o} bilinmeyen op {o} +@msg unknown order `{o}`: toggle, front, forward, backward or back bilinmeyen order `{o}`: toggle, front, forward, backward veya back +@msg unknown overprints `{v}` (preserve, simulate or discard) bilinmeyen overprints `{v}` (preserve, simulate veya discard) +@msg unknown panel bilinmeyen panel +@msg unknown pieLegend `{v}` (none, standard or wedges) bilinmeyen pieLegend `{v}` (none, standard veya wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) bilinmeyen piePosition `{v}` (even, ratio veya stacked) +@msg unknown pieSort `{v}` (none, all or first) bilinmeyen pieSort `{v}` (none, all veya first) +@msg unknown plate `{n}` bilinmeyen kalıp `{n}` +@msg unknown preference `{k}` bilinmeyen tercih `{k}` +@msg unknown profile {id} (see stroke.widthProfile.list) bilinmeyen profil {id} (bkz. stroke.widthProfile.list) +@msg unknown proof target `{t}` bilinmeyen prova hedefi `{t}` +@msg unknown quotes key `{k}` (double, single) bilinmeyen quotes anahtarı `{k}` (double, single) +@msg unknown resolution `{v}` bilinmeyen çözünürlük `{v}` +@msg unknown rule `{rule}` ({_1}) bilinmeyen kural `{rule}` ({_1}) +@msg unknown rule `{r}` (see color.harmony) bilinmeyen kural `{r}` (bkz. color.harmony) +@msg unknown setting `{k}` bilinmeyen ayar `{k}` +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) bilinmeyen şekil `{v}` (circle|ellipse|square|diamond|line) +@msg unknown spacing `{o}` (smooth|steps|distance) bilinmeyen spacing `{o}` (smooth|steps|distance) +@msg unknown tileType `{t}` ({_1}) bilinmeyen tileType `{t}` ({_1}) +@msg unknown units bilinmeyen birimler +@msg unknown units `{u}` bilinmeyen birimler `{u}` +@msg unknown value axis `{v}` (left, right or both) bilinmeyen değer ekseni `{v}` (left, right veya both) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) bilinmeyen çeşitleme `{v}` (tintsShades|warmCool|vividMuted) +@msg unknown warp style `{s}` bilinmeyen çarpıtma stili `{s}` +@msg unknown {key} `{v}` (none, short or full) bilinmeyen {key} `{v}` (none, short veya full) +@msg unknown {key} profile `{n}` bilinmeyen {key} profili `{n}` +@msg unknown {k} key `{key}` (size, position) bilinmeyen {k} anahtarı `{key}` (size, position) +@msg unreadable object okunamayan nesne +@msg unsafe destination file name güvenli olmayan hedef dosya adı +@msg use paths or compound paths yolları veya bileşik yolları kullanın +@msg useArtboards must be true or false, not {v} useArtboards true veya false olmalıdır, {v} değil +@msg value for `{var}` must match its variable kind `{var}` değeri değişkeninin türüyle eşleşmelidir +@msg variable `{_1}` is already defined `{_1}` değişkeni zaten tanımlı +@msg variable `{name}` has no `trait` `{name}` değişkeninde `trait` yok +@msg variable `{name}` is already defined `{name}` değişkeni zaten tanımlı +@msg variable `{name}` is declared twice `{name}` değişkeni iki kez bildirilmiş +@msg variable `{to}` already exists `{to}` değişkeni zaten var +@msg view is required view gereklidir +@msg view must be one of {_1} view şunlardan biri olmalıdır: {_1} +@msg warpStyle can only edit an applied Warp effect warpStyle yalnızca uygulanmış bir Çarpıtma efektini düzenleyebilir +@msg width and height must be more than 0 and at most {limit} width ve height 0'dan büyük ve en fazla {limit} olmalıdır +@msg width factors must be finite genişlik çarpanları sonlu olmalıdır +@msg width must be positive width pozitif olmalıdır +@msg width out of range genişlik aralık dışında +@msg width/height must be > 0 width/height > 0 olmalıdır +@msg x and y must be finite numbers x ve y sonlu sayılar olmalıdır +@msg x and y must be given together x ve y birlikte verilmelidir +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone için bir anchor gerekir: anchor ile bir panelin yanına veya side (Start ya da End) ile yeni bir yerleştirme sütununa yerleştirin +@msg zoom must be positive zoom pozitif olmalıdır +@msg {C}: no effect at index {list} {C}: {list} dizininde efekt yok +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} korumalıdır ve kalır +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} korumalıdır: ayarları başka bir adla kaydedin +@msg {LABEL} produced an empty result {LABEL} boş bir sonuç üretti +@msg {_1} MB of document, at most {_2} MB {_1} MB belge, en fazla {_2} MB +@msg {_1} MB of images, at most {_2} MB {_1} MB görüntü, en fazla {_2} MB +@msg {_1} bytes of RGBA data for a {width} × {height} image {width} × {height} boyutlu bir görüntü için {_1} bayt RGBA verisi +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1} okunamıyor veya okunduktan sonra değişmiş: önce yeniden bağlayın veya güncelleyin +@msg {_1} can't go into {into} {_1}, {into} içine konulamaz +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1} yazdırmayı düşük çözünürlükle sınırlayamaz: PDF 1.4 veya sonrasını seçin ya da yüksek çözünürlüklü yazdırmaya izin verin +@msg {_1} files can't be opened yet {_1} dosyaları henüz açılamıyor +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1} dosyaları parolayla korunamaz: parolaları kaldırın veya standart seçmeyin +@msg {_1} files can't be {_2} {_1} dosyaları için şu yapılamaz: {_2} +@msg {_1} files can't carry editing data: turn off preserveEditing {_1} dosyaları düzenleme verileri taşıyamaz: preserveEditing seçeneğini kapatın +@msg {_1} files can't have PDF layers: turn off createLayers {_1} dosyalarında PDF katmanları olamaz: createLayers seçeneğini kapatın +@msg {_1} files need a creation date, and this platform has no clock to give one {_1} dosyaları için bir oluşturma tarihi gerekir ve bu platformda bunu verecek bir saat yok +@msg {_1} isn't a path {_1} bir yol değil +@msg {_1} options: {e} {_1} seçenekleri: {e} +@msg {_1} paints nothing to rasterize {_1} rasterleştirilecek hiçbir şey boyamıyor +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1} parolaları en fazla {MAX_LEGACY_PASSWORD} ASCII karakter içerebilir (PDF 1.7 ve sonrası her karakteri alır) +@msg {_1} with linked images or an image map writes several files: use document.export bağlantılı görüntüler veya bir görüntü eşlemi içeren {_1} birkaç dosya yazar: document.export kullanın +@msg {_1} writes one file per artboard here: use document.export, or name one artboard {_1} burada çalışma yüzeyi başına bir dosya yazar: document.export kullanın veya tek bir çalışma yüzeyi belirtin +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} piksel {_3} için çok büyük (kenar başına en fazla {max} piksel): ölçeği düşürün +@msg {_1}: belongs to another account {_1}: başka bir hesaba ait +@msg {_1}: not a folder of its own {_1}: kendine ait bir klasör değil +@msg {_1}: not a plain file {_1}: düz bir dosya değil +@msg {dest}: {e} {dest}: {e} +@msg {doc} has no folder {doc} belgesinin klasörü yok +@msg {file} isn't linked {file} bağlantılı değil +@msg {folder} is not a package folder {folder} bir paket klasörü değil +@msg {folder}: more than {max} files and folders {folder}: {max} taneden fazla dosya ve klasör +@msg {folder}: {e} {folder}: {e} +@msg {g} is not a Live Paint group {g} bir Canlı Boyama grubu değil +@msg {id} is not a slice {id} bir dilim değil +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key} 0–{MAX_ADD_AROUND} pt olmalıdır +@msg {key} must be [x,y] {key} [x,y] olmalıdır +@msg {key} must be a percentage {min}..100 {key} {min}..100 aralığında bir yüzde olmalıdır +@msg {key} must be a positive number, not {n} {key} pozitif bir sayı olmalıdır, {n} değil +@msg {key} must be a positive number, not {v} {key} pozitif bir sayı olmalıdır, {v} değil +@msg {key} must be one of {_1} {key} şunlardan biri olmalıdır: {_1} +@msg {key} must be {_1}, got {s} {key} {_1} olmalıdır, verilen: {s} +@msg {key} must name a floating panel {key} yüzen bir paneli belirtmelidir +@msg {key} must name a panel in another group {key} başka bir gruptaki bir paneli belirtmelidir +@msg {key} must name a panel that shows {key} gösterilen bir paneli belirtmelidir +@msg {key} must name a registered panel {key} kayıtlı bir paneli belirtmelidir +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} dosyalarında saydamlık yoktur ve dosyada {what} olurdu: önce düzleştirin (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind} görüntüleri açılamıyor (bkz. document.formats) +@msg {k} `{v}` is not one of the choices {k} `{v}` seçeneklerden biri değil +@msg {k} has control characters{_1} {k} denetim karakterleri içeriyor{_1} +@msg {k} is too long (at most {MAX_TEXT} characters) {k} çok uzun (en fazla {MAX_TEXT} karakter) +@msg {k} must be > 0 {k} > 0 olmalıdır +@msg {k} must be a number (pt) or a length such as "210 mm" {k} bir sayı (pt) veya "210 mm" gibi bir uzunluk olmalıdır +@msg {k} must be a number from {min} to {max} {k} {min} ile {max} arasında bir sayı olmalıdır +@msg {k} must be a number or "auto" {k} bir sayı veya "auto" olmalıdır +@msg {k} must be a string {k} bir dize olmalıdır +@msg {k} must be text {k} metin olmalıdır +@msg {k} must be true or false {k} true veya false olmalıdır +@msg {k} must be {{size?, position?}} {k} {{size?, position?}} olmalıdır +@msg {k}: can't read `{s}` as a length {k}: `{s}` bir uzunluk olarak okunamıyor +@msg {label} must be a number at most {max} {label} en fazla {max} olan bir sayı olmalıdır +@msg {label} must be a number from -1296 to 1296 {label} -1296 ile 1296 arasında bir sayı olmalıdır +@msg {label} must be a number from 1 to 10000 {label} 1 ile 10000 arasında bir sayı olmalıdır +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name} yerleşiktir ve silinemez +@msg {name}: CRC or size mismatch {name}: CRC veya boyut uyuşmazlığı +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: bu Affinity dosyasının yalnızca gömülü önizlemesi okunabildi; uyarısıyla birlikte görmek için Dosya › Aç komutunu kullanın veya yerleştirmeden önce Affinity'den SVG ya da PDF olarak dışa aktarın +@msg {name}: {e} {name}: {e} +@msg {native}; its embedded preview can't be read either ({e}) {native}; gömülü önizlemesi de okunamıyor ({e}) +@msg {std} files are CMYK, and the file would have colours in {_1} {std} dosyaları CMYK'dir ve dosyada {_1} renkleri olurdu +@msg {std} files embed their fonts, and the file would have one that isn't {std} dosyaları yazı tiplerini gömer ve dosyada gömülmemiş bir yazı tipi olurdu +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target}, bu belgenin okunduğu dosyadır ve okunurken bazı şeyler dışarıda kaldı ({what}): üzerine yazmak bunları kalıcı olarak kaybettirir. Bunun yerine başka bir dosya yazın veya yine de değiştirmek için acknowledgeLoss: true verin +@msg {ty} brushes need selected art (or params.{k}) {ty} fırçaları için seçili resim (veya params.{k}) gerekir +@msg {v} is not an asset id {v} bir varlık kimliği değil +@msg {what} can't be intertwined {what} iç içe geçirilemez +@msg {what} doesn't fit the paper with its bleed and marks {what}, taşma payı ve işaretleriyle birlikte kâğıda sığmıyor +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} {MAX_TILES} taneden fazla döşemeye yazdırılırdı: ölçeğini küçültün Playback Options Oynatma Seçenekleri Accelerated Hızlandırılmış Step by Step Adım Adım @@ -7447,3 +9250,12 @@ breakText Glyphs Glifler Grommets Kuşgözleri Grommet Inset Kuşgözlerinin kenara uzaklığı Diameter Çap +@msg `{key}` must be from 0.01 to 1000 pt `{key}` 0.01 ile 1000 pt arasında olmalıdır +@msg turn on at least one side en az bir kenarı açın +@msg with no hem and no grommets there is nothing to mark kenar kıvırma ve kuşgözü olmadan işaretlenecek bir şey yok +@msg select the banner, or mark every artboard afişi seçin veya her çalışma yüzeyini işaretleyin +@msg there is no banner to mark işaretlenecek afiş yok +@msg the banner has no width or height afişin genişliği veya yüksekliği yok +@msg the hem is too deep for the banner kenar kıvırma afiş için çok derin +@msg the grommet inset is too large for the banner kuşgözlerinin kenara uzaklığı afiş için çok büyük +@msg the spacing makes more than {MAX_GROMMETS} grommets bu aralık {MAX_GROMMETS} taneden fazla kuşgözü oluşturur diff --git a/docs/localization-parity.md b/docs/localization-parity.md index cd8dc33f30..53e5fa0e1f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -64,7 +64,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome | | Georgian | `ka` | 5,200 rows (counted 2026-10-21): menus, panels, dialogs, plurals (one count-neutral form) and messages, tested complete; reviewed by a native speaker | full | -| Turkish | `tr` | 5,558 rows, 880 of them `@msg` (counted 2026-10-28); 6 menu strings and the default swatch names still fall back to English | full | +| Turkish | `tr` | 9,175 rows, 3,446 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); 41 messages, 62 menu strings, 26 `tl!` literals, 13 undo labels and the default swatch names still fall back to English | full | | Indonesian | `id` | 5,531 rows, 788 of them `@msg` (counted 2026-10-28): menus and `tl!` literals complete when counted; its messages are partial; one plural form | full | | Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f3707717e6..d1ffa7ec13 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -885,6 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). + - The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with their notes name one item in the singular and more in the plural, in English and in each language's plural forms (`counted_status_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). From f384398494561aedb6e12973d67cfed2d455a22a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:08:36 -0800 Subject: [PATCH 03/33] Image Trace: preset trace counts measured on current main The anchor, pixel-difference and staircase figures for the new preset values are measured again with JPEG block smoothing and the Limited palette change in main. 16 Colors makes 20% fewer anchors, and Low Fidelity Photo leaves 96 staircases of 2 px steps where it left 77. --- docs/image-trace-quality.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 2b2b363433..0c18767785 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -259,9 +259,10 @@ leaves 1.4 specks (was 0.5), and Outline's stroked centre lines lie 0.095 px off anchors a stroke (was 3.0). ΔE changes by 0.01 or less except Line Art and Outline (2.62 and 2.61 to 2.66 and 2.67); edge ΔE rises in 8 of the 12, for example 4.79 to 5.25 (16 Colors), 3.98 to 4.46 (3 Colors) and 9.46 to 10.03 (Black and White Logo). On synthetic shapes and photos of 300 to 4,000 px traced outside this harness, -High Fidelity Photo makes 41% fewer anchors and 16 Colors 15% fewer; the mean pixel difference of each -trace changes by −0.23 to +0.25 of a level; 16 Colors leaves 91 staircases of steps of 2 px or more where it left 85, and High -Fidelity Photo 473 where it left 461. The tables below are the previous measurement, not a rerun. +High Fidelity Photo makes 41% fewer anchors and 16 Colors 20% fewer; the mean pixel difference of each +trace changes by −0.23 to +0.26 of a level; 16 Colors leaves 41 staircases of steps of 2 px or more where it left 40, High +Fidelity Photo 440 where it left 391, and Low Fidelity Photo 96 where it left 77. The tables below are the previous +measurement, not a rerun. Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. ## A simpler contour walk From 090293db4ebd3b66f3a28d2c1fef9fe05dcec00e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:22:12 -0800 Subject: [PATCH 04/33] Image Trace: preset docs name the enhanced versions and older figures The preset paragraphs say that the enhanced versions use the same Paths, Corners and Noise, and that Corners 50 applies to the other eight presets. The quality notes add the staircase and anchor rises in Line Art, Outline, 3 Colors, Sketched Art and Silhouettes, and say which figures were measured at the earlier values. The anchor-limit comments name the same settings in both places. --- crates/engine/src/cmd/buildcmds/trace.rs | 12 ++++++------ docs/image-trace-adjustments.md | 6 +++--- docs/image-trace-quality.md | 12 ++++++++---- docs/target-app-parity.md | 2 +- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 024ae851f5..0a03ab00b1 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -288,10 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); } diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index e35fe5453b..2c9889f5de 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -18,9 +18,9 @@ its current location. Opening the controls does not add a document undo step. | Create | Fills / Strokes | Creates filled areas, stroked lines, or both. | | Ignore Color | Color picker | Leaves out the selected color (white by default). | -The built-in presets other than Auto Color and Flat Logo all use Paths 50. Corners is 100 in -Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline, and 50 in the others. -Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, +The built-in presets other than Auto Color and Flat Logo all use Paths 50, and so do their enhanced +versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White +Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo, 10 in Low Fidelity Photo, 15 in 3 Colors, 6 Colors, 16 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default and Black and White Logo, and 90 in Silhouettes (see [image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index 0c18767785..41262be69c 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -247,7 +247,8 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co | Technical Drawing | 50 | 100 | 1 | 95, 90, 4 | | Outline | 50 | 75 | 20 | 80, 70, 10 | -The palettes, color counts, thresholds and other options of the presets did not change. +The palettes, color counts, thresholds and other options of the presets did not change. The enhanced +versions of these presets use the same Paths, Corners and Noise. Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 @@ -255,14 +256,17 @@ anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High F Sketched Art does not change. Outlines on flat art lie further from the true edge: off mean 0.100 to 0.123 px (16 Colors), 0.101 to 0.119 (6 Colors), 0.104 to 0.129 (3 Colors), 0.064 to 0.092 (Black and White Logo) and 0.056 to 0.074 (Line Art), and off max 1.00 to 1.16 px in 6 Colors and 16 Colors. Technical Drawing -leaves 1.4 specks (was 0.5), and Outline's stroked centre lines lie 0.095 px off (was 0.086) with 2.7 +leaves 1.4 specks (was 0.5), and Outline's stroked center lines lie 0.095 px off (was 0.086) with 2.7 anchors a stroke (was 3.0). ΔE changes by 0.01 or less except Line Art and Outline (2.62 and 2.61 to 2.66 and 2.67); edge ΔE rises in 8 of the 12, for example 4.79 to 5.25 (16 Colors), 3.98 to 4.46 (3 Colors) and 9.46 to 10.03 (Black and White Logo). On synthetic shapes and photos of 300 to 4,000 px traced outside this harness, High Fidelity Photo makes 41% fewer anchors and 16 Colors 20% fewer; the mean pixel difference of each trace changes by −0.23 to +0.26 of a level; 16 Colors leaves 41 staircases of steps of 2 px or more where it left 40, High -Fidelity Photo 440 where it left 391, and Low Fidelity Photo 96 where it left 77. The tables below are the previous -measurement, not a rerun. +Fidelity Photo 440 where it left 391, Low Fidelity Photo 96 where it left 77, Line Art 17 where it left 13, Outline 13 +where it left 10 and 3 Colors 14 where it left 12. On the same images Sketched Art makes 4,084 anchors where it made +3,936 and Silhouettes 1,608 where it made 1,578. The figures for these twelve presets and their enhanced versions in +the other sections of this file, and in the Image Trace entries of +[target-app-parity.md](target-app-parity.md), were measured at the earlier values. Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. ## A simpler contour walk diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b59be1312b..529faa455f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1418,7 +1418,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges:** in Color and Grayscale, a semi-transparent pixel (alpha 128 to 254) on the edge of a cut-out image, beside a pixel that is less than half opaque, traces as a color of the fully opaque pixels within two pixels of it when its own color is that color or a darker shade of it, and of several such colors, as the one the most of those pixels have (art across a transparent gap does not count), so a darkened edge tone no longer traces as a 1 px sliver of an unrelated palette color, while a thin semi-transparent outline of another color keeps its own; code-drawn cut-out, opaque-edge and thin-outline tests in `crates/trace`. - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. -- **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50; Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the others; Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. +- **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. From e47975d302153fda30a444a686b730f28f4fdda7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:32:02 -0800 Subject: [PATCH 05/33] Type: .ai import reads Insert Aki, and .ai save writes it Opening an .ai file now reads Insert Aki Left and Right from its text document through the same cascade as the other character keys: the run, its character style and the styles that one is based on, [Normal Character Style], then the document's defaults. The values are read in thousandths of an em. A negative value or one that is not a number opens as 0, and a value past 1000 opens as 1000. How the text document stores these values is VectorCraft's own rule. An .ai save writes each run's nonzero values in the form that reader reads, and no longer reports Insert Aki as left out of the editing data. A legacy .ai text object has no Insert Aki: type with it that is written as text now reports that the setting is left out. Type written as outlines keeps the space. --- crates/eps/src/ai_editing/tests.rs | 51 +++++++++++++++++++ crates/eps/src/ai_editing/writer/texts.rs | 19 ++++++- crates/eps/src/import/ate.rs | 60 +++++++++++++++++++++++ crates/eps/src/legacy_ai.rs | 2 +- crates/eps/src/legacy_ai/encoding.rs | 3 ++ crates/eps/src/legacy_ai/tests.rs | 35 +++++++++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 8 files changed, 173 insertions(+), 3 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 967c982ad4..84f093695c 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -4139,6 +4139,57 @@ fn standard_vertical_roman_alignment_comes_back() { assert_eq!(flags(&texts(&read_back(&both))[0])[2], (false, true)); } +/// Insert Aki Left and Right come back on each run, in vertical and horizontal type: a run with +/// either writes it as key 49 or 50 in 1/1000 em, a run without writes neither, and nothing is +/// reported. Each object lays out as it did. A run that also has an attribute the text document +/// leaves out is still reported. +#[test] +fn insert_aki_comes_back() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let plain = style(14.0, Color::BLACK); + let left = CharStyle { aki_left: 250.0, ..plain.clone() }; + let both = CharStyle { aki_left: 125.5, aki_right: 500.0, ..plain.clone() }; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let mut down = TextObject::point(vectorcraft_geom::Point::new(150.0, 20.0), "", plain.clone()); + down.runs = vec![TextRun::new("AB", left.clone()), TextRun::new("CD", plain.clone()), TextRun::new("EF", both.clone())]; + down.vertical = true; + let mut across = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "", plain.clone()); + across.runs = vec![TextRun::new("GH", both.clone()), TextRun::new("IJ", plain.clone())]; + for t in [down, across] { + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&type_lines(&back), &type_lines(&doc)); + let texts = |d: &Document| -> Vec { + d.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() + }; + let aki = |t: &TextObject| t.runs.iter().map(|r| (r.style.aki_left, r.style.aki_right)).collect::>(); + let (written, read) = (texts(&doc), texts(&back)); + assert_eq!(read.iter().map(aki).collect::>(), [vec![(250.0, 0.0), (0.0, 0.0), (125.5, 500.0)], vec![(125.5, 500.0), (0.0, 0.0)]]); + let origins = |t: &TextObject| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (r3(g.origin.x), r3(g.origin.y))).collect::>() + }; + for (w, r) in written.iter().zip(&read) { + assert_eq!(origins(r), origins(w), "vertical={}", w.vertical); + } + let decoded = text_document(&program(&doc)); + for (key, count) in [("/49 250.0", 1), ("/49 125.5", 2), ("/50 500.0", 2)] { + assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}"); + } + assert_eq!(decoded.matches("/49 ").count() + decoded.matches("/50 ").count(), 5, "{decoded}"); + // Underline is still left out, and reported. + let mut lossy = doc.clone(); + let id = lossy.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.underline = true; + } + assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + /// The text document of program `text` (LF line ends), decoded, with its UTF-16 strings' zero /// bytes left out. fn text_document(text: &str) -> String { diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 6bc3c63b09..01b49d40c1 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -20,6 +20,7 @@ use std::fmt::Write; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, @@ -29,7 +30,7 @@ use vectorcraft_geom::{Affine, PathData, Point}; use crate::ps; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -324,6 +325,12 @@ fn end_read_as_none(t: &TextObject) -> bool { !closed(&segs) && end < 1.0 - 1e-9 && place_on(&segs, end) >= segs.len() as f64 - 0.02 } +/// Insert Aki Left or Right `v` as the text document holds it: 0 to [`MAX_AKI`] in 1/1000 em, and 0 +/// for a value that is not a number. +fn held_aki(v: f64) -> f64 { + if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } +} + /// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { // Small capitals are read back at Document Setup's default size. @@ -358,6 +365,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { tate_chu_yoko: s.tate_chu_yoko, // Key 35 holds one of the two: a Tate-chu-yoko run is read back without the other. standard_vertical_roman: s.standard_vertical_roman && !s.tate_chu_yoko, + aki_left: held_aki(s.aki_left), + aki_right: held_aki(s.aki_right), ..CharStyle::default() } }; @@ -675,6 +684,14 @@ impl TextDoc { }; d.push((12, V::Int(caps))); d.push((35, V::Int(baseline_direction(st)))); + // Insert Aki Left and Right in 1/1000 em, as the reader reads keys 49 and 50. No key is no + // space added: neither the stories' character attributes nor `[Normal Character Style]` set one. + for (key, v) in [(49, st.aki_left), (50, st.aki_right)] { + let v = held_aki(v); + if v > 0.0 { + d.push((key, real(v))); + } + } let fill = solid(&st.fill).flatten(); // A stroke of no width keeps its paint. let stroke = solid(&st.stroke).flatten(); diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 8d01b141d0..844cbe9f53 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -25,6 +25,7 @@ use std::collections::{BTreeMap, HashMap}; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ CharStyle, HyphenationOptions, JustificationOptions, Justify, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, @@ -489,6 +490,17 @@ struct Style { /// Key 35 at 1 (Standard): Standard Vertical Roman Alignment, half-width characters upright in /// a column. Any other value, or no key in the run, its character style or the defaults, is off. standard_vertical_roman: bool, + /// Keys 49 and 50, Insert Aki Left and Right ([`CharStyle::aki_left`]), in 1/1000 em. + aki_left: f64, + aki_right: f64, +} + +/// Insert Aki Left or Right as key `v` of a character style gives it, in 1/1000 em (the unit the +/// scripting reference gives `aki left` and `aki right`), 0 to [`MAX_AKI`]. A negative value, one +/// that is not a finite number, or no key is 0: no space added. A key the run itself carries wins +/// over its styles' even when it is not a number, so a bad value never shows a style's. +fn aki(v: Option<&Val>) -> f64 { + v.and_then(Val::num).filter(|v| v.is_finite() && *v > 0.0).map_or(0.0, |v| v.min(MAX_AKI)) } /// The longest font version string read from a font record: name ID 5 strings are short (`Version @@ -852,6 +864,8 @@ impl Texts { caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8), tate_chu_yoko: num("35") == Some(3.0), standard_vertical_roman: num("35") == Some(1.0), + aki_left: aki(pick("49")), + aki_right: aki(pick("50")), } } } @@ -1470,6 +1484,9 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size), tate_chu_yoko: s.tate_chu_yoko, standard_vertical_roman: s.standard_vertical_roman, + // In ems of the type's own size, so the art's scale does not apply. + aki_left: s.aki_left, + aki_right: s.aki_right, ..CharStyle::default() } } @@ -1754,6 +1771,47 @@ mod tests { assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman); } + /// Keys 49 and 50 of a character style are Insert Aki Left and Right in 1/1000 em, each from the + /// run, its character style and the styles that is based on, `[Normal Character Style]`, then the + /// document's defaults. A run's own 0 wins over a style's value, a value past 1000 is 1000, and a + /// negative value, one that is not a number or no key at all is 0. + #[test] + fn a_run_keeps_its_insert_aki() { + let texts = |defaults: &[u8], normal: &[u8]| Texts { + stories: vec![], + fonts: vec![], + defaults: read(defaults).unwrap(), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![ + read(&[&b"/0 ([Normal Character Style]) /6 << "[..], normal, b" >>"].concat()).unwrap(), + read(b"/0 (Base) /6 << /49 125.0 >>").unwrap(), + read(b"/0 (Spaced) /5 1 /6 << /50 500.0 >>").unwrap(), + ], + para_sheets: vec![], + frames: vec![], + patterns: HashMap::new(), + }; + let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| { + let s = texts(defaults, normal).style(Some(&read(run).unwrap())); + (s.aki_left, s.aki_right) + }; + assert_eq!(aki(b"/0 0", b"", b"/6 << /49 250.0 /50 750.0 >>"), (250.0, 750.0), "the run's own"); + assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << >>"), (125.0, 500.0), "its style's, and the style that is based on"); + assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << /49 0.0 /50 0 >>"), (0.0, 0.0), "the run's own zero wins"); + assert_eq!(aki(b"/49 10.0 /50 20.0", b"/49 30.0", b"/6 << >>"), (30.0, 20.0), "Normal, then the document's"); + assert_eq!(aki(b"/49 10.0 /50 20.0", b"", b"/6 << >>"), (10.0, 20.0), "the document's"); + assert_eq!(aki(b"/0 0", b"", b"/6 << >>"), (0.0, 0.0), "no key"); + assert_eq!(aki(b"/0 0", b"", b"/6 << /49 1000.5 /50 1e300 >>"), (MAX_AKI, MAX_AKI), "clamped"); + for bad in [&b"-1.0"[..], b"-250", b"(125)", b"true", b"[ 125 ]", b"1e400", b"-1e400"] { + let run = [&b"/5 2 /6 << /49 "[..], bad, b" /50 ", bad, b" >>"].concat(); + assert_eq!(aki(b"/0 0", b"", &run), (0.0, 0.0), "{}", String::from_utf8_lossy(bad)); + } + // In ems of the type's size: the art's scale leaves it as it is. + let s = texts(b"/0 0", b"").style(Some(&read(b"/6 << /49 250.0 /50 125.0 >>").unwrap())); + let c = char_style(&s, 10.0, Affine::IDENTITY); + assert_eq!((c.aki_left, c.aki_right), (250.0, 125.0)); + } + /// Keys 61, 62 and 64 of a character style are its stroke's cap (0 butt, 1 round, 2 /// projecting), join (0 miter, 1 round, 2 bevel) and miter limit, from the run, its character /// style or the document's defaults. A value that isn't one of theirs keeps the default, a miter @@ -2224,6 +2282,8 @@ mod tests { caps: 0, tate_chu_yoko: false, standard_vertical_roman: false, + aki_left: 0.0, + aki_right: 0.0, }, )], kerns: vec![], diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 7e38b5ba51..76980f4b7e 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -101,7 +101,7 @@ const HEX_LINE: usize = 60; pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)"; pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines"; pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)"; -pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; +pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, Insert Aki, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out"; pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)"; pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)"; pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)"; diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index 7ebae72123..d971e5249e 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -123,6 +123,9 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool { || s.optical_kerning || s.small_caps.is_some() || s.position != CharPosition::Normal + // Its text operators (§15.4) have no Insert Aki. + || s.aki_left != 0.0 + || s.aki_right != 0.0 || !s.features.is_empty() || !s.font_axes.is_empty() }; diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 15d7d07152..55e0d06171 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1394,6 +1394,41 @@ fn variable_font_settings_are_warned_as_left_out() { assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); } +/// A legacy `.ai` text object has no Insert Aki (§15.4): type with Insert Aki Left or Right is +/// written as text with the warning that it is left out. Written as outlines, the glyphs keep the +/// space it adds, and nothing is reported. +#[test] +fn insert_aki_is_warned_as_left_out_of_text() { + for (left, right) in [(250.0, 0.0), (0.0, 125.0)] { + let mut doc = typed(); + let id = texts(&doc)[0].0.id; + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.aki_left = left; + t.runs[0].style.aki_right = right; + } + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{left} {right}: {:?}", out.warnings); + assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text"); + } + let width = |aki: f64| { + let mut st = style(20.0, red()); + st.aki_left = aki; + st.aki_right = aki; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "HH", st); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }); + assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings); + let back = crate::import(&out.bytes).unwrap().document; + children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap().width() + }; + // Between the two H's: 0.5 em after the first and 0.5 em before the second, 20 pt. + let (plain, spaced) = (width(0.0), width(500.0)); + assert!((spaced - plain - 20.0).abs() < 0.05, "{plain} {spaced}"); +} + /// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a /// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back /// on the same characters, a block is closed before its text object ends, and type with neither diff --git a/docs/mcp.md b/docs/mcp.md index f756bc8c97..c84389ef33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8741,7 +8741,10 @@ menus, and a value typed past 1000 sets 1000; Reset Panel sets both to 0. Charac in Advanced Character Formats. With Fractional Widths off or System Layout on, each side is set in whole points, and justification keeps that width. Live SVG text places each character the space moves, and type on a path with Insert Aki is written as outlines. An SVG saved without Preserve Editing (`preserveEditing`) reopens without the -Insert Aki values; save it with Preserve Editing to keep them editable. +Insert Aki values; save it with Preserve Editing to keep them editable. An `.ai` file's text document keeps both +values, and opening the file reads them back. The stored values are read in thousandths of an em and a negative +value opens as 0; these are VectorCraft's own rules. A legacy `.ai` save writes type with Insert Aki as text without the values and warns that they are left +out. ```json {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"akiRight":500}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 296bd84b2b..d292278490 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1381,6 +1381,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. Character panel › Insert Aki Left and Insert Aki Right (with the East Asian options; `text.setFormat` or `text.setRangeStyle {akiLeft, akiRight}`, thousandths of an em from 0 to 1000, 0 by default) add space before and after each selected character, measured as tracking is, and kept as set through justification ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); before and after follow the reading order in vertical and right-to-left type, character styles carry both values (Character Style Options › Advanced Character Formats edits them), and a file holding a value outside the range opens with the nearer end. + Insert Aki Left and Right open from an `.ai` file's text document (read in thousandths of an em, the unit the [scripting reference](https://web.archive.org/web/20160410092022/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/pdfs/illustrator_scripting_reference_applescript.pdf#page=90) gives `aki left` and `aki right`; VectorCraft's own rule for the stored value) from the run, its character style, the styles that one is based on, `[Normal Character Style]` and the document's defaults in that order. A negative value or one that is not a number opens as 0, and a value past 1000 opens as 1000. An `.ai` save writes each run's nonzero values in the form that reader reads. A legacy `.ai` save writes type with Insert Aki as text without it and reports that it is left out; type it writes as outlines keeps the space. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). Isolation mode and opacity mask editing exclude each other ([transparency and blending modes](https://web.archive.org/web/20230102045151/https://helpx.adobe.com/illustrator/using/transparency-blending-modes.html)): in isolation mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Enter Isolation Mode and Object › Perspective › Edit Text are off, the Contextual Task Bar leaves out Isolate, and Quick Actions leave out Isolate Group. From 8fa551e173e00f7d584913cf6d3e3298f563fe93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 03:55:28 -0800 Subject: [PATCH 06/33] Selection: clicks in a clip group follow the region its clipping path's effects give it The canvas clips a clip group by its clipping path with the path's live geometry effects applied, but clicks, hovers and marquees still tested the plain clipping path. A click where a Transform effect had moved the clip selected nothing, and a click on the clipping path's own place selected art that was not drawn there. - The engine registers the effect-shaped region with the doc crate (`hit::set_clip_region`), as it does for image paint and live art. It gives a region only when the clipping path holds a visible geometry effect; otherwise clicks keep the plain shapes, and type keeps counting by its frame. - Clicks, `objects_at`, the hidden art of a selected object, the Unlock submenu's list and marquees inside a clip group or a clipping layer use that region. Outline view and layers with Preview off draw no effects and keep the plain shapes; the Selection, Direct Selection and Enclosing Lasso marquees pass the view's outline state (`hit::marquee_in_view`). Each container around a selected object tests its clipping path in the outline state a click has there. - A marquee touches the clipping path itself by its own geometry, as a click on its outline finds it, and also on the edge of the region, so a marquee around a clipping path that an effect moved into large art still selects it. `hit::marquee_in` keeps the plain shapes for the Color Theme Picker, which clips by them. - The region is kept per thread until the clipping path or the live inputs change. A clip group's reach takes in the region's box, so culling does not skip art the region moved past the plain clipping path. Up to 4096 boxes are kept; when they are full, a new box replaces only as many others as it needs room for. Docs: docs/target-app-parity.md. --- crates/doc/src/hit.rs | 368 +++++++++++++++--- crates/doc/src/hit/tests.rs | 239 ++++++++++++ crates/doc/src/node/ops.rs | 9 +- crates/engine/src/session/documents.rs | 13 + crates/engine/src/tests/clip.rs | 42 ++ crates/tools/src/addons/enclosing_lasso.rs | 2 +- .../tools/src/addons/enclosing_lasso/tests.rs | 22 ++ crates/tools/src/direct.rs | 4 +- crates/tools/src/direct/tests.rs | 23 ++ crates/tools/src/lib.rs | 30 ++ crates/tools/src/select.rs | 4 +- crates/tools/src/select/tests.rs | 19 + docs/target-app-parity.md | 1 + 13 files changed, 713 insertions(+), 63 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fd907a26cc..c0a80a8964 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,7 +1,7 @@ //! Hit testing over the document tree. use std::cell::RefCell; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::{Arc, OnceLock}; @@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & return false; } // How a click reaches it, if one does. + let start = opt; let Some(opt) = path_options(&nodes, &chain, opt) else { return false }; - // Hidden by a mask: one of the containers around it clips, and not to `p`. - let masked = nodes - .iter() - .rev() - .skip(1) - .any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p))); + // Hidden by a mask: one of the containers around it clips, and not to `p`. A container + // tests its clipping path in outline from the first layer with Preview off down to it, as + // a click going down to it does ([`path_options`]). + let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| { + let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n))); + n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline)) + }); // A click may reach it there ([`may_hit`]: not a guide while guides are locked or // hidden, nor a Shaper group's hidden part), and its own art is what a click would hit // in it: a group's hidden, locked or masked contents don't count. @@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; + let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; if layer.clips() && let Some(clip) = children.first() { @@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) { tops.push(clip.id); } - if !clip_contains(clip, p) { + if !clip_contains(clip, p, opt.outline) { return true; } } - let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; for (i, c) in children.iter().enumerate().rev() { if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) { continue; @@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec) { let Some(children) = parent.children() else { return }; - if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) { + if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) { return; } for i in hit_order(parent, children, p) { @@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool { matches!(n.kind, NodeKind::Envelope { editing: true, .. }) } -/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame: -/// glyph outlines need the font engine, above this crate. -fn clip_contains(clip: &Node, p: Point) -> bool { - clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) +/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`]) +/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count. +fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool { + let areas = if outline { clip_regions(clip) } else { clip_areas(clip) }; + areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) } -/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in -/// [`clip_contains`]. +/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry +/// effects of the clipping path and of what it clips by applied, as one path and fill rule +/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a +/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated +/// above this crate, so the engine registers one with [`set_clip_region`]. +pub type ClipRegion = fn(&Node) -> Option>; + +static CLIP_REGION: OnceLock = OnceLock::new(); + +/// Register how the region of a clipping path with live effects is found (the first registration +/// stays). +pub fn set_clip_region(f: ClipRegion) { + // Already set: the same engine, registered by another session. + let _ = CLIP_REGION.set(f); +} + +/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only +/// then can the registered [`ClipRegion`] find a geometry effect in it. +fn has_effects(clip: &Node) -> bool { + let mut found = false; + clip.walk(&mut |n| { + let visible = |e: &crate::Effect| e.visible; + found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)); + }); + found +} + +/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the +/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its +/// path elements. +struct EvaluatedClip { + clip: Node, + inputs: u64, + region: Option>>, + size: usize, +} + +/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip +/// group whose clipping path has live effects asks for its region, and clip groups can be nested. +const CLIPS_KEPT: usize = 16; + +thread_local! { + /// The regions [`clip_region`] keeps, the latest first. + static CLIPS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many regions [`clip_region`] evaluated on this thread. + static CLIPS_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The region clipping path `clip` clips to with its live geometry effects applied +/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes +/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the +/// [`LiveInputs`] have changed since. +fn clip_region(clip: &Node) -> Option>> { + let f = CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIPS.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?; + let e = kept.remove(i); + let region = e.region.clone(); + kept.insert(0, e); + Some(region) + }); + if let Some(region) = kept { + return region; + } + #[cfg(test)] + CLIPS_EVALUATED.with(|c| c.set(c.get() + 1)); + let region = f(clip).map(Rc::new); + let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len()); + let size = elements.saturating_add(art_size(std::slice::from_ref(clip))); + if size <= LIVE_KEPT_SIZE { + let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size }; + CLIPS.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(CLIPS_KEPT); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); + } + region +} + +/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the +/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path. +struct ClipBox { + clip: Node, + inputs: u64, + rect: Option, + size: usize, +} + +/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip +/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not +/// only the latest few as with the regions. +const CLIP_BOXES_KEPT: usize = 4096; + +thread_local! { + /// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes. + static CLIP_BOXES: RefCell<(HashMap, usize)> = RefCell::new((HashMap::new(), 0)); +} + +/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]), +/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change. +/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the +/// pointer moving over more clip groups than fit still finds most of their boxes. +pub(crate) fn reshaped_clip_box(clip: &Node) -> Option { + use vectorcraft_geom::kurbo::Shape; + CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect)); + if let Some(rect) = kept { + return rect; + } + let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box())); + let size = art_size(std::slice::from_ref(clip)); + if size <= LIVE_KEPT_SIZE { + CLIP_BOXES.with_borrow_mut(|(boxes, total)| { + if let Some(old) = boxes.remove(&clip.id) { + *total = total.saturating_sub(old.size); + } + while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE { + let Some(other) = boxes.keys().next().copied() else { break }; + if let Some(old) = boxes.remove(&other) { + *total = total.saturating_sub(old.size); + } + } + boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size }); + *total = total.saturating_add(size); + }); + } + rect +} + +/// The regions a click inside a clip group must fall in: those `clip` clips to with its live +/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]). +fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> { + match clip_region(clip) { + Some(region) => region.as_ref().iter().cloned().collect(), + None => clip_regions(clip), + } +} + +/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live +/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate. pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { let frame = |n: &Node| { let b = n.geometric_bounds()?; @@ -698,7 +857,7 @@ fn hit_children( // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for // the selection tools in isolation mode within it. let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); - if !edited && !clip_contains(clip, p) { + if !edited && !clip_contains(clip, p, opt.outline) { return None; } } @@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option match &n.kind { // A clip group only hits inside its clipping path. NodeKind::Group { children, clip } => { - if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) { + if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) { return None; } children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) @@ -1081,7 +1240,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> path.push(0); return true; } - if !clip_contains(&clip, self.p) { + if !clip_contains(&clip, self.p, self.opt.outline) { return false; } } @@ -1244,31 +1403,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit /// the selection tools' clicks. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false) + marquee_with(doc, r, scope, leaves, false, false) +} + +/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer +/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as +/// the clicks of [`HitOptions::outline`] do. +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group -/// traversal follow [`marquee`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option) -> Vec { - marquee_with(doc, r, scope, true, true) +/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool) -> Vec { +/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? +fn previews_off(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { preview: false, .. }) +} + +fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let mut out = Vec::new(); - // `tops` pairs each object with the part of `r` in which the marquee can touch it. - let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // The objects the marquee may touch ([`Top`]). + let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), + Some(c) => c + .iter() + .enumerate() + .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) + .map(|(_, c)| (c, Some(r), outline, None)) + .collect(), // A single object isolated: only it. None => doc .parent_of(s.id) .and_then(|p| doc.node(p)) .and_then(|p| p.children()) .into_iter() - .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r))) + .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None))) .collect(), }, // The objects of the layers, looking through sublayers (hidden, locked and template ones @@ -1277,42 +1453,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, r)) + .flat_map(|l| layer_objects(l, r, outline)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of - /// the sublayers it is in leave. - fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc, Rect)> { + /// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`, + /// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain + /// shapes ([`mask_marquee`]). + fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec> { let mut out = vec![]; - let Some(r) = marquee_in(l, r) else { return out }; - for c in l.children().into_iter().flatten() { + let outline = outline || previews_off(l); + let inner = marquee_in_parent(l, r, outline); + for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { - if c.visible && !c.locked && !c.is_template() { - out.extend(layer_objects(c, r)); + if let Some(inner) = inner + && c.visible + && !c.locked + && !c.is_template() + { + out.extend(layer_objects(c, inner, outline)); } } else if !c.is_ruler_guide() { - out.push((c, r)); + if i == 0 && l.clips() { + out.push((c, mask_marquee(l, r), outline, Some(r))); + } else if inner.is_some() { + out.push((c, inner, outline, None)); + } } } out } + /// The part of `r` in which the marquee can touch the clipping path of `parent` by its own + /// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its + /// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to. + fn mask_marquee(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) + } + /// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a + /// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where + /// the clip shows? Never in outline, nor without live effects: its own geometry counts then. + fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool { + if outline { + return false; + } + clip_region(clip).is_some_and(|region| { + region.as_ref().as_ref().is_some_and(|(bp, _)| { + // The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it. + let mut edge = PathData::from_bezpath(bp); + edge.subpaths.iter_mut().for_each(|sp| sp.closed = true); + vectorcraft_geom::hit::intersects_rect(&edge, r) + }) + }) + } + /// Is `n` collected whole by [`collect_leaves`], not by its members? + fn is_leaf(n: &Node) -> bool { + !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. }) + } /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool) -> bool { + /// compound paths, layers and groups are touched by their box. A clipping path is touched by + /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - marquee_in(n, r).is_some_and(|r| { - children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds)) + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); + children.iter().enumerate().any(|(i, c)| { + c.visible + && !shaper_hides(n, i, scope) + && if i == 0 && n.clips() { + mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline) + } else { + inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + } }) } NodeKind::Compound { children, .. } if whole_compounds => { children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A box with no width or no height (an instance of a symbol that draws a straight // line) is touched where the marquee crosses it. _ => n.geometric_bounds_with(s).is_some_and(|b| { @@ -1321,18 +1543,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh }), } } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - let Some(r) = marquee_in(n, r) else { return }; + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); for (i, c) in children.iter().enumerate() { - if c.visible && !c.locked && !shaper_hides(n, i, scope) { - collect_leaves(c, s, r, scope, whole_compounds, out); + if !c.visible || c.locked || shaper_hides(n, i, scope) { + continue; + } + if i == 0 && n.clips() { + let before = out.len(); + if let Some(r) = mask_marquee(n, r) { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); + } + if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { + out.push(c.id); + } + } else if let Some(r) = inner { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds) { + if touches(n, s, r, scope, whole_compounds, outline) { out.push(n.id); } } @@ -1340,36 +1574,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); - for (t, r) in tops { + for (t, r, outline, edge) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; } if leaves { - collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out); - } else if touches(t, &symbols, r, scope, whole_compounds) { + let before = out.len(); + if let Some(r) = r { + collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + } + if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { + out.push(t.id); + } + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) + || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) + { out.push(t.id); } } out } +/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which +/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a +/// layer, the marquee whose edge test it also takes (`clip_edge_touches`). +type Top<'a> = (&'a std::sync::Arc, Option, bool, Option); + /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a -/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None -/// when the marquee misses it); otherwise it is all of `r`. +/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its +/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`. pub fn marquee_in(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) +} + +/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its +/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline` +/// ([`marquee_in_view`]). +fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option { match parent.children().and_then(|c| c.first()) { - Some(clip) if parent.clips() => marquee_in_clip(clip, r), + Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline), _ => Some(r), } } /// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of /// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip` -/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those -/// bounds, art outside a region that is not a rectangle still counts. -fn marquee_in_clip(clip: &Node, r: Rect) -> Option { +/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of +/// those regions. Within those bounds, art outside a region that is not a rectangle still counts. +fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option { use vectorcraft_geom::kurbo::Shape; - let regions = clip_regions(clip); + let regions = if outline { clip_regions(clip) } else { clip_areas(clip) }; // The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it. let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| { let mut edge = vectorcraft_geom::PathData::from_bezpath(bp); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 3eac4202b6..4584421200 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -110,6 +110,245 @@ fn half_clipped(d: &mut Document) -> (Node, Node) { (mask, art) } +/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping +/// path, its first shape moved 100 pt right; without one, no geometry effect. +fn moved_clip_region(clip: &Node) -> Option> { + let mut moves = false; + clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + if !moves { + return None; + } + Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) +} + +/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region. +fn test_move() -> crate::Effect { + crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true } +} + +/// Clicks inside a clip group whose clipping path has a live effect fall in the region the +/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and +/// again after the clipping path changes; a clipping path without effects is not evaluated. +#[test] +fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf); + for x in [148.0, 150.0, 152.0] { + assert_eq!(leaf(&d, x), Some(art_id), "in the moved region"); + } + assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place"); + assert_eq!(evaluated(), before + 1); + // Outline mode draws no effects: the art's edge shows within the clipping path's own shape. + let outline = HitOptions { outline: true, ..HitOptions::default() }; + assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode"); + // So with a marquee across the art's left edge: in the view, only in Outline view. The + // clipping path's own left edge lies there too, and counts in both. + let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); + assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + // `marquee_in` measures by the plain shapes, as its callers clip by them. + assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); + // Hidden, the effect no longer moves the region. + d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false; + assert_eq!(leaf(&d, 50.0), Some(art_id)); + assert_eq!(leaf(&d, 150.0), None); + assert_eq!(evaluated(), before + 1); + // Shown again and widened, the region is evaluated again. + let mask = d.node_mut(mask_id).unwrap(); + mask.appearance.effects[0].visible = true; + if let NodeKind::Path { path, .. } = &mut mask.kind { + *path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0)); + } + assert_eq!(leaf(&d, 180.0), Some(art_id)); + assert_eq!(leaf(&d, 195.0), None); + assert_eq!(evaluated(), before + 2); +} + +/// A marquee around a clipping path that an effect moved into the middle of large art touches the +/// clipping path on the edge of its moved region, in a clip group and in a clipping layer. +#[test] +fn a_marquee_touches_a_moved_clipping_path_on_its_region() { + set_clip_region(moved_clip_region); + let parts = |d: &mut Document| { + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art()); + (mask, art) + }; + // Around the moved region (120..160) and the clipping path's own place, inside the art. + let around = Rect::new(10.0, 10.0, 170.0, 70.0); + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let (mask, art) = parts(&mut d); + let (g, mask_id) = (d.alloc_id(), mask.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + assert_eq!(marquee(&d, around, None, false), [g]); + assert_eq!(marquee(&d, around, None, true), [mask_id]); + // Only over the clipping path's own place, the marquee misses the region but touches the + // clipping path's anchors, which a click on its outline also finds. + let own = Rect::new(10.0, 10.0, 70.0, 70.0); + assert_eq!(marquee(&d, own, None, false), [g]); + assert_eq!(marquee(&d, own, None, true), [mask_id]); + // Away from both, nothing. + assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty()); + + let mut d = Document::new(400.0, 400.0); + let top = d.layers[0].id; + let (mask, art) = parts(&mut d); + let mask_id = mask.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + assert_eq!(marquee(&d, around, None, false), [mask_id]); +} + +/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point +/// and marquees count its clipping path by its plain shape, without the effect that moves it. +#[test] +fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind { + (*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + // The art's top edge, within the clipping path's own shape. + let p = Point::new(50.0, 0.5); + assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id)); + assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id)); + assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id)); +} + +/// The pointer moving over empty canvas past more clip groups with live effects than the regions +/// kept measures each group's box once: the boxes are kept for every clip group. +#[test] +fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + for i in 0..(2 * CLIPS_KEPT) { + let x = 20.0 * i as f64; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(500.0, 500.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + for _ in 0..3 { + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + } + assert_eq!(evaluated(), first); +} + +/// With more clip groups with live effects than the boxes kept, a new box replaces only as many +/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions. +#[test] +fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let groups = CLIP_BOXES_KEPT + 64; + let mut members = Vec::with_capacity(groups); + for i in 0..groups { + let x = (i % 100) as f64 * 5.0; + let y = (i / 100) as f64 * 5.0; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default()); + mask.appearance.effects.push(test_move()); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + members.push(Arc::new(clip)); + } + if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) { + *children = members; + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(900.0, 900.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let again = evaluated() - first; + assert!(again < groups / 8, "{again} of {groups} regions evaluated again"); +} + +/// Every test of a clip group by its clipping path follows the region a live effect moved it to: +/// the selected art hidden by the mask, a click into a group holding the clip group, the locked +/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer +/// whose Preview is off, which is clicked in outline while the layer above clips by its region. +#[test] +fn every_clip_test_follows_the_moved_region() { + set_clip_region(moved_clip_region); + let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0)); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + d.insert(Some(l), 0, outer.clone()).unwrap(); + let opt = HitOptions::default(); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place"); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region"); + let symbols = d.symbol_boxes(); + assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill)); + assert_eq!(hit_any(&outer, own, opt, &symbols), None); + d.node_mut(art_id).unwrap().locked = true; + assert_eq!(locked_objects_at(&d, moved, opt), [art_id]); + assert!(locked_objects_at(&d, own, opt).is_empty()); + + // A clipping layer holding the mask and a sublayer whose Preview is off, with the art. + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind { + (*children, *preview) = (vec![Arc::new(art)], false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + d.insert(Some(top), 0, mask).unwrap(); + d.node_mut(top).unwrap().set_clips(true); + // The art's top edge, at the clipping path's own place and in the moved region. + let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5)); + assert!(hit_test(&d, own, opt).is_none()); + assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id)); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id)); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None); +} + /// The art a mask hides counts only for a selected object: there a click hits nothing, and the /// selection tools grab the selection by that art. Not where the art shows (the click hits it), /// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index fb6e8de8d9..9d34150a88 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -211,7 +211,9 @@ impl Node { /// A quick box round everything the object can paint, for culling clicks: paths and compound /// paths grow their geometric bounds by the farthest their strokes can reach from any path - /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in + /// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a + /// clipping layer's box takes in the region that the live geometry effects of its clipping + /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box @@ -261,6 +263,11 @@ impl Node { NodeKind::Blend { children, spec } => { vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols)) } + // The live geometry effects of a clipping path can move or grow the region it clips to + // past its plain shape ([`crate::hit::set_clip_region`]). + NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { + vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) + } _ => self.visual(symbols), } } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index a87b47be0e..a1a3fe5293 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,8 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Clicks inside a clip group fall in the region its clipping path's effects give it. + vectorcraft_doc::hit::set_clip_region(reshaped_clip_region); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { @@ -491,6 +493,17 @@ impl Session { } } +/// The region clipping path `clip` clips to with its live geometry effects applied +/// ([`vectorcraft_render::effects::clip_outline`]), for clicks inside its clip group; `None` when +/// nothing in it has a visible geometry effect of its own or on a fill or stroke, so that clicks +/// count its plain shapes, type by its frame. +fn reshaped_clip_region(clip: &Node) -> Option> { + use vectorcraft_render::effects::has_geometry; + let mut reshaped = false; + clip.walk(&mut |n| reshaped |= has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(i.effects()))); + reshaped.then(|| vectorcraft_render::effects::clip_outline(clip)) +} + /// Whether some of type `t` is set in a font named (in any case) one of `names`, lowercased. fn sets_in_any(t: &TextObject, names: &HashSet) -> bool { !names.is_empty() && t.runs.iter().any(|r| names.contains(&r.style.font_family.to_lowercase())) diff --git a/crates/engine/src/tests/clip.rs b/crates/engine/src/tests/clip.rs index cbba2f36cc..7d500f6835 100644 --- a/crates/engine/src/tests/clip.rs +++ b/crates/engine/src/tests/clip.rs @@ -119,12 +119,54 @@ fn text_on_top_clips_by_its_glyphs() { assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art)); assert!(b.x1 < 95.0, "{b:?}"); assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text"); + // An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap(); + assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow"); // Release gives the text back. select(&mut s, &[g]); s.execute("object.clippingMask.release", &json!({})).unwrap(); assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_))); } +#[test] +fn clicks_follow_the_region_a_clipping_paths_effects_give_it() { + // Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves + // 50 pt right: the art shows on the right half, as clicks find it. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()); + let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap()); + select(&mut s, &[art, clip]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap(); + let r = render(&s); + assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region"); + assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path"); + assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place"); + let d = &s.doc().unwrap().doc; + let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None); + assert_eq!(at(75.0), [g]); + assert!(at(25.0).is_empty()); + // A marquee across the art's edge reaches it within the moved region only. + let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true); + assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region"); + assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place"); + + // The same with a sublayer that clips by its first object. + let mut d = (**d).clone(); + let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec(); + let top = d.layers[0].id; + d.remove(g).unwrap(); + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (members, true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf); + assert_eq!(leaf(75.0), Some(art)); + assert_eq!(leaf(25.0), None); +} + #[test] fn make_refuses_a_top_object_that_cannot_clip() { let mut s = session(); diff --git a/crates/tools/src/addons/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs index 9b92f0833d..0f674aead9 100644 --- a/crates/tools/src/addons/enclosing_lasso.rs +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool { let symbols = cx.doc.symbol_boxes(); let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); let mut ids = if let Some(region) = region { - enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation) + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline) .into_iter() .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) .collect() diff --git a/crates/tools/src/addons/enclosing_lasso/tests.rs b/crates/tools/src/addons/enclosing_lasso/tests.rs index 836e640306..a8ba79aac7 100644 --- a/crates/tools/src/addons/enclosing_lasso/tests.rs +++ b/crates/tools/src/addons/enclosing_lasso/tests.rs @@ -367,3 +367,25 @@ fn enclosing_lasso_considers_the_geometry_a_visible_compound_paints() { ); } } + +/// A loop around clipped art that the clipping path's own shape holds, but not the region a live +/// effect moved it to, selects the art in Outline view only, which draws the clipping path without +/// its effects. +#[test] +fn outline_view_loops_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let around = [(410.0, 410.0), (490.0, 410.0), (490.0, 490.0), (410.0, 490.0)]; + let gesture = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut tool = crate::create(ID); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 410.0, 410.0)); + for &(x, y) in &around[1..] { + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 410.0, 490.0)) + }; + assert_eq!(gesture(true), vec![Action::Exec("select.set".into(), json!({"ids": [art.0]}))]); + assert_eq!(gesture(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 3030414b38..cee2c7dfa1 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1608,7 +1608,7 @@ impl DirectSelectionTool { // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every // object it touches, each whole. if enclosed || whole { - let mut touched = vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true); + let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; @@ -1680,7 +1680,7 @@ impl DirectSelectionTool { } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). - for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) { + for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) { sel.push((id, vec![])); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 7ce48bdc1e..32229158af 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2396,3 +2396,26 @@ fn type_on_a_path_shows_and_drags_its_paths_handles() { assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}"); assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty()); } + +/// An Alt-marquee across clipped art where the clipping path's own shape, but not the region a +/// live effect moved it to, lets it show selects the art in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let alt = Mods { alt: true, ..Mods::default() }; + let marquee = |outline: bool| { + let c = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 440.0, 410.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 460.0, 430.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 460.0, 430.0).with_mods(alt)) + }; + let selects = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([art.0]))); + let a = marquee(true); + assert!(selects(&a), "outline: {a:?}"); + let a = marquee(false); + assert!(!selects(&a), "preview: {a:?}"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 1119bb0764..74e11e4760 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -450,6 +450,36 @@ pub(crate) mod testutil { (d, g, clip, art) } + /// A document with the rectangle of [`doc_with_rect`] and a clip group whose clipping path, + /// (400, 400)–(500, 500), has a live effect that moves the region it clips to 100 pt right + /// (registered with [`vectorcraft_doc::hit::set_clip_region`]), over art at (420, 420)–(480, 480), + /// inside the clipping path's own shape and outside the moved region: the document, the clip + /// group and the art. + pub fn doc_with_moved_clip_region() -> (Document, NodeId, NodeId) { + fn moved(clip: &Node) -> Option> { + let mut moves = false; + clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + if !moves { + return None; + } + Some(vectorcraft_doc::hit::clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) + } + vectorcraft_doc::hit::set_clip_region(moved); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = Node::path(clip, shapes::rectangle(Rect::new(400.0, 400.0, 500.0, 500.0)), Default::default()); + path.appearance.effects.push(vectorcraft_doc::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let picture = Node::path(art, shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)), Appearance::default_art()); + let group = + Node::new(g, vectorcraft_doc::NodeKind::Group { children: vec![std::sync::Arc::new(path), std::sync::Arc::new(picture)], clip: true }); + d.insert(Some(l), 1, group).unwrap(); + (d, g, art) + } + /// A new layer of `d`, above the others, with the unpainted rectangle `mask` as its clipping /// mask and `art` clipped by it: the layer and the clipping mask. pub fn add_masked_layer(d: &mut Document, mask: Rect, art: Node) -> (NodeId, NodeId) { diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 70060ebc2b..be767f60c3 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -40,7 +40,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -1125,7 +1125,7 @@ impl Tool for SelectionTool { if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) { return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - let touched = marquee(cx.doc, r, cx.isolation, false); + let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline); let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside)); let ids = if enclosed { inside(cx, r, touched) } else { touched }; let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) })); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 63ca697c7d..a04741498d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2558,3 +2558,22 @@ fn outline_view_click_through_an_image_selects_the_path_behind() { assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}"); } } + +/// A marquee across clipped art where the clipping path's own shape, but not the region a live +/// effect moved it to, lets it show reaches the clip group in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() { + let (d, g, _) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let marquee = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 440.0, 410.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 460.0, 430.0)); + t.pointer(&cx, &ev(PointerKind::Up, 460.0, 430.0)) + }; + assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]); + assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c07d6e597..2dcb038f04 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1582,6 +1582,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, and type used as a clipping path keeps them when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. From e086cf6d83c109e4c56b2e801f817f7540924ccc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 05:51:21 -0800 Subject: [PATCH 07/33] PDF, EPS and print: brush art painting onto the page keeps its path --- crates/brush/src/lib.rs | 27 +++++++++++++ crates/eps/src/scene.rs | 5 ++- crates/eps/src/tests.rs | 53 +++++++++++++++++++++++++ crates/pdf/src/export/nodes.rs | 13 +++++-- crates/pdf/src/print/layout.rs | 12 ++++-- crates/pdf/src/tests.rs | 71 ++++++++++++++++++++++++++++++++++ crates/pdf/src/tests/print.rs | 56 +++++++++++++++++++++++++++ crates/render/src/brush_fx.rs | 8 ++-- docs/mcp.md | 8 +++- docs/target-app-parity.md | 1 + 10 files changed, 240 insertions(+), 14 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 851afc9e7a..c3a532d54b 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -1001,6 +1001,33 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest +/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has +/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and +/// the exports leave for brush art when they cull. +pub fn reach(n: &Node) -> f64 { + let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none()); + if !n.appearance.items.iter().any(paints) { + return 0.0; + } + let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max); + 16.0 * w + 8.0 +} + +/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and +/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the +/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as +/// it is painted with its own appearance and not its paths'. Symbol art is not looked into +/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it). +pub fn reach_within(n: &Node) -> f64 { + let members = match &n.kind { + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(), + NodeKind::Compound { .. } => &[], + _ => n.children().map_or(&[][..], |c| &c[..]), + }; + members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max) +} + /// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any /// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed. pub fn expand(doc: &Document, n: &Node) -> Option { diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 299d130f7d..8d147cb2d1 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -489,8 +489,11 @@ impl<'a> Scene<'a> { self.warn(TOO_LARGE); return; } + // Off the region, an object is still written when brush art painted along its brushed + // strokes, or those of the objects in it, can reach the region. + let off = |b: Rect, reach: f64| !overlaps(b.inflate(1.0 + reach, 1.0 + reach), self.o.region); match n.visual_bounds_with(&self.symbols) { - Some(b) if !force && !overlaps(b.inflate(1.0, 1.0), self.o.region) => return, + Some(b) if !force && off(b, 0.0) && off(b, vectorcraft_brush::reach_within(n)) => return, None if !n.is_container() => return, _ => {} } diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 8547c4d015..c8a4bee003 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1581,6 +1581,59 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() { assert!(page.contains("1 0 0 rg"), "{page}"); } +#[test] +fn a_path_whose_brush_art_reaches_the_region_is_written() { + // A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib lies + // left of the artboard, and the nib paints 10 pt either side of it, onto the artboard: alone, in + // a group and as a compound path. Without its brush, or 100 pt left of the artboard, where the + // nib does not reach it, the line is left out. + let red = |x: f64, brushed: bool| { + let mut n = Node::path( + vectorcraft_doc::NodeId(0), + shapes::line((x, 40.0).into(), (x, 60.0).into()), + Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0), + ); + if brushed { + n.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + n + }; + let cases: [(&str, f64, bool, bool); 5] = [ + ("path", -5.0, true, true), + ("group", -5.0, true, true), + ("compound path", -5.0, true, true), + ("unbrushed path", -5.0, false, false), + ("far path", -100.0, true, false), + ]; + for (what, x, brushed, written) in cases { + let mut d = Document::new(200.0, 200.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let line = red(x, brushed); + let mut n = match what { + "group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line)]), + "compound path" => { + let mut c = Node::new( + vectorcraft_doc::NodeId(0), + NodeKind::Compound { children: vec![Arc::new(red(x, false))], rule: vectorcraft_geom::FillRule::NonZero }, + ); + c.appearance = line.appearance; + c + } + _ => line, + }; + n.id = d.alloc_id(); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, n).unwrap(); + let page = page_of(&d, &opts(&d)); + assert_eq!(page.contains("1 0 0 rg") || page.contains("1 0 0 RG"), written, "{what}: {page}"); + } +} + #[test] fn level_preview_and_overprint_ids_read_back() { for l in Level::ALL { diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 78930c7500..403cbc5431 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -14,6 +14,11 @@ struct Measured { members: Vec, } +/// Box `b` grown by `reach`, the room brush art can paint past it; `b` itself when `reach` is 0. +fn brushed(b: Option, reach: f64) -> Option { + if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -312,15 +317,17 @@ impl Exporter<'_> { krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity) } - /// The box of `n`, and of the members of a plain group or layer. + /// The box of `n`, and of the members of a plain group or layer. A box grows by the room brush + /// art can paint past the brushed strokes of `n` and of the objects in it + /// ([`vectorcraft_brush::reach_within`]), as the renderer culls it. fn measure(&self, n: &Node) -> Measured { if !matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) { #[cfg(test)] MEASURES.with(|m| m.set(m.get() + 1)); - return Measured { bounds: n.visual_bounds_with(&self.symbols), members: vec![] }; + return Measured { bounds: brushed(n.visual_bounds_with(&self.symbols), vectorcraft_brush::reach_within(n)), members: vec![] }; } let members: Vec<_> = n.editing_children().iter().map(|c| self.measure(c)).collect(); - Measured { bounds: n.visual_of_members(members.iter().map(|m| m.bounds)), members } + Measured { bounds: brushed(n.visual_of_members(members.iter().map(|m| m.bounds)), vectorcraft_brush::reach(n)), members } } pub(super) fn node(&mut self, s: &mut Surface, n: &Node, page: Rect, force: bool) { diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index a88dd89950..5d28e9e2b1 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -71,7 +71,9 @@ pub struct TileGrid { /// Calls `f` with the bounds of each object of `n` that prints: visible, not on a template /// layer and not a guide (layers are already picked by the Print Layers option). Symbol -/// instances are measured by their art from `symbols`. +/// instances are measured by their art from `symbols`. A box grows by the room brush art can +/// paint past the brushed strokes of the object and of the objects in it +/// ([`vectorcraft_brush::reach_within`]). fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { if !n.visible { return; @@ -85,7 +87,8 @@ fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { } _ => { if let Some(b) = n.visual_bounds_with(symbols) { - f(b); + let reach = vectorcraft_brush::reach_within(n); + f(if reach > 0.0 { b.inflate(reach, reach) } else { b }); } } } @@ -102,9 +105,10 @@ fn has_art(doc: &Document, r: Rect) -> bool { any } -/// The bounds of all the art that prints. +/// The bounds of all the art that prints, with the brush art it paints. The box of a symbol +/// instance whose art holds brushed strokes grows as in [`has_art`]. fn art_bounds(doc: &Document) -> Option { - let symbols = doc.symbol_boxes(); + let symbols = doc.symbol_boxes().with_brush_art(); let mut all: Option = None; for l in &doc.layers { printed(l, &symbols, &mut |b| all = Some(all.map_or(b, |a| a.union(b)))); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index bee80238bd..9487e1bca3 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -246,6 +246,77 @@ fn an_instance_whose_brush_art_reaches_the_page_is_written() { assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{:?}", l[0].geometric_bounds()); } +/// A 200 × 100 pt document whose 3 pt. Round brush paints a 20 pt round nib. +fn doc_with_wide_nib() -> Document { + let mut d = doc(200.0, 100.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + d +} + +/// A line from (`x`, 40) to (`x`, 60) with a 1 pt black stroke, painted by the 3 pt. Round brush +/// when `brushed`. +fn nib_line(x: f64, brushed: bool) -> Node { + let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + if brushed { + stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + Node::path(NodeId(0), shapes::line((x, 40.0).into(), (x, 60.0).into()), stroke) +} + +#[test] +fn a_path_whose_brush_art_reaches_the_page_is_written() { + // The line at x = -5 lies left of the page, and the 20 pt nib paints 10 pt either side of it, + // onto the page: alone, in a group, in a knockout group and as a compound path. + let compound = |n: Node| { + let mut c = Node::new(NodeId(0), NodeKind::Compound { children: vec![Arc::new(nib_line(-5.0, false))], rule: FillRule::NonZero }); + c.appearance = n.appearance; + c + }; + let knockout = |n: Node| { + let mut g = Node::group(NodeId(0), vec![Arc::new(n), Arc::new(rect_node(Rect::new(150.0, 10.0, 170.0, 30.0), Color::rgb(0.0, 0.0, 1.0)))]); + g.knockout = vectorcraft_doc::Knockout::On; + g + }; + let group = |n: Node| Node::group(NodeId(0), vec![Arc::new(n)]); + let wraps: [(&str, &dyn Fn(Node) -> Node); 4] = + [("path", &|n| n), ("group", &group), ("knockout group", &knockout), ("compound path", &compound)]; + for (what, wrap) in wraps { + let mut d = doc_with_wide_nib(); + add(&mut d, wrap(nib_line(-5.0, true))); + let out = roundtrip(&d); + let nib: Vec = leaves(&out).iter().filter_map(|n| n.geometric_bounds()).filter(|b| b.x1 < 100.0).collect(); + assert_eq!(nib.len(), 1, "{what}: the nib's art, {nib:?}"); + assert!(close(nib[0], Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{what}: {nib:?}"); + } + // Without its brush, or 100 pt left of the page, where the nib does not reach it, the line is + // left out. + for line in [nib_line(-5.0, false), nib_line(-100.0, true)] { + let mut d = doc_with_wide_nib(); + add(&mut d, line); + assert!(leaves(&roundtrip(&d)).is_empty()); + } + // A clipping path left of the page keeps the nib's art off it. + let mut d = doc_with_wide_nib(); + let clip = Node::new( + NodeId(0), + NodeKind::Path { + path: shapes::rectangle(Rect::new(-30.0, 0.0, -2.0, 100.0)), + rule: FillRule::NonZero, + live: None, + clipping: true, + guide: false, + }, + ); + add(&mut d, Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(nib_line(-5.0, true))], clip: true })); + let out = roundtrip(&d); + assert!(leaves(&out).is_empty(), "{:?}", leaves(&out)); +} + /// An instance of a symbol with 9-slice guides, scaled to 200 × 150, is written as the canvas /// draws it: its 10 × 10 corner square stays 10 × 10 and its 10 × 10 center square becomes 30 × 20. #[test] diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 5c5e1eb2c0..d7277153b3 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -451,6 +451,62 @@ fn a_symbol_instances_brush_art_keeps_its_artboard_printed() { assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{p:?}"); } +#[test] +fn a_brushed_paths_brush_art_keeps_its_artboard_printed_and_framed() { + // A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib, alone, + // in a group or as the art of a symbol instance: the line lies left of the artboard, and the nib + // paints 10 pt either side of it, onto the artboard. + let line = || { + let mut stroke = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0); + stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Node::path(vectorcraft_doc::NodeId(0), shapes::line((-5.0, 40.0).into(), (-5.0, 60.0).into()), stroke) + }; + for what in ["path", "group", "symbol instance"] { + let mut d = doc(100.0, 100.0, &[]); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let mut n = match what { + "path" => line(), + "group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line())]), + _ => { + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Nib".into(), art: Arc::new(line()) }); + Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Nib".into(), xf: vectorcraft_geom::Affine::IDENTITY }) + } + }; + n.id = d.alloc_id(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, n).unwrap(); + // Skip Blank Artboards keeps the artboard, and its page holds the nib's art. + let p = pages(&job(&d, json!({"skipBlank": true})).bytes); + assert_eq!(p.len(), 1, "{what}"); + assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{what}: {p:?}"); + // Ignoring artboards, the page holds all the nib's art, 20 × 40 pt. + let pv = preview(&d, &settings(json!({"artboards": "ignore"}))).unwrap(); + let t = pv.sheets[0].trim; + assert!(t[2] - t[0] >= 20.0 && t[3] - t[1] >= 40.0, "{what}: {t:?}"); + } + // A compound path is painted with its own appearance: the brushed stroke left on its path + // paints nothing, and the artboard stays blank. + let mut d = doc(100.0, 100.0, &[]); + let kind = NodeKind::Compound { children: vec![Arc::new(line())], rule: vectorcraft_geom::FillRule::NonZero }; + let mut compound = Node::new(d.alloc_id(), kind); + compound.appearance = Appearance::basic(Paint::None, rgb(1.0, 0.0, 0.0), 1.0).into(); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, compound).unwrap(); + assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err()); + // A brushed stroke without a paint draws no brush art: the artboard stays blank. + let mut d = doc(100.0, 100.0, &[]); + let mut unpainted = line(); + unpainted.id = d.alloc_id(); + unpainted.appearance.stroke_mut().unwrap().paint = Paint::None; + d.insert(Some(layer), 0, unpainted).unwrap(); + assert!(preview(&d, &settings(json!({"skipBlank": true}))).is_err()); +} + #[test] fn copies_collate_and_reverse() { let mut d = diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index 3c6ea922d4..fe7eb0f804 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -157,17 +157,17 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO /// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it /// has a visible brushed stroke and of the objects in that art that have one /// ([`SymbolBoxes::brush_width`]) or the pieces live-effect plug-ins paint for them -/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. +/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. The room for `n`'s own strokes +/// is [`vectorcraft_brush::reach`], which the exports leave too. pub(crate) fn pad(symbols: &SymbolBoxes, n: &Node) -> f64 { - let own = vectorcraft_brush::has_brush(n) - .then(|| n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max)); + let own = vectorcraft_brush::reach(n); let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => { symbols.brush_width(symbol).into_iter().chain(crate::fx::painted_brush_width(symbols, symbol)).reduce(f64::max).map(|w| w.max(1.0)) } _ => None, }; - own.into_iter().chain(art).reduce(f64::max).map_or(0.0, |w| 16.0 * w + 8.0) + art.map_or(own, |w| own.max(16.0 * w + 8.0)) } pub use vectorcraft_brush::instance_art; diff --git a/docs/mcp.md b/docs/mcp.md index 0cbb30e0b6..2832e7f169 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5015,8 +5015,12 @@ when its symbol or a symbol nested in its art holds an instance of itself, and w nest 32 deep in its art. PDF and EPS export and the SVG of an artboard leave out art outside the page or artboard, and Skip Blank Artboards skips an artboard with no art on it. For both, the box of an instance whose art holds brushed strokes grows by 16 times the widest stroke (at least 1 pt) of the objects in its art that have a brushed stroke, -plus 8 pt. The SVG of an artboard also keeps an object whose effects paint onto the artboard, and an object that holds -an instance when the effects in the symbol's art, or the instance's own, paint onto it. +plus 8 pt. PDF and EPS export and Skip Blank Artboards grow the box of an object with a visible, painted brushed stroke the +same way, by its own widest stroke, and the box of an object that holds one by the largest such room among them (of a +clip group, only its clipping path counts). Print with Ignore Artboards frames the page around the art with the same +room for brushed objects and for instances whose art holds brushed strokes. The SVG of an artboard also keeps an +object whose effects paint onto the artboard, and an object that holds an instance when the effects in the symbol's +art, or the instance's own, paint onto it. ## Expand diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 08ce46cebf..f0349613f4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2003,6 +2003,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. - **Painted pieces with brushed strokes are culled and measured by their brush art (G17):** a piece that keeps the object's brushed stroke draws the brush along the piece's own path at the piece's stroke width. Culling leaves VectorCraft's usual room for brush art (16 × the stroke width + 8 pt) past each piece, from the piece's width rather than the object's, and so does culling of a group, layer, symbol instance, blend, envelope or repeat that holds the object. A group or layer also leaves that room for each brushed path among its members, painted or not. Object › Rasterize takes the brush art drawn along each piece and leaves out the object's own brush art, which is not drawn. Pieces without a brush are culled as before. Regressions: `crates/render/src/tests/paintedbrush.rs`. Scores and hours unchanged. +- **Brushed paths just off the page are exported and printed:** PDF and EPS export keep a path or compound path whose brush art reaches the page while the path lies just off it, alone or in a group, by leaving the canvas's room for brush art (16 × the widest stroke + 8 pt, VectorCraft's own value) past its box. Skip Blank Artboards keeps an artboard such brush art reaches, and Print with Ignore Artboards frames the page with that room around brushed paths and around instances whose art holds brushed strokes. A clip group leaves room only for its clipping path. Art without brushed strokes is written as before. Regressions: `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/print.rs`, `crates/eps/src/tests.rs`. Scores and hours unchanged. - **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged. - **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. From 9efde43f1d827b95b838b75cc5d310362a9814f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 04:20:33 -0800 Subject: [PATCH 08/33] Metafile import: EMF and WMF are read through craft-metafile, so EMF+ pictures open EMF and WMF import now plays the records with the shared craft-metafile reader (storytold/craft-libs#778, at the craft-libs rev the SVG, EPS and DXF crates already use) and maps its picture onto the document here: paths with their fills, strokes, caps, joins, miter limits and dashes, clipping groups, images and point type. The EMF and WMF record players in crates/metafile/src/import and the DIB decoder they used are removed. The writers are unchanged, and the PICT reader keeps its own player. What changes for a file being opened, placed or pasted, and for an EPS file's Windows metafile preview (read when its PostScript can't be): - An EMF that draws with EMF+ records is read from them. It opened empty, with a warning that EMF+ is not read. A file with both kinds of record is read from its EMF+ records too. - Hatched and pattern brushes fill with the average color of the brush's tile, translucent where the tile has gaps. Hatches filled with the hatch color and pattern brushes with gray. - Translucent fills, strokes and EMF+ text keep their alpha as opacity. - Text keeps a stretch across from the world transform; it kept only the turn. Text the file clips to a rectangle is clipped to it, and an underlined or struck-through font gives underlined or struck-through type. - A clip path whose bounding box holds the whole picture is kept unless it is that rectangle; a diamond or a bow tie around the picture was dropped. - Images drawn with SRCAND, SRCPAINT or SRCINVERT are drawn as they look over white, and images drawn with other raster operations are drawn as a plain copy. They were left out with a warning. - Excluded clip rectangles and the other clip region modes are applied. A clip path combined with RGN_OR, RGN_XOR or RGN_DIFF is ignored without the warning it gave. - An image past the reader's size or pixel limits, or one that can't be decoded, is left out without a warning of its own. A file past the reader's limits (more than 32 nested clip paths, 200,000 drawn items, 256 MiB held) is read up to that point without a warning. - An EMF record whose size is not a multiple of 4 ends the file, with the "ends early" warning. Tests: an EMF+ only picture imports its fill (it failed before), a dual EMF+ file draws its translucent EMF+ fill and not its fallback, hatch and pattern brush colors, clipped and underlined text, excluded clip rectangles, a shared clipping group, an odd record size, WMF at 1440 units an inch without a placeable header and at its own units with an inverted box, an EMF without a frame, diamond and bow-tie clips, text with a stretch, clips nested past the stack and 200,000 clip records; the fuzz test gains random EMF+ records. --- Cargo.lock | 12 + Cargo.toml | 2 + crates/engine/tests/import_fuzz.rs | 18 + crates/metafile/Cargo.toml | 3 +- crates/metafile/src/bytes.rs | 52 +-- crates/metafile/src/dib.rs | 288 +----------- crates/metafile/src/import.rs | 632 +++----------------------- crates/metafile/src/import/emf.rs | 392 ---------------- crates/metafile/src/import/pict.rs | 6 +- crates/metafile/src/import/picture.rs | 523 +++++++++++++++++++++ crates/metafile/src/import/wmf.rs | 338 -------------- crates/metafile/src/lib.rs | 13 +- crates/metafile/src/tests/import.rs | 304 ++++++++++++- docs/mcp.md | 9 +- docs/target-app-parity.md | 1 + 15 files changed, 948 insertions(+), 1645 deletions(-) delete mode 100644 crates/metafile/src/import/emf.rs create mode 100644 crates/metafile/src/import/picture.rs delete mode 100644 crates/metafile/src/import/wmf.rs diff --git a/Cargo.lock b/Cargo.lock index f3e85a08a7..32fcfc62ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1043,6 +1043,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-metafile" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2" +dependencies = [ + "encoding_rs", + "image", + "kurbo 0.13.1", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -6681,6 +6692,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ + "craft-metafile", "image", "kurbo 0.13.1", "vectorcraft-brush", diff --git a/Cargo.toml b/Cargo.toml index c7856d589e..610e2b462c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,8 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } +# WMF, EMF and EMF+ reader (craft-libs#778). +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 79178d6233..51615e70c8 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2933,6 +2933,24 @@ proptest! { survive_metafile("WMF records", "x.wmf", &wmf_of(&records))?; } + #[test] + fn random_emf_plus_records_never_panic(records in prop::collection::vec((0x4001u16..0x403B, any::(), arb_body()), 0..32)) { + // One comment of EMF+ records (type, flags, data) after an EmfPlusHeader. + let mut plus = vec![]; + let header = (0x4001u16, 0u16, [0xDBC0_1002u32, 0, 96, 96].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + for (kind, flags, data) in std::iter::once(&header).chain(&records) { + plus.extend(kind.to_le_bytes()); + plus.extend(flags.to_le_bytes()); + plus.extend((12 + data.len() as u32).to_le_bytes()); + plus.extend((data.len() as u32).to_le_bytes()); + plus.extend(data); + } + let mut comment = (4 + plus.len() as u32).to_le_bytes().to_vec(); + comment.extend(b"EMF+"); + comment.extend(plus); + survive_metafile("EMF+ records", "x.emf", &emf_of(&[(70, comment)]))?; + } + #[test] fn pasted_metafiles_never_panic(which in 0usize..2, cut in 0usize..200_000, edits in prop::collection::vec((0usize..200_000, any::()), 0..12)) { paste_from_elsewhere("clipboard.importEmf", json!({"dataBase64": mutated_b64(metafile_samples()[which].clone(), cut, &edits)}))?; diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 01b5d6434a..9fdf99d732 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT) reader" +description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader" [lints] workspace = true @@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } +craft-metafile = { workspace = true } kurbo = { workspace = true } image = { workspace = true } diff --git a/crates/metafile/src/bytes.rs b/crates/metafile/src/bytes.rs index ddf534b793..133a476866 100644 --- a/crates/metafile/src/bytes.rs +++ b/crates/metafile/src/bytes.rs @@ -1,5 +1,4 @@ -//! Little-endian values: the buffer both writers build records in, and a reader that never reads -//! past its data (every read is an `Option`). +//! Little-endian values: the buffer both writers build records in. /// Bytes being written. #[derive(Default)] @@ -45,52 +44,3 @@ impl Out { } } } - -/// Sequential little-endian reads from a slice. -#[derive(Clone, Copy)] -pub(crate) struct Reader<'a> { - data: &'a [u8], - pos: usize, -} - -impl<'a> Reader<'a> { - pub fn new(data: &'a [u8]) -> Self { - Self { data, pos: 0 } - } - pub fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { - let b = self.data.get(self.pos..self.pos.checked_add(n)?)?; - self.pos += n; - Some(b) - } - fn array(&mut self) -> Option<[u8; N]> { - self.bytes(N)?.try_into().ok() - } - pub fn u16(&mut self) -> Option { - self.array().map(u16::from_le_bytes) - } - pub fn i16(&mut self) -> Option { - self.array().map(i16::from_le_bytes) - } - pub fn u32(&mut self) -> Option { - self.array().map(u32::from_le_bytes) - } - pub fn i32(&mut self) -> Option { - self.array().map(i32::from_le_bytes) - } - pub fn f32(&mut self) -> Option { - self.array().map(f32::from_le_bytes) - } - pub fn skip(&mut self, n: usize) -> Option<()> { - self.bytes(n).map(drop) - } - /// The bytes not read yet. - pub fn rest(&self) -> &'a [u8] { - self.data.get(self.pos..).unwrap_or_default() - } -} - -/// `len` bytes of `data` from `offset` (record-relative offsets read from untrusted files). -pub(crate) fn slice(data: &[u8], offset: u32, len: u32) -> Option<&[u8]> { - let start = usize::try_from(offset).ok()?; - data.get(start..start.checked_add(usize::try_from(len).ok()?)?) -} diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index 4aeb5b4381..9bc720f435 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -1,28 +1,22 @@ //! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit -//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source); read from 1, -//! 4, 8, 16, 24 and 32-bit uncompressed and bit-field bitmaps and from embedded JPEG and PNG. +//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source). use std::io::Cursor; -use crate::bytes::Reader; - /// Most pixels along a side of an image the writers store (larger ones are scaled down). const MAX_SIDE: u32 = 8192; /// Most pixels an image the writers store holds. const MAX_PIXELS: u64 = 1 << 24; -/// Most pixels along a side, and in all, of a bitmap the reader decodes. +/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes. pub(crate) const MAX_READ_SIDE: u32 = 1 << 15; pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26; /// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small /// file of many image records can't cost minutes of decoding (#3600). pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; -/// What [`decode`] says of a bitmap past what is left of the file's budget. +/// What [`charge`] says of a bitmap past what is left of the file's budget. pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may"; const BI_RGB: u32 = 0; -const BI_BITFIELDS: u32 = 3; -const BI_JPEG: u32 = 4; -const BI_PNG: u32 = 5; /// Pixels with straight (not premultiplied) alpha, row by row from the top. #[derive(Clone, Debug, PartialEq)] @@ -121,48 +115,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec, Vec) { (header(img.width, img.height, 32, bits.len()), bits) } -/// How the fourth byte of 32-bit pixels reads. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Alpha { - /// Unused (StretchDIBits and BitBlt ignore it): every pixel opaque. - Ignore, - /// Premultiplied alpha (AlphaBlend with per-pixel alpha). - Premultiplied, -} - -/// A colour channel of `v` under `mask`, scaled to 0–255. -fn channel(v: u32, mask: u32) -> u8 { - if mask == 0 { - return 0; - } - let shift = mask.trailing_zeros(); - let max = u64::from(mask >> shift); - let x = u64::from((v & mask) >> shift); - ((x * 255 + max / 2) / max.max(1)).min(255) as u8 -} - -/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`), -/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG -/// whose chunks don't read to the end, are returned as they are. -fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { - const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; - if !bytes.starts_with(SIGNATURE) { - return bytes.into(); - } - let mut out = SIGNATURE.to_vec(); - let mut at = SIGNATURE.len(); - while at < bytes.len() { - let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() }; - let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize; - let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() }; - if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") { - out.extend_from_slice(&bytes[at..end]); - } - at = end; - } - out.into() -} - /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); @@ -170,215 +122,24 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { Ok(()) } -/// Read a DIB from its BITMAPINFO (`bmi`: the header and colour table) and pixel `bits`, taking its -/// pixels from what is `left` of the file's budget ([`MAX_FILE_PIXELS`]). -pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> Result { - let bad = || "a bitmap is damaged".to_string(); - let mut r = Reader::new(bmi); - let size = r.u32().ok_or_else(bad)?; - let (width, height, bpp, compression, colors, palette_entry, masks_at) = if size == 12 { - // BITMAPCOREHEADER: 16-bit sizes, RGB triples. - let w = i32::from(r.u16().ok_or_else(bad)?); - let h = i32::from(r.u16().ok_or_else(bad)?); - r.skip(2).ok_or_else(bad)?; - let bpp = r.u16().ok_or_else(bad)?; - (w, h, bpp, BI_RGB, 0, 3, 0) - } else if size >= 40 { - let w = r.i32().ok_or_else(bad)?; - let h = r.i32().ok_or_else(bad)?; - r.skip(2).ok_or_else(bad)?; - let bpp = r.u16().ok_or_else(bad)?; - let c = r.u32().ok_or_else(bad)?; - r.skip(12).ok_or_else(bad)?; - let used = r.u32().ok_or_else(bad)?; - (w, h, bpp, c, used, 4, 40) - } else { - return Err(bad()); - }; - if compression == BI_JPEG || compression == BI_PNG { - // The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded. - // A PNG's compressed ICC profile and text chunks expand when its decoder is made, and - // nothing here uses them: they are left out before the size is read and the pixels decoded. - let bits = png_without_metadata(bits); - let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?; - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } - charge(w, h, left)?; - let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8(); - return Ok(Rgba { width: w, height: h, pixels: img.into_raw() }); - } - if compression != BI_RGB && compression != BI_BITFIELDS { - return Err("compressed (RLE) bitmaps can't be read yet".into()); - } - let top_down = height < 0; - let (w, h) = (width.unsigned_abs(), height.unsigned_abs()); - if w == 0 || h == 0 { - return Err("a bitmap is empty".into()); - } - if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS { - return Err("a bitmap is too large to read".into()); - } - let header_len = size as usize; - // Bit-field masks follow a plain 40-byte header, or sit inside the larger ones. - let fields = compression == BI_BITFIELDS; - let masks: Option<[u32; 4]> = fields.then(|| { - let mut m = Reader::new(bmi.get(masks_at..).unwrap_or_default()); - let rgb = [m.u32().unwrap_or(0), m.u32().unwrap_or(0), m.u32().unwrap_or(0)]; - // An alpha mask comes with BITMAPV3INFOHEADER and later. - let a = if header_len >= 56 { m.u32().unwrap_or(0) } else { 0 }; - [rgb[0], rgb[1], rgb[2], a] - }); - let palette_at = header_len + if fields && header_len == 40 { 12 } else { 0 }; - let bpp_u = u32::from(bpp); - let palette: Vec<[u8; 3]> = if bpp_u <= 8 { - let n = if colors == 0 { 1usize << bpp_u } else { (colors as usize).min(256) }; - bmi.get(palette_at..) - .unwrap_or_default() - .chunks_exact(palette_entry) - .take(n) - .map(|e| [e.get(2).copied().unwrap_or(0), e.get(1).copied().unwrap_or(0), e.first().copied().unwrap_or(0)]) - .collect() - } else { - vec![] - }; - if !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) { - return Err(format!("{bpp}-bit bitmaps can't be read")); - } - let row = stride(w, bpp_u).ok_or_else(bad)?; - if bits.len() < row.checked_mul(h as usize).ok_or_else(bad)? { - return Err(bad()); - } - charge(w, h, left)?; - let (mr, mg, mb, ma) = match (masks, bpp) { - (Some([r, g, b, a]), _) => (r, g, b, a), - (None, 16) => (0x7c00, 0x03e0, 0x001f, 0), - _ => (0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0xff00_0000), - }; - let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..h as usize { - let src_row = if top_down { y } else { h as usize - 1 - y }; - let line = bits.get(src_row * row..src_row * row + row).ok_or_else(bad)?; - for x in 0..w as usize { - let px: [u8; 4] = match bpp { - 1 | 4 | 8 => { - let bit = x * bpp_u as usize; - let byte = line.get(bit / 8).copied().unwrap_or(0); - let idx = (byte >> (8 - bpp_u as usize - bit % 8)) & ((1u16 << bpp_u) - 1) as u8; - let [r, g, b] = palette.get(idx as usize).copied().unwrap_or([0, 0, 0]); - [r, g, b, 255] - } - 16 => { - let v = u32::from(u16::from_le_bytes([line.get(x * 2).copied().unwrap_or(0), line.get(x * 2 + 1).copied().unwrap_or(0)])); - [channel(v, mr), channel(v, mg), channel(v, mb), 255] - } - 24 => { - let p = line.get(x * 3..x * 3 + 3).unwrap_or(&[0, 0, 0]); - [p[2], p[1], p[0], 255] - } - _ => { - let p = line.get(x * 4..x * 4 + 4).unwrap_or(&[0, 0, 0, 0]); - let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]); - let a = if alpha == Alpha::Premultiplied && ma != 0 { channel(v, ma) } else { 255 }; - let un = - |c: u8| if alpha == Alpha::Premultiplied && a < 255 { (u32::from(c) * 255 / u32::from(a.max(1))).min(255) as u8 } else { c }; - [un(channel(v, mr)), un(channel(v, mg)), un(channel(v, mb)), if alpha == Alpha::Premultiplied { a } else { 255 }] - } - }; - pixels.extend_from_slice(&px); - } - } - Ok(Rgba { width: w, height: h, pixels }) -} - -/// A packed DIB (a BITMAPINFO and its bits, one after the other, as WMF records hold them) split -/// into the two. -pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> { - let mut r = Reader::new(packed); - let size = r.u32()? as usize; - let (bpp, compression, used, entry) = if size == 12 { - r.skip(6)?; - (r.u16()?, BI_RGB, 0, 3) - } else { - r.skip(10)?; - let bpp = r.u16()?; - let c = r.u32()?; - r.skip(12)?; - (bpp, c, r.u32()? as usize, 4) - }; - let masks = if compression == BI_BITFIELDS && size == 40 { 12 } else { 0 }; - let colors = if used > 0 { - used.min(256) - } else if bpp <= 8 { - 1usize << bpp - } else { - 0 - }; - let len = size.checked_add(masks)?.checked_add(colors * entry)?; - Some((packed.get(..len)?, packed.get(len..)?)) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() { - use image::ImageEncoder; - let mut png = vec![]; - let mut encoder = image::codecs::png::PngEncoder::new(&mut png); - encoder.set_icc_profile(vec![0; 1 << 20]).unwrap(); - encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap(); - assert!(png.windows(4).any(|w| w == b"iCCP")); - let stripped = png_without_metadata(&png); - assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len()); - let img = image::load_from_memory(&stripped).unwrap().to_rgba8(); - assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]); - // Not a PNG, or a PNG cut short: unchanged. - assert_eq!(&*png_without_metadata(b"BM...."), b"BM...."); - assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]); - } - fn sample() -> Rgba { // 3 × 2: red, green, blue / half-transparent black, transparent, white. let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]; Rgba { width: 3, height: 2, pixels } } - /// A whole file's budget. - fn budget() -> u64 { - MAX_FILE_PIXELS - } - - /// A BITMAPINFOHEADER of an embedded PNG. - fn png_header() -> Vec { - let mut bmi = vec![0u8; 40]; - bmi[..4].copy_from_slice(&40u32.to_le_bytes()); - bmi[16..20].copy_from_slice(&BI_PNG.to_le_bytes()); - bmi - } - - #[test] - fn oversized_png_is_refused_from_its_header() { - // A width over the limit in the IHDR chunk: decoding the pixels would fail with a different error. - let png = crate::tests::png_claiming(MAX_READ_SIDE + 1, 1); - let err = decode(&png_header(), &png, Alpha::Ignore, &mut budget()).unwrap_err(); - assert_eq!(err, "a bitmap is too large to read"); - } - #[test] fn bitmaps_share_the_file_budget() { // #3600: each bitmap is charged before it is decoded, and one past what is left is refused. - let (bmi, bits) = rgb24(&sample(), 1.0); let mut left = 6 + 5; - assert!(decode(&bmi, &bits, Alpha::Ignore, &mut left).is_ok()); + assert!(charge(3, 2, &mut left).is_ok()); assert_eq!(left, 5); - assert_eq!(decode(&bmi, &bits, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET); + assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET); assert_eq!(left, 5, "a refused bitmap costs nothing"); - // An embedded PNG is charged from its header, so one past the budget is never decoded. - let mut left = (1 << 20) - 1; - let png = crate::tests::png_claiming(1 << 10, 1 << 10); - assert_eq!(decode(&png_header(), &png, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET); } #[test] @@ -402,45 +163,6 @@ mod tests { assert_eq!(&half[12..16], &[0, 0, 128, 128]); } - #[test] - fn rgb24_round_trips_over_white() { - let (bmi, bits) = rgb24(&sample(), 1.0); - assert_eq!(bmi.len(), 40); - // Rows of 9 bytes padded to 12. - assert_eq!(bits.len(), 24); - let back = decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap(); - assert_eq!((back.width, back.height), (3, 2)); - assert_eq!(&back.pixels[..12], &[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]); - // Half-transparent black over white is mid grey; transparent is white. - assert_eq!(&back.pixels[12..16], &[127, 127, 127, 255]); - assert_eq!(&back.pixels[16..20], &[255, 255, 255, 255]); - } - - #[test] - fn bgra32_round_trips_with_alpha() { - let (bmi, bits) = bgra32(&sample(), 1.0); - let back = decode(&bmi, &bits, Alpha::Premultiplied, &mut budget()).unwrap(); - assert_eq!(&back.pixels[..12], &sample().pixels[..12]); - assert_eq!(back.pixels[15], 128); - assert_eq!(back.pixels[19], 0); - // Read as StretchDIBits does, alpha is ignored. - assert!(decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap().opaque()); - } - - #[test] - fn palette_bitmaps_and_damage() { - // A 1-bit 2 × 1 bitmap: black then white. - let mut bmi = header(2, 1, 1, 4); - bmi.extend_from_slice(&[0, 0, 0, 0, 255, 255, 255, 0]); - let back = decode(&bmi, &[0b0100_0000, 0, 0, 0], Alpha::Ignore, &mut budget()).unwrap(); - assert_eq!(back.pixels, vec![0, 0, 0, 255, 255, 255, 255, 255]); - // Too few bits, a silly size, an unknown depth: errors, no panic. - assert!(decode(&bmi, &[0], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&header(1 << 20, 1 << 20, 24, 0), &[], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&header(1, 1, 7, 0), &[0; 4], Alpha::Ignore, &mut budget()).is_err()); - assert!(decode(&[1, 2], &[], Alpha::Ignore, &mut budget()).is_err()); - } - #[test] fn large_images_are_scaled_to_fit() { let img = image::RgbaImage::new(MAX_SIDE * 2, 4); diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index da7816663e..43023e0183 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,16 +1,14 @@ -//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play -//! their records on a [`Player`], a small model of the device context they draw into (objects, -//! transforms, the current position, the path bracket, the clip), which turns what they draw into -//! document objects. +//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`, +//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their +//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which +//! turns what they draw into document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep -//! their pixels (as PNG), text becomes point type in the font the file names. Records the reader -//! doesn't know are counted and skipped, with one warning. +//! their pixels (as PNG), text becomes point type in the font the file names. -mod emf; pub(crate) mod pict; -mod wmf; +mod picture; use std::sync::Arc; @@ -20,7 +18,7 @@ use vectorcraft_doc::{ Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind, StrokeLayer, TextObject, }; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, Vec2, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; use crate::dib::{self, Rgba}; use crate::{Imported, Kind}; @@ -30,24 +28,13 @@ const MAX_NODES: usize = 1 << 20; /// Objects and clips reaching further than this from the origin (points, well inside the canvas) /// are left out: they come from damaged or hostile coordinates. const LIMIT: f64 = 1e6; -/// Most nested saved device contexts. -const MAX_SAVED: usize = 1024; /// Width of a cosmetic pen (one pixel of a 96 ppi screen), points. const HAIRLINE: f64 = 0.75; -/// Curves made for arcs and ellipses are this close to the true curve (logical units are -/// transformed after, so it is relative). -const ARC_TOLERANCE: f64 = 0.01; /// Raster operations. pub(crate) const SRCCOPY: u32 = 0x00CC_0020; -const PATCOPY: u32 = 0x00F0_0021; -const WHITENESS: u32 = 0x00FF_0062; -const BLACKNESS: u32 = 0x0000_0042; const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out"; -const HATCHES: &str = "hatched brushes are filled with their colour"; -const PATTERN_BRUSHES: &str = "pattern brushes are filled grey"; -const EXCLUDED_CLIPS: &str = "clip areas cut out of the clip (excluded rectangles, differences) are ignored"; const BAD_IMAGE: &str = "an image that couldn't be read was left out"; const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out"; const FAR_AWAY: &str = "objects far outside the picture were left out"; @@ -57,6 +44,50 @@ fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT) } +/// Is `path` an upright rectangle around the whole of `frame`? Writers clip to one first; it clips +/// nothing in the picture. +fn around(path: &BezPath, frame: Rect) -> bool { + if path.elements().len() > 6 { + return false; + } + let b = path.bounding_box(); + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + let near = |p: Point, q: Point| (p - q).hypot() <= 1e-6 * (1.0 + b.width().max(b.height())); + // Each edge, the closing one included, runs along a side: from a corner to itself or to a + // neighbor (corners are in order around the box), never across it. + let along = |i: usize, j: usize| (i + 4 - j) % 4 != 2; + let mut seen = [false; 4]; + let (mut first, mut last) = (None, None); + for e in path.elements() { + let (p, start) = match e { + PathEl::MoveTo(p) => (*p, true), + PathEl::LineTo(p) => (*p, false), + PathEl::ClosePath => continue, + PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false, + }; + let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false }; + if start { + if let (Some(f), Some(l)) = (first, last) + && !along(f, l) + { + return false; + } + first = Some(i); + } else if last.is_some_and(|l| !along(l, i)) { + return false; + } + last = Some(i); + seen[i] = true; + } + if let (Some(f), Some(l)) = (first, last) + && !along(f, l) + { + return false; + } + let b = b.inflate(0.5, 0.5); + seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1)) +} + /// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries. #[derive(Clone, Debug, PartialEq)] pub(crate) struct PenObj { @@ -68,7 +99,6 @@ pub(crate) struct PenObj { } impl PenObj { - pub const NULL: PenObj = PenObj { style: PS_NULL, width: 0.0, color: [0; 3], entries: vec![] }; pub fn solid(color: [u8; 3]) -> Self { Self { style: 0, width: 0.0, color, entries: vec![] } } @@ -77,28 +107,6 @@ impl PenObj { pub(crate) const PS_NULL: u32 = 5; const PS_GEOMETRIC: u32 = 0x0001_0000; -/// A brush. -#[derive(Clone, Debug, PartialEq)] -pub(crate) enum BrushObj { - Null, - Solid([u8; 3]), - Hatched([u8; 3]), - /// A bitmap pattern (written grey). - Pattern, -} - -impl BrushObj { - /// From a LOGBRUSH's style and colour. - pub fn from_log(style: u32, color: [u8; 3]) -> Self { - match style { - 0 => Self::Solid(color), - 1 => Self::Null, - 2 => Self::Hatched(color), - _ => Self::Pattern, - } - } -} - /// A font: its height in logical units (negative: the character height, positive: the cell /// height), escapement (tenths of a degree), weight, italics and face. #[derive(Clone, Debug, Default, PartialEq)] @@ -110,35 +118,17 @@ pub(crate) struct FontObj { pub face: String, } -/// A GDI object. -#[derive(Clone, Debug)] -pub(crate) enum Obj { - Pen(PenObj), - Brush(BrushObj), - Font(FontObj), - /// Palettes, regions, colour spaces: they take a slot but don't change the drawing. - Other, -} - -/// The state records change, saved and restored as a whole. +/// The drawing state. #[derive(Clone, Debug)] struct Dc { pen: PenObj, - brush: BrushObj, + /// The brush's color. + brush: [u8; 3], font: FontObj, text_color: [u8; 3], text_align: u32, fill_rule: FillRule, miter: f64, - /// Arcs run counterclockwise (the default). - arc_ccw: bool, - /// Logical → page (EMF world transform). - world: Affine, - map_mode: u32, - win_org: Vec2, - win_ext: Vec2, - vp_org: Vec2, - vp_ext: Vec2, clips: Vec>, } @@ -146,105 +136,38 @@ impl Default for Dc { fn default() -> Self { Self { pen: PenObj::solid([0; 3]), - brush: BrushObj::Solid([255; 3]), + brush: [255; 3], font: FontObj::default(), text_color: [0; 3], text_align: 0, fill_rule: FillRule::EvenOdd, miter: 10.0, - arc_ccw: true, - world: Affine::IDENTITY, - map_mode: 1, - win_org: Vec2::ZERO, - win_ext: Vec2::new(1.0, 1.0), - vp_org: Vec2::ZERO, - vp_ext: Vec2::new(1.0, 1.0), clips: vec![], } } } -/// How an arc closes. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ArcKind { - Open, - Chord, - Pie, -} - pub(crate) struct Player { kind: Kind, - /// Device units (EMF) or logical units (WMF) → document points. + /// Picture units → document points. dev_to_doc: Affine, - /// Millimetres per device pixel (EMF's fixed mapping modes). - mm_per_px: f64, dc: Dc, - saved: Vec, - objects: Vec>, - /// The lowest object slot that may be free (WMF numbering). - free_hint: usize, - /// The path being recorded (document space), whether a figure is open in it and where that - /// figure started (logical). - path: Option, - figure: bool, - figure_start: Point, /// The artboard (document space): clips holding all of it clip nothing worth keeping. frame: Rect, - /// The current position (logical). - pos: Point, - /// Lines drawn one after another outside a path bracket, not drawn yet. + /// Lines drawn one after another, not drawn yet. pending: BezPath, out: Drawn, doc: Document, warnings: Vec, - skipped: usize, next_clip: u32, /// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]). pub pixels_left: u64, - /// The file holds EMF+ records (which aren't read). - pub emf_plus: bool, } fn rgb(c: [u8; 3]) -> Paint { Paint::solid(Color::rgb8(c[0], c[1], c[2])) } -/// The arc of the ellipse in `r` from the ray through `start` to the ray through `end`. -pub(crate) fn arc_path(r: Rect, start: Point, end: Point, ccw: bool, kind: ArcKind) -> BezPath { - let r = r.abs(); - let c = r.center(); - let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); - let mut bp = BezPath::new(); - if radii.x <= 0.0 || radii.y <= 0.0 { - return bp; - } - let angle = |p: Point| ((p.y - c.y) / radii.y).atan2((p.x - c.x) / radii.x); - let (a0, a1) = (angle(start), angle(end)); - let tau = std::f64::consts::TAU; - // Counterclockwise on a y-down device is towards smaller angles. - let sweep = if ccw { - let s = (a0 - a1).rem_euclid(tau); - -(if s == 0.0 { tau } else { s }) - } else { - let s = (a1 - a0).rem_euclid(tau); - if s == 0.0 { tau } else { s } - }; - let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; - let tol = ARC_TOLERANCE * radii.x.max(radii.y).max(1e-9); - if kind == ArcKind::Pie { - bp.move_to(c); - let first = c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin()); - bp.line_to(first); - arc.append_iter(tol).for_each(|el| bp.push(el)); - } else { - kurbo::Shape::path_elements(&arc, tol).for_each(|el| bp.push(el)); - } - if kind != ArcKind::Open { - bp.close_path(); - } - bp -} - /// A rectangle with elliptical corners `rx` × `ry`. pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { let r = r.abs(); @@ -261,7 +184,7 @@ pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { } impl Player { - fn new(kind: Kind, dev_to_doc: Affine, mm_per_px: f64, artboard: Rect) -> Self { + fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self { let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; let (w, h) = (side(artboard.width()), side(artboard.height())); let mut doc = Document::new(w, h); @@ -269,24 +192,14 @@ impl Player { Self { kind, dev_to_doc, - mm_per_px, dc: Dc::default(), - saved: vec![], - objects: vec![], - free_hint: 0, - path: None, - figure: false, - figure_start: Point::ZERO, frame: artboard, - pos: Point::ZERO, pending: BezPath::new(), out: vec![], doc, warnings: vec![], - skipped: 0, next_clip: 0, pixels_left: dib::MAX_FILE_PIXELS, - emf_plus: false, } } @@ -296,188 +209,19 @@ impl Player { } } - /// A record of a kind the reader doesn't know. - pub fn skip(&mut self) { - self.skipped += 1; - } - // ---------- mapping ---------- - /// Logical → document. + /// Picture units → document. fn xf(&self) -> Affine { - if self.kind == Kind::Wmf { - return self.dev_to_doc; - } - let d = &self.dc; - let page_to_dev = match d.map_mode { - // Fixed modes: millimetres a unit, y up. - 2..=6 => { - let mm = [0.1, 0.01, 0.254, 0.0254, 25.4 / 1440.0][(d.map_mode - 2) as usize]; - let s = mm / self.mm_per_px.max(1e-12); - Affine::translate(d.vp_org) * Affine::scale_non_uniform(s, -s) * Affine::translate(-d.win_org) - } - 7 | 8 => { - let ratio = |v: f64, w: f64| if w.abs() > 1e-12 && v.is_finite() { v / w } else { 1.0 }; - let (mut sx, mut sy) = (ratio(d.vp_ext.x, d.win_ext.x), ratio(d.vp_ext.y, d.win_ext.y)); - if d.map_mode == 7 { - // Isotropic: the same scale both ways, the smaller one. - let s = sx.abs().min(sy.abs()); - (sx, sy) = (s.copysign(sx), s.copysign(sy)); - } - Affine::translate(d.vp_org) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-d.win_org) - } - _ => Affine::translate(d.vp_org - d.win_org), - }; - self.dev_to_doc * page_to_dev * d.world + self.dev_to_doc } - /// How much logical lengths grow in the document. + /// How much picture lengths grow in the document. fn scale(&self) -> f64 { let s = self.xf().determinant().abs().sqrt(); if s.is_finite() { s } else { 0.0 } } - pub fn set_map_mode(&mut self, m: u32) { - self.dc.map_mode = m; - } - pub fn set_window_org(&mut self, x: f64, y: f64) { - self.dc.win_org = Vec2::new(x, y); - } - pub fn set_window_ext(&mut self, x: f64, y: f64) { - self.dc.win_ext = Vec2::new(x, y); - } - pub fn set_viewport_org(&mut self, x: f64, y: f64) { - self.dc.vp_org = Vec2::new(x, y); - } - pub fn set_viewport_ext(&mut self, x: f64, y: f64) { - self.dc.vp_ext = Vec2::new(x, y); - } - pub fn scale_ext(&mut self, window: bool, x: (f64, f64), y: (f64, f64)) { - let e = if window { &mut self.dc.win_ext } else { &mut self.dc.vp_ext }; - if x.1 != 0.0 && y.1 != 0.0 { - *e = Vec2::new(e.x * x.0 / x.1, e.y * y.0 / y.1); - } - } - /// `SetWorldTransform` / `ModifyWorldTransform` (`mode`: 1 identity, 2 left, 3 right, 4 set). - pub fn world(&mut self, x: Affine, mode: u32) { - if !x.as_coeffs().iter().all(|v| v.is_finite()) { - return; - } - self.dc.world = match mode { - 1 => Affine::IDENTITY, - 2 => self.dc.world * x, - 3 => x * self.dc.world, - _ => x, - }; - } - - // ---------- state ---------- - - pub fn set_fill_mode(&mut self, alternate: bool) { - self.dc.fill_rule = if alternate { FillRule::EvenOdd } else { FillRule::NonZero }; - } - pub fn set_miter(&mut self, m: f64) { - if m.is_finite() && m >= 1.0 { - self.dc.miter = m; - } - } - pub fn set_arc_ccw(&mut self, ccw: bool) { - self.dc.arc_ccw = ccw; - } - pub fn set_text_color(&mut self, c: [u8; 3]) { - self.dc.text_color = c; - } - pub fn set_text_align(&mut self, a: u32) { - self.dc.text_align = a; - } - - pub fn save(&mut self) { - if self.saved.len() < MAX_SAVED { - self.saved.push(self.dc.clone()); - } - } - - /// `RestoreDC(n)`: a negative `n` counts back from the latest save, a positive one is a save's - /// number. - pub fn restore(&mut self, n: i32) { - let len = self.saved.len(); - let keep = if n < 0 { len.checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1).filter(|k| *k < len) }; - if let Some(k) = keep { - self.saved.truncate(k + 1); - if let Some(dc) = self.saved.pop() { - self.dc = dc; - } - } - } - - // ---------- objects ---------- - - /// Put `obj` in slot `index` (EMF numbers its objects). - pub fn create_at(&mut self, index: u32, obj: Obj) { - let i = index as usize; - if i == 0 || i > u16::MAX as usize { - return; - } - if self.objects.len() <= i { - self.objects.resize(i + 1, None); - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - - /// Put `obj` in the lowest free slot (WMF). - pub fn create(&mut self, obj: Obj) { - let start = self.free_hint.min(self.objects.len()); - let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start); - if i > u16::MAX as usize { - // The table is full past the hint: the next creation looks from the end, not again - // through every slot. - self.free_hint = i; - return; - } - if i == self.objects.len() { - self.objects.push(None); - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - self.free_hint = i + 1; - } - - pub fn delete(&mut self, index: u32) { - if let Some(s) = self.objects.get_mut(index as usize) { - *s = None; - self.free_hint = self.free_hint.min(index as usize); - } - } - - /// Select object `index`, or a stock object (EMF: the high bit set). - pub fn select(&mut self, index: u32) { - if self.kind == Kind::Emf && index & 0x8000_0000 != 0 { - match index & 0x7fff_ffff { - 0 | 18 => self.dc.brush = BrushObj::Solid([255; 3]), - 1 => self.dc.brush = BrushObj::Solid([0xc0; 3]), - 2 => self.dc.brush = BrushObj::Solid([0x80; 3]), - 3 => self.dc.brush = BrushObj::Solid([0x40; 3]), - 4 => self.dc.brush = BrushObj::Solid([0; 3]), - 5 => self.dc.brush = BrushObj::Null, - 6 => self.dc.pen = PenObj::solid([255; 3]), - 7 | 19 => self.dc.pen = PenObj::solid([0; 3]), - 8 => self.dc.pen = PenObj::NULL, - 10..=17 => self.dc.font = FontObj::default(), - _ => {} - } - return; - } - match self.objects.get(index as usize).cloned().flatten() { - Some(Obj::Pen(p)) => self.dc.pen = p, - Some(Obj::Brush(b)) => self.dc.brush = b, - Some(Obj::Font(f)) => self.dc.font = f, - _ => {} - } - } - // ---------- output ---------- fn push(&mut self, mut node: Node) { @@ -491,19 +235,8 @@ impl Player { self.out.push((self.dc.clips.clone(), node)); } - fn fill_paint(&mut self) -> Option { - match self.dc.brush.clone() { - BrushObj::Null => None, - BrushObj::Solid(c) => Some(rgb(c)), - BrushObj::Hatched(c) => { - self.warn(HATCHES); - Some(rgb(c)) - } - BrushObj::Pattern => { - self.warn(PATTERN_BRUSHES); - Some(rgb([0x80; 3])) - } - } + fn fill_paint(&self) -> Paint { + rgb(self.dc.brush) } fn stroke_layer(&self) -> Option { @@ -549,8 +282,8 @@ impl Player { return; } let mut items = vec![]; - if fill && let Some(p) = self.fill_paint() { - items.push(AppearanceItem::Fill(FillLayer::new(p))); + if fill { + items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint()))); } if stroke && let Some(st) = self.stroke_layer() { items.push(AppearanceItem::Stroke(st)); @@ -573,124 +306,7 @@ impl Player { } } - /// A figure in logical units: added to the path being recorded, else drawn (filled when it is - /// an area). - pub fn figure(&mut self, mut bp: BezPath, area: bool) { - bp.apply_affine(self.xf()); - match &mut self.path { - Some(path) => { - path.extend(bp); - self.figure = false; - } - None => self.draw(bp, area, true), - } - } - - /// Polygon / Polyline (and Bézier ones): `pts` in logical units. - pub fn poly(&mut self, pts: &[Point], closed: bool, bezier: bool) { - let Some((first, rest)) = pts.split_first() else { return }; - let mut bp = BezPath::new(); - bp.move_to(*first); - if bezier { - for c in rest.as_chunks::<3>().0 { - bp.curve_to(c[0], c[1], c[2]); - } - } else { - rest.iter().for_each(|p| bp.line_to(*p)); - } - if closed { - bp.close_path(); - } - self.figure(bp, closed); - } - - /// Several polygons (one area) or polylines. - pub fn poly_poly(&mut self, polys: &[Vec], closed: bool) { - let mut bp = BezPath::new(); - for p in polys { - let Some((first, rest)) = p.split_first() else { continue }; - bp.move_to(*first); - rest.iter().for_each(|q| bp.line_to(*q)); - if closed { - bp.close_path(); - } - } - self.figure(bp, closed); - } - - pub fn move_to(&mut self, p: Point) { - self.pos = p; - self.figure = false; - } - - /// LineTo / PolylineTo / PolyBezierTo: from the current position through `pts` (logical). - pub fn poly_to(&mut self, pts: &[Point], bezier: bool) { - let Some(last) = pts.last().copied() else { return }; - let xf = self.xf(); - let start = xf * self.pos; - let target = match &mut self.path { - Some(path) => { - if !self.figure { - path.move_to(start); - self.figure = true; - self.figure_start = self.pos; - } - path - } - None => { - if self.pending.elements().last().and_then(|e| e.end_point()) != Some(start) { - self.pending.move_to(start); - } - &mut self.pending - } - }; - if bezier { - for c in pts.as_chunks::<3>().0 { - target.curve_to(xf * c[0], xf * c[1], xf * c[2]); - } - } else { - pts.iter().for_each(|p| target.line_to(xf * *p)); - } - self.pos = last; - } - - pub fn arc(&mut self, r: Rect, start: Point, end: Point, kind: ArcKind) { - let bp = arc_path(r, start, end, self.dc.arc_ccw, kind); - self.figure(bp, kind != ArcKind::Open); - } - - // ---------- paths and clips ---------- - - pub fn begin_path(&mut self) { - self.path = Some(BezPath::new()); - self.figure = false; - } - pub fn end_path(&mut self) { - // The path stays until it is filled, stroked or made the clip. - } - pub fn close_figure(&mut self) { - if let Some(p) = &mut self.path - && self.figure - { - p.close_path(); - self.figure = false; - self.pos = self.figure_start; - } - } - pub fn abort_path(&mut self) { - self.path = None; - } - - /// FillPath / StrokePath / StrokeAndFillPath. - pub fn paint_path(&mut self, fill: bool, stroke: bool) { - if let Some(mut bp) = self.path.take() { - // Filling closes the open figure. - if fill && self.figure { - bp.close_path(); - } - self.draw(bp, fill, stroke); - } - } + // ---------- clips ---------- fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) { if replace { @@ -699,10 +315,7 @@ impl Player { if !sane(path.bounding_box()) { return self.warn(FAR_AWAY); } - // A rectangle around the whole picture (what writers clip to first) clips nothing in it. - let lines = path.elements().iter().all(|e| !matches!(e, PathEl::QuadTo(..) | PathEl::CurveTo(..))); - let around = path.bounding_box().inflate(0.5, 0.5); - if lines && path.elements().len() <= 6 && around.contains(self.frame.origin()) && around.contains(Point::new(self.frame.x1, self.frame.y1)) { + if around(&path, self.frame) { return; } if self.dc.clips.len() >= MAX_NEST { @@ -712,69 +325,10 @@ impl Player { self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })); } - /// SelectClipPath (`mode`: 1 and, 5 copy; the others cut out, which isn't read). - pub fn clip_path(&mut self, mode: u32) { - let Some(bp) = self.path.take() else { return }; - match mode { - 1 => self.push_clip(bp, self.dc.fill_rule, false), - 5 => self.push_clip(bp, self.dc.fill_rule, true), - _ => self.warn(EXCLUDED_CLIPS), - } - } - - /// IntersectClipRect (logical units). - pub fn clip_rect(&mut self, r: Rect) { - let mut bp = shapes::rectangle(r.abs()).to_bezpath(); - bp.apply_affine(self.xf()); - self.push_clip(bp, FillRule::NonZero, false); - } - - /// A clip region of `rects` in device units (`mode` as [`Self::clip_path`]); none with mode - /// copy removes the clip. - pub fn clip_region(&mut self, rects: &[Rect], mode: u32) { - if rects.is_empty() { - if mode == 5 { - self.dc.clips.clear(); - } - return; - } - let mut bp = BezPath::new(); - for r in rects { - bp.extend(shapes::rectangle(r.abs()).to_bezpath()); - } - bp.apply_affine(self.dev_to_doc); - match mode { - 1 => self.push_clip(bp, FillRule::NonZero, false), - 5 => self.push_clip(bp, FillRule::NonZero, true), - _ => self.warn(EXCLUDED_CLIPS), - } - } - - pub fn exclude_clip(&mut self) { - self.warn(EXCLUDED_CLIPS); - } - - // ---------- blits, images and text ---------- - - /// A raster operation without a source over `dest` (logical): the brush, white or black. - pub fn pattern_blit(&mut self, dest: Rect, rop: u32) { - let brush = match rop { - PATCOPY => self.dc.brush.clone(), - WHITENESS => BrushObj::Solid([255; 3]), - BLACKNESS => BrushObj::Solid([0; 3]), - _ => return self.skip(), - }; - let pen = std::mem::replace(&mut self.dc.pen, PenObj::NULL); - let outer = std::mem::replace(&mut self.dc.brush, brush); - let mut bp = shapes::rectangle(dest.abs()).to_bezpath(); - bp.apply_affine(self.xf()); - self.draw(bp, true, false); - self.dc.pen = pen; - self.dc.brush = outer; - } + // ---------- images and text ---------- /// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest` - /// (logical: origin and signed size) with raster operation `rop`, at `opacity`. + /// (picture units: origin and signed size) with raster operation `rop`, at `opacity`. pub fn image(&mut self, img: Result, src: Rect, dest: Rect, rop: u32, opacity: f64) { if rop != SRCCOPY { self.warn(SKIPPED_ROPS); @@ -793,8 +347,8 @@ impl Player { self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity); } - /// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image - /// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the + /// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An + /// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the /// document's images. pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) { if img.width == 0 || img.height == 0 { @@ -814,14 +368,13 @@ impl Player { self.push(n); } - /// Text at `at` (logical; the current position with TA_UPDATECP) in the current font. + /// Text at `at` (picture units) in the current font. pub fn text(&mut self, at: Point, s: &str) { let s: String = s.chars().filter(|c| *c != '\0').collect(); if s.trim().is_empty() { return; } let align = self.dc.text_align; - let at = if align & 1 != 0 { self.pos } else { at }; let f = self.dc.font.clone(); let k = self.scale(); // A negative height is the em; a positive one the cell (the em and the internal leading). @@ -863,18 +416,7 @@ impl Player { /// The document: what was drawn on one layer, clipped art in clipping groups. fn finish(mut self) -> Imported { self.flush(); - if self.skipped > 0 { - let n = self.skipped; - self.warnings.push(format!( - "{n} record{} of kinds VectorCraft doesn't read {} skipped", - if n == 1 { "" } else { "s" }, - if n == 1 { "was" } else { "were" } - )); - } let out = std::mem::take(&mut self.out); - if out.is_empty() && self.emf_plus { - self.warnings.push("the picture is drawn with EMF+ records, which aren't read yet: nothing was imported".into()); - } let children = nest(&mut self.doc, out); let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); if let Some(c) = layer.children_mut() { @@ -904,33 +446,7 @@ fn crop(img: Rgba, src: Rect) -> Rgba { Rgba { width: x1 - x0, height: y1 - y0, pixels } } -/// Read a metafile. +/// Read an EMF or WMF file. pub(crate) fn import(bytes: &[u8]) -> Result { - match crate::sniff(bytes) { - Some(Kind::Emf) => emf::play(bytes), - Some(Kind::Wmf) => wmf::play(bytes), - None => Err("not an EMF or WMF file".into()), - } -} - -#[cfg(test)] -mod table_tests { - use super::*; - - /// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next - /// ones don't scan every slot again; a freed slot is still found. - #[test] - fn a_full_object_table_is_not_rescanned() { - let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0)); - for _ in 0..=u16::MAX as usize + 1 { - p.create(Obj::Other); - } - p.delete(5); - p.create(Obj::Other); - p.create(Obj::Other); - assert!(p.free_hint > u16::MAX as usize); - p.delete(7); - p.create(Obj::Other); - assert!(p.objects[7].is_some()); - } + picture::import(bytes) } diff --git a/crates/metafile/src/import/emf.rs b/crates/metafile/src/import/emf.rs deleted file mode 100644 index ece16c7864..0000000000 --- a/crates/metafile/src/import/emf.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! EMF records (MS-EMF) played on a [`Player`]: the header gives the frame (the artboard) and the -//! reference device (device pixels → millimetres), then every record in turn until EMR_EOF. - -use vectorcraft_geom::{Affine, Point, Rect}; - -use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player}; -use crate::bytes::{Reader, slice}; -use crate::dib::{self, Alpha}; -use crate::{Imported, Kind}; - -/// Points per millimetre. -const PT_PER_MM: f64 = 72.0 / 25.4; -/// Most points one record may give (a hostile count can't make a huge allocation). -const MAX_POINTS: usize = 1 << 22; -/// Records that change nothing VectorCraft keeps (background mode and colour, raster modes, -/// palettes, colour management, comments…). -const IGNORED: &[u32] = - &[1, 13, 15, 16, 18, 20, 21, 23, 25, 28, 48, 50, 51, 52, 65, 66, 70, 98, 100, 101, 104, 110, 111, 112, 113, 115, 119, 120, 121]; - -fn rect(r: &mut Reader) -> Option { - Some(Rect::new(f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?))) -} - -fn point32(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i32()?), f64::from(r.i32()?))) -} - -fn point16(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?))) -} - -fn color(r: &mut Reader) -> Option<[u8; 3]> { - let [red, g, b, _] = r.u32()?.to_le_bytes(); - Some([red, g, b]) -} - -fn xform(r: &mut Reader) -> Option { - let mut v = [0.0; 6]; - for x in &mut v { - *x = f64::from(r.f32()?); - } - Some(Affine::new(v)) -} - -/// `n` points (32-bit or 16-bit), `None` when the record is shorter. -fn points(r: &mut Reader, n: u32, wide: bool) -> Option> { - let n = n as usize; - if n > MAX_POINTS || r.rest().len() < n * if wide { 8 } else { 4 } { - return None; - } - (0..n).map(|_| if wide { point32(r) } else { point16(r) }).collect() -} - -/// The polygons of a PolyPolygon / PolyPolyline record. -fn polys(r: &mut Reader, wide: bool) -> Option>> { - r.skip(16)?; - let n = r.u32()? as usize; - let total = r.u32()?; - if n > MAX_POINTS || r.rest().len() < n * 4 { - return None; - } - let counts: Vec = (0..n).map(|_| r.u32()).collect::>()?; - let mut all = points(r, total, wide)?.into_iter(); - Some(counts.iter().map(|c| all.by_ref().take(*c as usize).collect()).collect()) -} - -/// A LOGFONTW → the font. -fn font(r: &mut Reader) -> Option { - let height = f64::from(r.i32()?); - r.skip(4)?; - let escapement = f64::from(r.i32()?); - r.skip(4)?; - let weight = r.i32()?; - let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0); - r.skip(7)?; - let units: Vec = (0..32).map_while(|_| r.u16()).take_while(|c| *c != 0).collect(); - Some(FontObj { height, escapement, weight, italic, face: String::from_utf16_lossy(&units) }) -} - -/// The bitmap of an image record: its BITMAPINFO and bits at the offsets the record gives. -fn bitmap(rec: &[u8], off_bmi: u32, cb_bmi: u32, off_bits: u32, cb_bits: u32, alpha: Alpha, left: &mut u64) -> Result { - let bmi = slice(rec, off_bmi, cb_bmi).ok_or("damaged")?; - let bits = slice(rec, off_bits, cb_bits).ok_or("damaged")?; - dib::decode(bmi, bits, alpha, left) -} - -/// The rows a DIB's source rectangle counts from the bottom in (StretchDIBits on a bottom-up DIB). -fn bottom_up(rec: &[u8], off_bmi: u32) -> bool { - let at = off_bmi as usize; - let size = rec.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); - let height = rec.get(at + 8..at + 12).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes); - size.is_some_and(|s| s >= 40) && height.is_some_and(|h| h > 0) -} - -/// The source rectangle `(x, y, w, h)` of an image of `img`'s height, counted from the top. -fn source(x: i32, y: i32, w: i32, h: i32, img: &Result, from_bottom: bool) -> Rect { - let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height)); - let (x, y, w, h) = (f64::from(x), f64::from(y), f64::from(w), f64::from(h)); - let top = if from_bottom { ih - y - h } else { y }; - Rect::new(x, top, x + w, top + h) -} - -/// The size and placement of the picture: (device → document, millimetres a pixel, the artboard). -fn frame(bytes: &[u8]) -> Option<(Affine, f64, Rect)> { - let mut r = Reader::new(bytes); - r.skip(4)?; - let header_size = r.u32()?; - let bounds = rect(&mut r)?; - let frame = rect(&mut r)?; - // Signature, version, bytes, records, handles, description and palette size. - r.skip(32)?; - let device = (f64::from(r.i32()?), f64::from(r.i32()?)); - let mm = (f64::from(r.i32()?), f64::from(r.i32()?)); - // The device in micrometres (more precise), when the header has it. - let micro = if header_size >= 108 { - r.skip(12)?; - Some((f64::from(r.u32()?), f64::from(r.u32()?))) - } else { - None - }; - let ok = |v: f64| v.is_finite() && v > 0.0; - let mm_per_px = match micro { - Some((mx, _)) if ok(mx) && ok(device.0) => mx / 1000.0 / device.0, - _ if ok(mm.0) && ok(device.0) => mm.0 / device.0, - _ => 25.4 / 96.0, - }; - let mm_per_px = if mm_per_px.is_finite() && mm_per_px > 1e-9 { mm_per_px } else { 25.4 / 96.0 }; - let k = mm_per_px * PT_PER_MM; - // The frame (0.01 mm) in device pixels; an empty frame falls back to the bounds. - let f = frame.abs(); - let (origin, size) = if f.width() > 0.0 && f.height() > 0.0 { - (Point::new(f.x0 / 100.0 / mm_per_px, f.y0 / 100.0 / mm_per_px), (f.width() / 100.0 * PT_PER_MM, f.height() / 100.0 * PT_PER_MM)) - } else { - let b = bounds.abs(); - (b.origin(), ((b.width() + 1.0) * k, (b.height() + 1.0) * k)) - }; - let dev_to_doc = Affine::scale(k) * Affine::translate(-origin.to_vec2()); - let side = |v: f64| if v.is_finite() { v.clamp(1.0, 1e6) } else { 1.0 }; - Some((dev_to_doc, mm_per_px, Rect::new(0.0, 0.0, side(size.0), side(size.1)))) -} - -pub(super) fn play(bytes: &[u8]) -> Result { - let (dev_to_doc, mm_per_px, artboard) = frame(bytes).ok_or("the EMF header is damaged")?; - let mut p = Player::new(Kind::Emf, dev_to_doc, mm_per_px, artboard); - let mut at = 0usize; - let mut ended = false; - while let Some(head) = bytes.get(at..at + 8) { - let kind = u32::from_le_bytes([head[0], head[1], head[2], head[3]]); - let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; - let Some(rec) = bytes.get(at..at.saturating_add(size)).filter(|_| size >= 8) else { break }; - if kind == 14 { - ended = true; - break; - } - if !matches!(kind, 27 | 54 | 5 | 6 | 88 | 89) { - p.flush(); - } - if record(&mut p, kind, rec).is_none() { - p.skip(); - } - at += size; - } - if !ended { - p.warn("the file ends early: what it held was imported"); - } - Ok(p.finish()) -} - -/// PolyBezier, Polygon, Polyline, PolyBezierTo, PolylineTo and their 16-bit forms. -fn rec_poly(p: &mut Player, kind: u32, r: &mut Reader) -> Option<()> { - let wide = kind < 85; - r.skip(16)?; - let n = r.u32()?; - let pts = points(r, n, wide)?; - match if wide { kind } else { kind - 83 } { - 2 => p.poly(&pts, false, true), - 3 => p.poly(&pts, true, false), - 4 => p.poly(&pts, false, false), - 5 => p.poly_to(&pts, true), - _ => p.poly_to(&pts, false), - } - Some(()) -} - -/// CreatePen (38). -fn rec_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> { - let ih = r.u32()?; - let style = r.u32()?; - let width = f64::from(r.i32()?); - r.skip(4)?; - p.create_at(ih, Obj::Pen(PenObj { style, width, color: color(r)?, entries: vec![] })); - Some(()) -} - -/// ExtCreatePen (95). -fn rec_ext_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> { - let ih = r.u32()?; - r.skip(16)?; - let style = r.u32()?; - let width = f64::from(r.u32()?); - let brush = r.u32()?; - let c = color(r)?; - r.skip(4)?; - let n = (r.u32()? as usize).min(64); - let entries: Vec = (0..n).map_while(|_| r.u32()).map(f64::from).collect(); - // A pen painted with the null brush draws nothing. - let style = if brush == 1 { super::PS_NULL } else { style }; - p.create_at(ih, Obj::Pen(PenObj { style, width, color: c, entries })); - Some(()) -} - -/// GdiComment (70): EMF+ records ride in comments starting "EMF+". -fn rec_comment(p: &mut Player, r: &mut Reader) -> Option<()> { - r.skip(4)?; - p.emf_plus |= r.u32()? == 0x2B46_4D45; - Some(()) -} - -/// ExtSelectClipRgn (75). -fn rec_clip_region(p: &mut Player, r: &mut Reader) -> Option<()> { - let cb = r.u32()?; - let mode = r.u32()?; - let data = r.bytes(cb as usize)?; - let mut d = Reader::new(data); - let rects = if cb >= 32 { - d.skip(8)?; - let n = d.u32()? as usize; - d.skip(20)?; - if n > MAX_POINTS || d.rest().len() < n * 16 { - return None; - } - (0..n).map(|_| rect(&mut d)).collect::>>()? - } else { - vec![] - }; - p.clip_region(&rects, mode); - Some(()) -} - -/// The rectangle at `(x, y)` of size `(w, h)`. -fn at_size(x: i32, y: i32, w: i32, h: i32) -> Rect { - Rect::new(f64::from(x), f64::from(y), f64::from(x) + f64::from(w), f64::from(y) + f64::from(h)) -} - -/// BitBlt (76) and StretchBlt (77). -fn rec_blt(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let dest = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let rop = r.u32()?; - let (xs, ys) = (r.i32()?, r.i32()?); - r.skip(24 + 4 + 4)?; - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - let (ws, hs) = if kind == 77 { (r.i32()?, r.i32()?) } else { (dest.2, dest.3) }; - let d = at_size(dest.0, dest.1, dest.2, dest.3); - if cb_bmi == 0 { - p.pattern_blit(d, rop); - } else { - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, false); - p.image(img, src, d, rop, 1.0); - } - Some(()) -} - -/// StretchDIBits (81). -fn rec_stretch_dibits(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let (xd, yd, xs, ys, ws, hs) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - r.skip(4)?; - let rop = r.u32()?; - let (wd, hd) = (r.i32()?, r.i32()?); - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, bottom_up(rec, off_bmi)); - p.image(img, src, at_size(xd, yd, wd, hd), rop, 1.0); - Some(()) -} - -/// AlphaBlend (114). -fn rec_alpha_blend(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16)?; - let (xd, yd, wd, hd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let blend = r.bytes(4)?; - let (constant, per_pixel) = (blend.get(2).copied().unwrap_or(255), blend.get(3).is_some_and(|f| *f & 1 != 0)); - let (xs, ys) = (r.i32()?, r.i32()?); - r.skip(24 + 4 + 4)?; - let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?); - let (ws, hs) = (r.i32()?, r.i32()?); - let alpha = if per_pixel { Alpha::Premultiplied } else { Alpha::Ignore }; - let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, alpha, &mut p.pixels_left); - let src = source(xs, ys, ws, hs, &img, false); - p.image(img, src, at_size(xd, yd, wd, hd), crate::import::SRCCOPY, f64::from(constant) / 255.0); - Some(()) -} - -/// ExtTextOutA (83) and ExtTextOutW (84). -fn rec_text(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> { - r.skip(16 + 4 + 8)?; - let at = point32(r)?; - let n = r.u32()? as usize; - let off = r.u32()?; - let s = if kind == 84 { - let raw = slice(rec, off, u32::try_from(n.checked_mul(2)?).ok()?)?; - String::from_utf16_lossy(&raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::>()) - } else { - slice(rec, off, u32::try_from(n).ok()?)?.iter().map(|b| char::from(*b)).collect() - }; - p.text(at, &s); - Some(()) -} - -/// Play one record (`rec`: all of it, with its type and size). `None`: unknown or damaged. -fn record(p: &mut Player, kind: u32, rec: &[u8]) -> Option<()> { - let mut r = Reader::new(rec.get(8..)?); - match kind { - 2..=6 | 85..=89 => rec_poly(p, kind, &mut r)?, - 7 | 90 => p.poly_poly(&polys(&mut r, kind == 7)?, false), - 8 | 91 => p.poly_poly(&polys(&mut r, kind == 8)?, true), - 9 => p.set_window_ext(f64::from(r.i32()?), f64::from(r.i32()?)), - 10 => p.set_window_org(f64::from(r.i32()?), f64::from(r.i32()?)), - 11 => p.set_viewport_ext(f64::from(r.i32()?), f64::from(r.i32()?)), - 12 => p.set_viewport_org(f64::from(r.i32()?), f64::from(r.i32()?)), - 17 => p.set_map_mode(r.u32()?), - 19 => p.set_fill_mode(r.u32()? == 1), - 22 => p.set_text_align(r.u32()?), - 24 => p.set_text_color(color(&mut r)?), - 27 => p.move_to(point32(&mut r)?), - 29 => p.exclude_clip(), - 30 => p.clip_rect(rect(&mut r)?), - 31 | 32 => { - let (xn, xd, yn, yd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - p.scale_ext(kind == 32, (f64::from(xn), f64::from(xd)), (f64::from(yn), f64::from(yd))); - } - 33 => p.save(), - 34 => p.restore(r.i32()?), - 35 => p.world(xform(&mut r)?, 4), - 36 => { - let x = xform(&mut r)?; - p.world(x, r.u32()?); - } - 37 => p.select(r.u32()?), - 38 => rec_create_pen(p, &mut r)?, - 39 => { - let ih = r.u32()?; - let style = r.u32()?; - p.create_at(ih, Obj::Brush(BrushObj::from_log(style, color(&mut r)?))); - } - 40 => p.delete(r.u32()?), - 42 => p.figure(vectorcraft_geom::shapes::ellipse(rect(&mut r)?.abs()).to_bezpath(), true), - 43 => p.figure(vectorcraft_geom::shapes::rectangle(rect(&mut r)?.abs()).to_bezpath(), true), - 44 => { - let b = rect(&mut r)?; - let (cx, cy) = (f64::from(r.i32()?), f64::from(r.i32()?)); - p.figure(super::round_rect(b, cx, cy), true); - } - 45..=47 => { - let b = rect(&mut r)?; - let (s, e) = (point32(&mut r)?, point32(&mut r)?); - p.arc(b, s, e, [ArcKind::Open, ArcKind::Chord, ArcKind::Pie][(kind - 45) as usize]); - } - 49 | 99 | 122 => p.create_at(r.u32()?, Obj::Other), - 54 => { - let pt = point32(&mut r)?; - p.poly_to(&[pt], false); - } - 57 => p.set_arc_ccw(r.u32()? != 2), - 58 => p.set_miter(f64::from(r.u32()?)), - 59 => p.begin_path(), - 60 => p.end_path(), - 61 => p.close_figure(), - 62 => p.paint_path(true, false), - 63 => p.paint_path(true, true), - 64 => p.paint_path(false, true), - 67 => p.clip_path(r.u32()?), - 68 => p.abort_path(), - 70 => rec_comment(p, &mut r)?, - 75 => rec_clip_region(p, &mut r)?, - 76 | 77 => rec_blt(p, kind, rec, &mut r)?, - 81 => rec_stretch_dibits(p, rec, &mut r)?, - 82 => { - let ih = r.u32()?; - p.create_at(ih, Obj::Font(font(&mut r)?)); - } - 83 | 84 => rec_text(p, kind, rec, &mut r)?, - 93 | 94 => p.create_at(r.u32()?, Obj::Brush(BrushObj::Pattern)), - 95 => rec_ext_create_pen(p, &mut r)?, - 114 => rec_alpha_blend(p, rec, &mut r)?, - k if IGNORED.contains(&k) => {} - _ => return None, - } - Some(()) -} diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs index a9b4cae9da..f6abbc6b83 100644 --- a/crates/metafile/src/import/pict.rs +++ b/crates/metafile/src/import/pict.rs @@ -24,7 +24,7 @@ use std::io::Cursor; use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; -use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; +use super::{BAD_IMAGE, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; use crate::dib::{self, Rgba}; use crate::{Imported, Kind}; @@ -600,7 +600,7 @@ impl Pict { let base = Affine::translate(-frame.origin().to_vec2()); let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height()); // A picture's coordinates map straight onto the document, as a WMF's do. - let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard); + let p = Player::new(Kind::Wmf, base, artboard); Self { p, frame, @@ -783,7 +783,7 @@ impl Pict { /// Fill `bp` (picture space) with `color`. fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) { bp.apply_affine(self.p.xf()); - self.p.dc.brush = BrushObj::Solid(color); + self.p.dc.brush = color; self.p.dc.fill_rule = rule; self.p.draw(bp, true, false); } diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs new file mode 100644 index 0000000000..d269fd27ca --- /dev/null +++ b/crates/metafile/src/import/picture.rs @@ -0,0 +1,523 @@ +//! EMF (with or without EMF+ records) and WMF files: `craft_metafile` plays the records into a +//! picture, and the picture's items become document objects here. +//! +//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit +//! and dashes from the pen). Strokes drawn one after another, each starting where the last one +//! ended, with the same pen and clip, join into one path. +//! - A path filled with a pattern or hatched brush is filled with the average color of the +//! brush's tile. +//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or +//! skewed with it. +//! - Text becomes point type in the font the file names, underlined or struck through as the font +//! is, and clipped to its rectangle when the file clips it. +//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around +//! the whole picture clips nothing and is left out. +//! +//! A WMF without a placeable header is read at 1440 units an inch, and one whose placeable box is +//! empty or inverted at the units an inch the header gives. An EMF without a usable frame is read +//! at its device's pixels a millimetre (96 pixels an inch when the header doesn't say). + +use std::collections::HashMap; +use std::sync::Arc; + +use craft_metafile::{Cap, ClipPath, HAlign, Item, Join, LineStyle, Seg, VAlign}; +use vectorcraft_color::Paint; +use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId, + NodeKind, StrokeLayer, TextObject, +}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes}; + +use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane}; +use crate::dib::Rgba; +use crate::wmf::PLACEABLE_KEY; +use crate::{Imported, Kind}; + +const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; +const ENDS_EARLY: &str = "the file ends early: what it held was imported"; + +/// Points a unit of a WMF without a placeable header (1440 units an inch). +const WMF_UNIT: f64 = 72.0 / 1440.0; +/// Points a millimetre. +const PT_PER_MM: f64 = 72.0 / 25.4; + +/// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an +/// EMF with a frame in points, and other files in their logical (WMF) or device (EMF) units. +fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let positive = |v: Option| v.filter(|v| *v > 0).map(f64::from); + match kind { + Kind::Wmf => { + if bytes.get(..4) != Some(&PLACEABLE_KEY.to_le_bytes()[..]) { + return (WMF_UNIT, WMF_UNIT); + } + if let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12)) + && r > l + && b > t + { + return (1.0, 1.0); + } + let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from); + (k, k) + } + Kind::Emf => { + // Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header + // has them, else over szlMillimeters (both sizes must be positive). + let device = positive(i32_at(72)).zip(positive(i32_at(76))); + let micro = (u32_at(4).is_some_and(|s| s >= 108)) + .then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0))) + .flatten(); + let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84)))); + let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh)); + let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t); + let ok = |v: f64| v.is_finite() && v > 0.0; + match px_mm { + Some(_) if frame => (1.0, 1.0), + Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y), + _ => (0.75, 0.75), + } + } + } +} + +/// What a stroke is drawn with, to tell whether two strokes join into one path. +#[derive(Clone, PartialEq)] +struct Pen { + color: [u8; 4], + width: f32, + line: LineStyle, + even_odd: bool, + chain: Vec, +} + +/// Strokes drawn one after another, not added yet: their pen, clips and path (document space). +struct Pending { + pen: Pen, + clips: Vec>, + path: BezPath, +} + +/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for +/// one that clips nothing in the picture. +type MadeClips = HashMap<*const ClipPath, (Arc, Option>)>; +/// The last clip region and the clip made for it. +type MadeRegion = (Vec<[f32; 4]>, Option>); + +struct Mapper { + /// Picture units → points. + xf: Affine, + /// How much lengths (stroke widths, dashes) grow from the picture to points. + k: f64, + frame: Rect, + doc: Document, + out: Drawn, + warnings: Vec, + next_clip: u32, + paths: MadeClips, + region: Option, + pending: Option, +} + +fn color(c: [u8; 4]) -> Paint { + rgb([c[0], c[1], c[2]]) +} + +/// The average color of a tile's pixels, weighted by their alpha, and their average alpha; None +/// for a clear tile. +fn average(rgba: &[u8]) -> Option<[u8; 4]> { + let pixels = rgba.as_chunks::<4>().0; + let mut sum = [0u64; 4]; + for p in pixels { + let a = u64::from(p[3]); + sum[0] += u64::from(p[0]) * a; + sum[1] += u64::from(p[1]) * a; + sum[2] += u64::from(p[2]) * a; + sum[3] += a; + } + let a = sum[3]; + let alpha = (a / pixels.len().max(1) as u64) as u8; + (a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)]) +} + +impl Mapper { + fn new(width: f64, height: f64, (kx, ky): (f64, f64)) -> Self { + let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 }; + let (w, h) = (side(width * kx), side(height * ky)); + let mut doc = Document::new(w, h); + doc.layers.clear(); + Self { + xf: Affine::scale_non_uniform(kx, ky), + // The mean of the two, as the reader scales stroke lengths. + k: (kx + ky) / 2.0, + frame: Rect::new(0.0, 0.0, w, h), + doc, + out: vec![], + warnings: vec![], + next_clip: 0, + paths: HashMap::new(), + region: None, + pending: None, + } + } + + fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + fn path(&self, segs: &[Seg]) -> BezPath { + let mut bp = craft_metafile::bez_path(segs); + bp.apply_affine(self.xf); + bp + } + + /// A clip of `path` (document space), or None when it clips nothing in the picture. + fn clip(&mut self, path: BezPath, rule: FillRule) -> Option> { + if around(&path, self.frame) { + return None; + } + self.next_clip += 1; + Some(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) })) + } + + /// The clips an item is drawn under, outermost first; None when it shows nowhere. + fn chain(&mut self, region: Option>, clips: &[Arc]) -> Option>> { + let mut chain = vec![]; + if let Some(rects) = region { + if rects.is_empty() { + return None; + } + let made = match &self.region { + Some((last, made)) if *last == rects => made.clone(), + _ => { + let mut bp = BezPath::new(); + for [x0, y0, x1, y1] in &rects { + bp.extend(shapes::rectangle(Rect::new(f64::from(*x0), f64::from(*y0), f64::from(*x1), f64::from(*y1))).to_bezpath()); + } + bp.apply_affine(self.xf); + if !sane(bp.bounding_box()) { + self.warn(FAR_AWAY); + return None; + } + let made = self.clip(bp, FillRule::NonZero); + self.region = Some((rects, made.clone())); + made + } + }; + chain.extend(made); + } + for c in clips { + let key = Arc::as_ptr(c); + let made = match self.paths.get(&key) { + Some((_, made)) => made.clone(), + None => { + let bp = self.path(&c.segs); + if !sane(bp.bounding_box()) { + self.warn(FAR_AWAY); + return None; + } + let made = self.clip(bp, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero }); + self.paths.insert(key, (c.clone(), made.clone())); + made + } + }; + chain.extend(made); + } + if chain.len() > MAX_NEST { + chain.truncate(MAX_NEST); + self.warn(&deep_clips()); + } + Some(chain) + } + + fn push(&mut self, clips: Vec>, mut node: Node) { + if self.out.len() >= MAX_NODES { + return; + } + if !node.visual_bounds().is_none_or(sane) { + return self.warn(FAR_AWAY); + } + node.id = self.doc.alloc_id(); + self.out.push((clips, node)); + } + + /// Add the strokes waiting to be joined. + fn flush(&mut self) { + if let Some(p) = self.pending.take() { + let node = self.path_node(p.path, None, Some((p.pen.color, p.pen.width, &p.pen.line)), p.pen.even_odd); + if let Some(n) = node { + self.push(p.clips, n); + } + } + } + + fn stroke_layer(&self, c: [u8; 4], width: f32, line: &LineStyle) -> StrokeLayer { + let w = f64::from(width) * self.k; + let mut st = StrokeLayer::new(color(c), if w > 0.0 && w.is_finite() { w } else { HAIRLINE }); + st.opacity = f32::from(c[3]) / 255.0; + st.cap = match line.cap { + Cap::Round => LineCap::Round, + Cap::Square => LineCap::Square, + Cap::Flat => LineCap::Butt, + }; + st.join = match line.join { + Join::Round => LineJoin::Round, + Join::Bevel => LineJoin::Bevel, + Join::Miter => LineJoin::Miter, + }; + let miter = f64::from(line.miter_limit); + if miter.is_finite() && miter >= 1.0 { + st.miter_limit = miter; + } + let dash = Dash { pattern: line.dash.iter().map(|d| f64::from(*d) * self.k).collect(), offset: 0.0, align_corners: false }; + st.dash = dash.is_dashed().then_some(dash); + st + } + + /// A path node painted with `fill` and `stroke`; None when neither shows. + fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option { + if bp.elements().is_empty() { + return None; + } + let mut items = vec![]; + if let Some(c) = fill.filter(|c| c[3] > 0) { + let mut f = FillLayer::new(color(c)); + f.opacity = f32::from(c[3]) / 255.0; + items.push(AppearanceItem::Fill(f)); + } + if let Some((c, w, line)) = stroke.filter(|s| s.0[3] > 0) { + items.push(AppearanceItem::Stroke(self.stroke_layer(c, w, line))); + } + if items.is_empty() { + return None; + } + let mut n = Node::path(NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() }); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; + } + Some(n) + } + + fn item(&mut self, item: Item) { + match item { + Item::Path { segs, fill, stroke, line, even_odd, region, clips } => { + let Some(chain) = self.chain(region, &clips) else { return self.flush() }; + let bp = self.path(&segs); + // An open stroke with nothing filled waits, to join the next one. + if let (None, Some((c, w))) = (fill, stroke) + && !segs.iter().any(|s| matches!(s, Seg::Close)) + { + let pen = Pen { color: c, width: w, line, even_odd, chain: chain.iter().map(|c| c.id).collect() }; + let start = bp.elements().first().and_then(|e| match e { + PathEl::MoveTo(p) => Some(*p), + _ => None, + }); + if let Some(p) = &mut self.pending + && p.pen == pen + && start.is_some() + && p.path.elements().last().and_then(|e| e.end_point()) == start + { + p.path.extend(bp.elements().iter().skip(1).copied()); + return; + } + self.flush(); + self.pending = Some(Pending { pen, clips: chain, path: bp }); + return; + } + self.flush(); + let stroke = stroke.map(|(c, w)| (c, w, &line)); + if let Some(n) = self.path_node(bp, fill, stroke, even_odd) { + self.push(chain, n); + } + } + Item::Pattern { segs, even_odd, tile, region, clips } => { + self.flush(); + let Some(chain) = self.chain(region, &clips) else { return }; + let Some(c) = average(&tile.rgba) else { return }; + self.warn(PATTERNS); + let bp = self.path(&segs); + if let Some(n) = self.path_node(bp, Some(c), None, even_odd) { + self.push(chain, n); + } + } + Item::Bitmap { transform, width, height, rgba, region, clips, .. } => { + self.flush(); + let Some(chain) = self.chain(region, &clips) else { return }; + self.image(Rgba { width, height, pixels: rgba }, Affine::new(transform), chain); + } + Item::Text(t) => { + self.flush(); + let Some(mut chain) = self.chain(t.region.clone(), &t.clips) else { return }; + // The text's own clip rectangle, inside the others. + if let Some([x0, y0, x1, y1]) = t.clip { + let mut bp = shapes::rectangle(Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)).abs()).to_bezpath(); + bp.apply_affine(self.xf); + if !sane(bp.bounding_box()) { + return self.warn(FAR_AWAY); + } + if let Some(own) = self.clip(bp, FillRule::NonZero) { + // Past the stack, the text's own clip takes the innermost place kept. + if chain.len() >= MAX_NEST { + chain.truncate(MAX_NEST.saturating_sub(1)); + self.warn(&deep_clips()); + } + chain.push(own); + } + } + self.text(&t, chain); + } + } + } + + /// An image whose unit square `unit` places in the picture. + fn image(&mut self, img: Rgba, unit: Affine, chain: Vec>) { + if img.width == 0 || img.height == 0 { + return; + } + let xf = self.xf * unit * Affine::scale_non_uniform(1.0 / f64::from(img.width), 1.0 / f64::from(img.height)); + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + return; + } + let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) }; + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + self.doc.images.entry(key.clone()).or_insert(blob); + let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; + self.push(chain, Node::new(NodeId(0), NodeKind::Image(Box::new(im)))); + } + + fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { + let s: String = t.text.chars().filter(|c| *c != '\0').collect(); + if s.trim().is_empty() || t.color[3] == 0 { + return; + } + // Text space → document without the move: its vertical scale gives the type size, and what + // is left of it (a turn, a stretch across) goes on the text object. + let [a, b, c, d, ..] = t.transform; + let linear = self.xf * Affine::new([a, b, c, d, 0.0, 0.0]); + let [_, _, c, d, ..] = linear.as_coeffs(); + let k = c.hypot(d); + let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY }; + let f = &t.font; + let h = f64::from(f.height); + // A negative height is the em; a positive one the cell (the em and the internal leading). + let em = if h < 0.0 { -h } else { h * 0.85 }; + let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; + let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; + if !f.family.trim().is_empty() { + style.font_family = f.family.trim().to_string(); + } + style.font_style = match (f.weight >= 600, f.italic) { + (true, true) => "Bold Italic", + (true, false) => "Bold", + (false, true) => "Italic", + (false, false) => "Regular", + } + .into(); + style.underline = f.underline; + style.strikethrough = f.strike; + // Where the baseline is below the reference point. + let drop = match t.v_align { + VAlign::Baseline => 0.0, + VAlign::Bottom => -0.2 * size, + VAlign::Top => 0.8 * size, + }; + let origin = self.xf * Point::new(t.transform[4], t.transform[5]); + let mut text = TextObject::point(Point::ZERO, &s, style); + text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop)); + text.para.justify = match t.h_align { + HAlign::Center => Justify::Center, + HAlign::Right => Justify::Right, + HAlign::Left => Justify::Left, + }; + text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds); + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); + n.opacity = f32::from(t.color[3]) / 255.0; + self.push(chain, n); + } + + /// The document: what was drawn on one layer, clipped art in clipping groups. + fn finish(mut self, kind: Kind, skipped: u32) -> Imported { + self.flush(); + if skipped > 0 { + let n = skipped; + self.warnings.push(format!( + "{n} record{} of kinds VectorCraft doesn't read {} skipped", + if n == 1 { "" } else { "s" }, + if n == 1 { "was" } else { "were" } + )); + } + let out = std::mem::take(&mut self.out); + let children = nest(&mut self.doc, out); + let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + if let Some(c) = layer.children_mut() { + *c = children; + } + self.doc.layers = vec![Arc::new(layer)]; + Imported { document: self.doc, kind, warnings: self.warnings } + } +} + +/// Does the file stop before its end-of-file record? +fn ends_early(bytes: &[u8], kind: Kind) -> bool { + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let mut at = match kind { + Kind::Emf => 0, + Kind::Wmf => { + let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 }; + let Some(words) = u16_at(start + 2) else { return true }; + start + usize::from(words) * 2 + } + }; + loop { + let size = match kind { + Kind::Emf => { + let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true }; + if kind == 14 { + return false; + } + // Records are a multiple of 4 bytes long; reading stops at one that isn't. + if !size.is_multiple_of(4) { + return true; + } + size as usize + } + Kind::Wmf => { + let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true }; + if function == 0 { + return false; + } + (words as usize).saturating_mul(2) + } + }; + if size < 6 { + return true; + } + at = at.saturating_add(size); + } +} + +/// Read an EMF or WMF file. +pub(crate) fn import(bytes: &[u8]) -> Result { + let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?; + let pic = craft_metafile::parse(bytes).map_err(|e| match e { + craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(), + craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()), + craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()), + })?; + let k = unit(bytes, kind); + let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k); + if ends_early(bytes, kind) { + m.warn(ENDS_EARLY); + } + for item in pic.items { + m.item(item); + } + Ok(m.finish(kind, pic.skipped_records)) +} diff --git a/crates/metafile/src/import/wmf.rs b/crates/metafile/src/import/wmf.rs deleted file mode 100644 index 7a682e59a9..0000000000 --- a/crates/metafile/src/import/wmf.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! WMF records (MS-WMF) played on a [`Player`]. A placeable header gives the picture's box in -//! logical units and the units an inch; without one, the first window origin and extent are the -//! box, at 1440 units an inch. - -use vectorcraft_geom::{Affine, Point, Rect, shapes}; - -use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player}; -use crate::bytes::Reader; -use crate::dib::{self, Alpha}; -use crate::wmf::PLACEABLE_KEY; -use crate::{Imported, Kind}; - -/// Units an inch when the file doesn't say (twips). -const DEFAULT_INCH: f64 = 1440.0; -/// Records that change nothing VectorCraft keeps (background, raster and mapping details, palettes, -/// escapes). -const IGNORED: &[u16] = &[ - 0x0102, 0x0103, 0x0104, 0x0105, 0x0107, 0x0108, 0x0201, 0x020A, 0x020B, 0x020C, 0x020D, 0x020E, 0x020F, 0x0211, 0x0410, 0x0412, 0x0231, 0x0234, - 0x0035, 0x0037, 0x0139, 0x0436, 0x0626, -]; - -fn point(r: &mut Reader) -> Option { - Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?))) -} - -/// A point stored y first. -fn point_yx(r: &mut Reader) -> Option { - let y = f64::from(r.i16()?); - Some(Point::new(f64::from(r.i16()?), y)) -} - -/// A rectangle stored bottom, right, top, left. -fn rect_brtl(r: &mut Reader) -> Option { - let (b, rt, t, l) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - Some(Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b))) -} - -fn color(r: &mut Reader) -> Option<[u8; 3]> { - let [red, g, b, _] = r.u32()?.to_le_bytes(); - Some([red, g, b]) -} - -fn points(r: &mut Reader, n: usize) -> Option> { - if r.rest().len() < n * 4 { - return None; - } - (0..n).map(|_| point(r)).collect() -} - -/// ANSI text (read as Latin-1). -fn ansi(b: &[u8]) -> String { - b.iter().map(|c| char::from(*c)).collect() -} - -/// The records' start, and the box and units an inch of a placeable header. -fn header(bytes: &[u8]) -> Option<(usize, Option<(Rect, f64)>)> { - let mut r = Reader::new(bytes); - let placeable = if r.u32()? == PLACEABLE_KEY { - r.skip(2)?; - let (l, t, rt, b) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - let inch = r.u16()?; - let inch = if inch == 0 { DEFAULT_INCH } else { f64::from(inch) }; - Some((Rect::new(f64::from(l), f64::from(t), f64::from(rt), f64::from(b)).abs(), inch)) - } else { - None - }; - let start = if placeable.is_some() { 22 } else { 0 }; - let mut h = Reader::new(bytes.get(start..)?); - h.skip(2)?; - let words = usize::from(h.u16()?); - if words < 9 { - return None; - } - Some((start + words * 2, placeable)) -} - -/// The first window origin and extent, as the picture's box when there is no placeable header. -fn window(bytes: &[u8], mut at: usize) -> Option { - let (mut org, mut ext) = (None, None); - while let Some(head) = bytes.get(at..at + 6) { - let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; - let function = u16::from_le_bytes([head[4], head[5]]); - if words < 3 || function == 0 { - break; - } - let mut r = Reader::new(bytes.get(at + 6..).unwrap_or_default()); - match function { - 0x020B if org.is_none() => org = point_yx(&mut r), - 0x020C if ext.is_none() => ext = point_yx(&mut r), - _ => {} - } - if org.is_some() && ext.is_some() { - break; - } - at = at.saturating_add(words.saturating_mul(2)); - } - let o = org.unwrap_or(Point::ZERO); - let e = ext?; - Some(Rect::new(o.x, o.y, o.x + e.x, o.y + e.y).abs()) -} - -/// Logical → document for a placeable file whose window (`org`, `ext`) is mapped onto its box `b`; -/// a negative extent flips that axis, as in GDI. -fn window_map(b: Rect, k: f64, org: Point, ext: Point) -> Affine { - let ratio = |box_len: f64, e: f64| if e.abs() > 1e-12 { box_len / e } else { 1.0 }; - Affine::scale_non_uniform(k * ratio(b.width(), ext.x), k * ratio(b.height(), ext.y)) * Affine::translate(-org.to_vec2()) -} - -pub(super) fn play(bytes: &[u8]) -> Result { - let (start, placeable) = header(bytes).ok_or("the WMF header is damaged")?; - let (frame, inch) = match placeable { - Some((b, inch)) if b.width() > 0.0 && b.height() > 0.0 => (Some(b), inch), - _ => (window(bytes, start).filter(|w| w.width() > 0.0 && w.height() > 0.0), DEFAULT_INCH), - }; - let k = 72.0 / inch; - let origin = frame.map_or(Point::ZERO, |f| f.origin()); - let artboard = frame.map_or(Rect::new(0.0, 0.0, 1.0, 1.0), |f| Rect::new(0.0, 0.0, f.width() * k, f.height() * k)); - let mut p = Player::new(Kind::Wmf, Affine::scale(k) * Affine::translate(-origin.to_vec2()), 25.4 / inch, artboard); - // With a placeable header, the window records map the window onto the box. - let placed = placeable.map(|(b, _)| b).filter(|b| b.width() > 0.0 && b.height() > 0.0); - let mut win = (placed.map_or(Point::ZERO, |b| b.origin()), placed.map_or(Point::ZERO, |b| Point::new(b.width(), b.height()))); - let mut at = start; - let mut ended = false; - while let Some(head) = bytes.get(at..at + 6) { - let words = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize; - let function = u16::from_le_bytes([head[4], head[5]]); - if function == 0 { - ended = true; - break; - } - let Some(rec) = words.checked_mul(2).and_then(|n| bytes.get(at..at.checked_add(n)?)).filter(|_| words >= 3) else { break }; - if !matches!(function, 0x0213 | 0x0214) { - p.flush(); - } - if let (Some(b), 0x020B | 0x020C) = (placed, function) { - if let Some(v) = point_yx(&mut Reader::new(rec.get(6..).unwrap_or_default())) { - if function == 0x020B { - win.0 = v; - } else { - win.1 = v; - } - p.dev_to_doc = window_map(b, k, win.0, win.1); - } - } else if record(&mut p, function, rec.get(6..).unwrap_or_default()).is_none() { - p.skip(); - } - at += rec.len(); - } - if !ended { - p.warn("the file ends early: what it held was imported"); - } - let mut out = p.finish(); - // No box given: the art's bounds. - if frame.is_none() - && let Some(b) = out.document.layers.first().and_then(|l| vectorcraft_doc::live::nodes_bounds(l.children().map_or(&[][..], |c| c.as_slice()))) - && let Some(a) = out.document.artboards.first_mut() - { - a.rect = Rect::from_origin_size(b.origin(), (b.width().max(1.0), b.height().max(1.0))); - } - Ok(out) -} - -/// An image record's source rectangle (from the bottom for a bottom-up DIB) and destination. -fn blit(p: &mut Player, rop: u32, src: (i16, i16, i16, i16), dest: (i16, i16, i16, i16), packed: Option<&[u8]>) { - let (xd, yd, wd, hd) = (f64::from(dest.0), f64::from(dest.1), f64::from(dest.2), f64::from(dest.3)); - let d = Rect::new(xd, yd, xd + wd, yd + hd); - let Some(packed) = packed else { return p.pattern_blit(d, rop) }; - let parts = dib::split(packed); - let img = parts.ok_or_else(|| "damaged".to_string()).and_then(|(bmi, bits)| dib::decode(bmi, bits, Alpha::Ignore, &mut p.pixels_left)); - let bottom_up = parts.and_then(|(bmi, _)| bmi.get(8..12)).is_some_and(|h| i32::from_le_bytes([h[0], h[1], h[2], h[3]]) > 0); - let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height)); - let (xs, ys, ws, hs) = (f64::from(src.0), f64::from(src.1), f64::from(src.2), f64::from(src.3)); - let top = if bottom_up { ih - ys - hs } else { ys }; - p.image(img, Rect::new(xs, top, xs + ws, top + hs), d, rop, 1.0); -} - -/// PolyPolygon (0x0538). -fn rec_poly_polygon(p: &mut Player, r: &mut Reader) -> Option<()> { - let n = usize::from(r.u16()?); - if r.rest().len() < n * 2 { - return None; - } - let counts: Vec = (0..n).map(|_| r.u16().map(usize::from)).collect::>()?; - let mut polys = Vec::with_capacity(n); - for c in counts { - polys.push(points(r, c)?); - } - p.poly_poly(&polys, true); - Some(()) -} - -/// Arc (0x0817), Pie (0x081A) and Chord (0x0830). -fn rec_arc(p: &mut Player, function: u16, r: &mut Reader) -> Option<()> { - let (end, start) = (point_yx(r)?, point_yx(r)?); - let b = rect_brtl(r)?; - let kind = match function { - 0x0817 => ArcKind::Open, - 0x081A => ArcKind::Pie, - _ => ArcKind::Chord, - }; - p.arc(b, start, end, kind); - Some(()) -} - -/// CreateFontIndirect (0x02FB). -fn rec_create_font(p: &mut Player, r: &mut Reader) -> Option<()> { - let height = f64::from(r.i16()?); - r.skip(2)?; - let escapement = f64::from(r.i16()?); - r.skip(2)?; - let weight = i32::from(r.i16()?); - let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0); - r.skip(7)?; - let face: Vec = r.rest().iter().take(32).take_while(|b| **b != 0).copied().collect(); - p.create(Obj::Font(FontObj { height, escapement, weight, italic, face: ansi(&face) })); - Some(()) -} - -/// TextOut (0x0521). -fn rec_text_out(p: &mut Player, r: &mut Reader) -> Option<()> { - let n = usize::try_from(r.i16()?).ok()?; - let s = ansi(r.bytes(n)?); - r.skip(n % 2)?; - let at = point_yx(r)?; - p.text(at, &s); - Some(()) -} - -/// ExtTextOut (0x0A32). -fn rec_ext_text_out(p: &mut Player, r: &mut Reader) -> Option<()> { - let at = point_yx(r)?; - let n = usize::try_from(r.i16()?).ok()?; - let opts = r.u16()?; - // ETO_OPAQUE or ETO_CLIPPED: a rectangle comes first. - if opts & 0x6 != 0 { - r.skip(8)?; - } - let s = ansi(r.bytes(n)?); - p.text(at, &s); - Some(()) -} - -/// StretchDIB (0x0F43). -fn rec_stretch_dib(p: &mut Player, r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - r.skip(2)?; - let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), Some(r.rest())); - Some(()) -} - -/// StretchBlt (0x0B41). -fn rec_stretch_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - let (hs, ws, ys, xs) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - // Without a bitmap, a reserved word comes before the destination. - let with_bitmap = body.len() > 22; - if !with_bitmap { - r.skip(2)?; - } - let (hd, wd, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, ws, hs), (xd, yd, wd, hd), with_bitmap.then(|| r.rest())); - Some(()) -} - -/// BitBlt (0x0940). -fn rec_bit_blt(p: &mut Player, body: &[u8], r: &mut Reader) -> Option<()> { - let rop = r.u32()?; - let (ys, xs) = (r.i16()?, r.i16()?); - let with_bitmap = body.len() > 20; - if !with_bitmap { - r.skip(2)?; - } - let (h, w, yd, xd) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?); - blit(p, rop, (xs, ys, w, h), (xd, yd, w, h), with_bitmap.then(|| r.rest())); - Some(()) -} - -/// Play one record (`r`: its parameters). `None`: unknown or damaged. -fn record(p: &mut Player, function: u16, body: &[u8]) -> Option<()> { - let mut r = Reader::new(body); - match function { - 0x001E => p.save(), - 0x0127 => p.restore(i32::from(r.i16()?)), - 0x0106 => p.set_fill_mode(r.u16()? == 1), - 0x0209 => p.set_text_color(color(&mut r)?), - 0x012E => p.set_text_align(u32::from(r.u16()?)), - 0x0214 => p.move_to(point_yx(&mut r)?), - 0x0213 => { - let pt = point_yx(&mut r)?; - p.poly_to(&[pt], false); - } - 0x0324 | 0x0325 => { - let n = usize::try_from(r.i16()?).ok()?; - let pts = points(&mut r, n)?; - p.poly(&pts, function == 0x0324, false); - } - 0x0538 => rec_poly_polygon(p, &mut r)?, - 0x041B => p.figure(shapes::rectangle(rect_brtl(&mut r)?.abs()).to_bezpath(), true), - 0x0418 => p.figure(shapes::ellipse(rect_brtl(&mut r)?.abs()).to_bezpath(), true), - 0x061C => { - let (h, w) = (f64::from(r.i16()?), f64::from(r.i16()?)); - p.figure(super::round_rect(rect_brtl(&mut r)?, w, h), true); - } - 0x0817 | 0x081A | 0x0830 => rec_arc(p, function, &mut r)?, - 0x0416 => p.clip_rect(rect_brtl(&mut r)?), - 0x0415 => p.exclude_clip(), - 0x012D => p.select(u32::from(r.u16()?)), - 0x01F0 => p.delete(u32::from(r.u16()?)), - 0x02FA => { - let style = u32::from(r.u16()?); - let width = f64::from(r.i16()?); - r.skip(2)?; - p.create(Obj::Pen(PenObj { style, width, color: color(&mut r)?, entries: vec![] })); - } - 0x02FC => { - let style = u32::from(r.u16()?); - p.create(Obj::Brush(BrushObj::from_log(style, color(&mut r)?))); - } - 0x02FB => rec_create_font(p, &mut r)?, - 0x00F7 | 0x06FF => p.create(Obj::Other), - 0x01F9 | 0x0142 => p.create(Obj::Brush(BrushObj::Pattern)), - 0x0521 => rec_text_out(p, &mut r)?, - 0x0A32 => rec_ext_text_out(p, &mut r)?, - 0x0F43 => rec_stretch_dib(p, &mut r)?, - 0x0B41 => rec_stretch_blt(p, body, &mut r)?, - 0x0940 => rec_bit_blt(p, body, &mut r)?, - 0x061D => { - let rop = r.u32()?; - let (h, w, y, x) = (f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?), f64::from(r.i16()?)); - p.pattern_blit(Rect::new(x, y, x + w, y + h), rop); - } - f if IGNORED.contains(&f) => {} - _ => return None, - } - Some(()) -} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 0e699236d7..86d268cee1 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -13,13 +13,14 @@ //! lines or gradients, so clipped art is written whole, images over white, dashes as separate //! lines and gradients and patterns as one colour (each loss comes back as a warning). //! -//! [`import`] reads either format back into a document of one artboard (the picture's frame) and -//! one layer: paths with fills and strokes, clipping, images and text. Records it doesn't read are -//! skipped, with one warning. [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) -//! into the same kind of document. +//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) +//! into a document of one artboard (the picture's frame) and one layer: paths with fills and +//! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning. +//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of +//! document. //! -//! - `bytes`: little-endian writing and bounds-checked reading. -//! - `dib`: device-independent bitmaps, both ways. +//! - `bytes`: little-endian writing. +//! - `dib`: device-independent bitmaps for the writers. //! - `scene`: the document walk both writers share. //! - `emf`, `wmf`: the writers. //! - `import`: the readers. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 1e0ec5671b..689037d277 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -151,13 +151,14 @@ fn dashes_gradients_and_images_round_trip_through_emf() { // ---------- hand-built records ---------- /// An EMF of `records` (type, body) with a frame of `w` × `h` hundredths of a millimetre on a -/// device of 100 pixels a millimetre. +/// device of 100 pixels a millimetre. Bodies are padded to a multiple of 4 bytes. fn hand_emf(w: i32, h: i32, records: &[(u32, Vec)]) -> Vec { let mut o = Out::default(); let rec = |o: &mut Out, kind: u32, body: &[u8]| { o.u32(kind); - o.u32(8 + body.len() as u32); + o.u32(8 + body.len().next_multiple_of(4) as u32); o.bytes(body); + o.pad(4); }; let mut head = Out::default(); head.bytes(&[0; 16]); @@ -336,6 +337,18 @@ fn wmf_window_is_mapped_onto_the_placeable_box() { } } +#[test] +fn wmf_without_a_placeable_header_is_read_at_1440_units_an_inch() { + // The window is 2880 × 1440 units: 2 × 1 inches. The rectangle is its left half. + let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 2880])), (0x041B, le16(&[1440, 1440, 0, 0]))]; + let plain = hand_wmf(2880, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", p[0].geometric_bounds()); +} + #[test] fn damaged_files_fail_or_import_partly() { let good = emf(&sample()).bytes; @@ -371,19 +384,29 @@ fn png_stretch_dibits(png: &[u8]) -> Vec { } #[test] -fn embedded_bitmaps_share_one_pixel_budget() { - // #3600: each bitmap was bounded but not their total, so many records of the largest one a record - // may hold cost minutes. Those past the file's budget are left out before they're decoded. +fn oversized_embedded_bitmaps_are_left_out_before_decoding() { + // #3600: many records of the largest bitmap a record may hold cost minutes. Each of these claims + // more pixels than one image may have, so the reader leaves it out from its header. (The reader's + // budget for all the images of one file is tested where the reader is.) let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 5]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); - assert!(back.warnings.iter().any(|w| w == "images past the most pixels one file may hold were left out"), "{:?}", back.warnings); + assert!(!all(&back.document).iter().any(|n| matches!(n.kind, NodeKind::Image(_)))); } #[test] fn clips_nest_only_so_deep() { - // Each clip inside the last one used to nest a clipping group one level deeper, past the stack. - let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000]; - records.push((43, le(&[100, 100, 200, 200]))); + // Each clip inside the last one nests a clipping group one level deeper; past the stack they + // are left out with a warning. + let mut records = vec![]; + // As many as the reader keeps: one more than the stack. + for i in 0..32 { + // BEGINPATH, a rectangle a little smaller each time, ENDPATH, SELECTCLIPPATH (RGN_AND). + records.push((59, vec![])); + records.push((43, le(&[100 + i, 100 + i, 2000 - i, 2000 - i]))); + records.push((60, vec![])); + records.push((67, le(&[1]))); + } + records.push((43, le(&[500, 500, 600, 600]))); let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let mut depth = 0; let mut n = back.document.layers[0].children().unwrap()[0].clone(); @@ -393,4 +416,267 @@ fn clips_nest_only_so_deep() { } assert_eq!(depth, vectorcraft_doc::clipnest::MAX_NEST); assert!(back.warnings.iter().any(|w| w.contains("clips nested more than")), "{:?}", back.warnings); + // A hostile count of clip records: each one used to nest a clipping group one level deeper, + // past the stack. They make one clip. + let mut records = vec![(30, le(&[0, 0, 1500, 1500])); 200_000]; + records.push((43, le(&[100, 100, 200, 200]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })), "one level"); + assert_eq!(paths(&back.document).len(), 1); +} + +/// An EMR_COMMENT holding EMF+ `records` (type, flags, data). +fn emf_plus(records: &[(u16, u16, Vec)]) -> Vec { + let mut plus = Out::default(); + for (kind, flags, data) in records { + plus.u16(*kind); + plus.u16(*flags); + plus.u32(12 + data.len() as u32); + plus.u32(data.len() as u32); + plus.bytes(data); + } + let mut body = Out::default(); + body.u32(4 + plus.len() as u32); + // "EMF+" + body.u32(0x2B46_4D45); + body.bytes(&plus.0); + body.0 +} + +fn le_f32(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +#[test] +fn emf_plus_only_pictures_import_their_drawing() { + // An EMF+ only file: its EMF records draw nothing, so it was imported empty with a warning. + // EmfPlusHeader (version, flags, 96 dpi), FillRects with an inline green color (flag S) and one + // rectangle of 10 × 5 mm at (10, 10) mm in device pixels, EmfPlusEndOfFile. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let rects = [le(&[0xFF00_FF00u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat(); + let comment = emf_plus(&[(0x4001, 0, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]); + let back = import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0])); + let mm = 72.0 / 25.4; + let b = p[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{b:?}"); +} + +#[test] +fn hatched_brushes_fill_with_their_average_color() { + // CREATEBRUSHINDIRECT: a hatched (style 2) blue brush, selected; a null pen; a rectangle. The + // hatch is drawn over the white background, so the average is a light blue. + let records = vec![(39, le(&[1, 2, 0x00ff_0000, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let [r, g, b] = fill_rgb(&p[0]).unwrap(); + assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]); + // With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill. + let mut records = records; + records.insert(0, (18, le(&[1]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let p = paths(&back.document); + assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255])); + let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; + assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity); +} + +#[test] +fn text_keeps_a_stretch_across() { + // A world transform twice as wide as it is high, a 10 mm font and "Hi". + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, -1000, 0, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let world = [2.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + let records = vec![(35, world), (82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + let mm = 72.0 / 25.4; + assert!((t.runs[0].style.size - 10.0 * mm).abs() < 0.01, "{}", t.runs[0].style.size); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf); +} + +#[test] +fn a_clip_whose_box_holds_the_picture_still_clips() { + // A diamond around the middle of the picture, whose box holds the whole frame but which cuts + // off its corners: BEGINPATH, POLYGON, ENDPATH, SELECTCLIPPATH (RGN_COPY), then a rectangle. + let mut diamond = le(&[0, 0, 0, 0, 4]); + diamond.extend(le(&[2500, -500, 5500, 1500, 2500, 3500, -500, 1500])); + // A bow tie through the four corners of a box around the picture. + let mut bow_tie = le(&[0, 0, 0, 0, 4]); + bow_tie.extend(le(&[-500, -500, 5500, 3500, 5500, -500, -500, 3500])); + for clip in [diamond, bow_tie] { + let records = vec![(59, vec![]), (3, clip), (60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind); + } +} + +#[test] +fn dual_emf_plus_files_draw_their_emf_plus_records() { + // A dual file (header flag 1): a translucent red EMF+ fill, and a plain rectangle that is only + // the fallback for readers of plain records. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let rects = [le(&[0x80FF_0000u32 as i32, 1]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat(); + let comment = emf_plus(&[(0x4001, 1, header), (0x400A, 0x8000, rects), (0x4002, 0, vec![])]); + let back = import(&hand_emf(5000, 3000, &[(70, comment), (43, le(&[3000, 1000, 4000, 2000]))])).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert_eq!(fill_rgb(&p[0]), Some([255, 0, 0])); + let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; + assert!((f.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", f.opacity); +} + +#[test] +fn pattern_brushes_fill_with_their_average_color() { + // CREATEDIBPATTERNBRUSHPT: a 2 × 2 tile of 24-bit pixels, two red and two blue (bottom-up rows + // padded to 4 bytes); selected, a null pen, a rectangle. + let mut brush = le(&[1, 0, 32, 40, 72, 16]); + brush.extend(le(&[40, 2, 2, 0x0018_0001, 0, 0, 0, 0, 0, 0])); + brush.extend([0, 0, 255, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0]); + let records = vec![(94, brush), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32])), (43, le(&[1000, 1000, 2000, 1500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["hatched and pattern brushes are filled with their average color".to_string()]); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let [r, g, b] = fill_rgb(&p[0]).unwrap(); + assert!((126..=128).contains(&r) && g == 0 && (126..=128).contains(&b), "{:?}", [r, g, b]); +} + +#[test] +fn clipped_text_is_clipped_to_its_rectangle() { + // EXTTEXTOUTW with ETO_CLIPPED and a rectangle of 9–12 × 10–16 mm, in an underlined and struck + // through font. + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 4, 900, 1000, 1200, 1600, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, -1000, 0, 0, 0, 400]); + font.extend([0, 1, 1, 0, 0, 0, 0, 0]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let mut records = vec![(82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + let mm = 72.0 / 25.4; + let own = Rect::new(9.0 * mm, 10.0 * mm, 12.0 * mm, 16.0 * mm); + assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01)); + let NodeKind::Text(t) = &children[1].kind else { panic!("text") }; + assert!(t.runs[0].style.underline && t.runs[0].style.strikethrough); + // Under clip paths nested as deep as the stack, the text's own clip is still the innermost. + for i in 0..32 { + records.insert(0, (67, le(&[1]))); + records.insert(0, (60, vec![])); + records.insert(0, (43, le(&[100 + i, 100 + i, 4000 - i, 2500 - i]))); + records.insert(0, (59, vec![])); + } + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let mut n = back.document.layers[0].children().unwrap()[0].clone(); + while let NodeKind::Group { children, clip: true } = &n.kind + && matches!(children.last().map(|c| &c.kind), Some(NodeKind::Group { .. })) + { + n = children.last().unwrap().clone(); + } + let NodeKind::Group { children, clip: true } = &n.kind else { panic!("a clipping group: {:?}", n.kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), own, 0.01), "{:?}", children[0].geometric_bounds()); + assert!(matches!(children[1].kind, NodeKind::Text(_))); +} + +#[test] +fn excluded_clip_rectangles_clip() { + // EXCLUDECLIPRECT cuts the top-left of the picture out of the clip; the rectangle crosses it. + // The clip it cuts from is the picture's bounds (5000 × 3000 device pixels). + let records = vec![(29, le(&[0, 0, 1500, 1500])), (43, le(&[1000, 1000, 2000, 1500]))]; + let mut bytes = hand_emf(5000, 3000, &records); + for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() { + bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + let back = import(&bytes).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + assert!(matches!(layer[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", layer[0].kind); +} + +#[test] +fn shapes_under_the_same_clip_share_one_clipping_group() { + let records = vec![(30, le(&[0, 0, 1500, 1500])), (43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let layer = back.document.layers[0].children().unwrap(); + assert_eq!(layer.len(), 1); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + assert_eq!(children.len(), 3, "the clip and both rectangles"); +} + +#[test] +fn a_record_whose_size_is_not_a_multiple_of_4_ends_the_file() { + let records = vec![(43, le(&[100, 100, 200, 200])), (43, le(&[300, 300, 400, 400])), (43, le(&[500, 500, 600, 600]))]; + let mut bytes = hand_emf(5000, 3000, &records); + // The second rectangle's size, after the header and the first rectangle. + let header = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let first = u32::from_le_bytes(bytes[header + 4..header + 8].try_into().unwrap()) as usize; + let at = header + first + 4; + let size = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); + bytes[at..at + 4].copy_from_slice(&(size + 2).to_le_bytes()); + let back = import(&bytes).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!(back.warnings, vec!["the file ends early: what it held was imported".to_string()]); +} + +#[test] +fn wmf_with_an_inverted_placeable_box_is_read_at_its_units_an_inch() { + // The box runs from right to left, so it gives no size: the window (1440 units square, one inch + // at the header's 1440 units an inch) does. The rectangle is its top-left quarter. + let records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[720, 720, 0, 0]))]; + let mut bytes = hand_wmf(1440, 1440, &records); + bytes[6..8].copy_from_slice(&1440i16.to_le_bytes()); + bytes[10..12].copy_from_slice(&0i16.to_le_bytes()); + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 36.0, 36.0), 1e-6), "{:?}", p[0].geometric_bounds()); +} + +#[test] +fn emf_without_a_frame_is_read_at_its_device_resolution() { + // An empty frame, and bounds of 5000 × 3000 device pixels at 100 pixels a millimetre. + let mut bytes = hand_emf(0, 0, &[(43, le(&[1000, 1000, 2000, 1500]))]); + for (i, v) in [0i32, 0, 5000, 3000].iter().enumerate() { + bytes[8 + i * 4..12 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + let back = import(&bytes).unwrap(); + let mm = 72.0 / 25.4; + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 30.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 10.0 * mm, 20.0 * mm, 15.0 * mm), 0.01), "{:?}", p[0].geometric_bounds()); + // A device 50 mm high: 200 pixels a millimetre down, so everything is half as tall. + bytes[84..88].copy_from_slice(&50i32.to_le_bytes()); + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 50.0 * mm, 15.0 * mm), 0.01), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds()); } diff --git a/docs/mcp.md b/docs/mcp.md index eb60457600..17028d3952 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7700,10 +7700,11 @@ and is missing from the picture" once for all such images. `document.open` and `file.place` read `.emf` and `.wmf` (placeable or not) into one artboard, the picture's frame, and one layer: paths with their fills and strokes (pens become strokes with caps, joins and dashes), clipping groups, -images and point type in the font the file names. Records VectorCraft doesn't read (EMF+ drawing among them) are -skipped with one warning. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard -for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's -clipboard service offers it (the Windows desktop service doesn't read metafiles yet). +images and point type in the font the file names. An EMF that draws with EMF+ records is read from them. Hatched and +pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. +`clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app +pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it +(the Windows desktop service doesn't read metafiles yet). ```json {"name":"export","arguments":{"path":"/tmp/logo.emf"}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ad7e9f4eab..7359d135d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1749,6 +1749,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). From c410e3fbb55bde577ab4336309c4b5396f6dd984 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:25:25 -0800 Subject: [PATCH 09/33] Brushes: the renderer's brush cull room counts only painted brushed strokes The doc comment on pad() now says a brushed stroke needs a paint to get room, as vectorcraft_brush::reach does. --- crates/render/src/brush_fx.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index fe7eb0f804..5844a2ef7f 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -155,7 +155,7 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO /// How far brush art can paint past `n`'s brushed strokes, or past the brushed strokes in the art /// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it -/// has a visible brushed stroke and of the objects in that art that have one +/// has a visible brushed stroke with a paint and of the objects in that art that have one /// ([`SymbolBoxes::brush_width`]) or the pieces live-effect plug-ins paint for them /// ([`crate::fx::painted_brush_width`]), and 0 when neither has one. The room for `n`'s own strokes /// is [`vectorcraft_brush::reach`], which the exports leave too. From f8e70c141599449d6cbab41ea41bbb3bffc85e02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:35:25 -0800 Subject: [PATCH 10/33] Metafile import: translucent strokes stay apart, and each pattern tile is averaged once Strokes drawn one after another with the same pen join into one path only when the pen is opaque. A translucent stroke keeps its own opacity, so where two of them overlap both show. Items filled with the same pattern brush share its tile, and the tile's average color is now worked out once per tile instead of once per item. --- crates/metafile/src/import/picture.rs | 18 ++++++++++++++---- crates/metafile/src/tests/import.rs | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index d269fd27ca..8373253ae4 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -2,8 +2,8 @@ //! picture, and the picture's items become document objects here. //! //! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit -//! and dashes from the pen). Strokes drawn one after another, each starting where the last one -//! ended, with the same pen and clip, join into one path. +//! and dashes from the pen). Opaque strokes drawn one after another, each starting where the +//! last one ended, with the same pen and clip, join into one path. //! - A path filled with a pattern or hatched brush is filled with the average color of the //! brush's tile. //! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or @@ -18,7 +18,7 @@ //! at its device's pixels a millimetre (96 pixels an inch when the header doesn't say). use std::collections::HashMap; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft_metafile::{Cap, ClipPath, HAlign, Item, Join, LineStyle, Seg, VAlign}; use vectorcraft_color::Paint; @@ -106,6 +106,10 @@ struct Pending { type MadeClips = HashMap<*const ClipPath, (Arc, Option>)>; /// The last clip region and the clip made for it. type MadeRegion = (Vec<[f32; 4]>, Option>); +/// Brush tiles already averaged, by address: items filled with the same brush share its tile. The +/// `Weak` keeps the address from being reused, and the tile's pixels are freed once the last item +/// that uses it has been read. +type Averaged = HashMap<*const craft_metafile::Tile, (Weak, Option<[u8; 4]>)>; struct Mapper { /// Picture units → points. @@ -120,6 +124,7 @@ struct Mapper { paths: MadeClips, region: Option, pending: Option, + averaged: Averaged, } fn color(c: [u8; 4]) -> Paint { @@ -161,6 +166,7 @@ impl Mapper { paths: HashMap::new(), region: None, pending: None, + averaged: HashMap::new(), } } @@ -317,8 +323,10 @@ impl Mapper { PathEl::MoveTo(p) => Some(*p), _ => None, }); + // A translucent stroke stays apart, so where strokes overlap each one shows. if let Some(p) = &mut self.pending && p.pen == pen + && pen.color[3] == u8::MAX && start.is_some() && p.path.elements().last().and_then(|e| e.end_point()) == start { @@ -338,7 +346,9 @@ impl Mapper { Item::Pattern { segs, even_odd, tile, region, clips } => { self.flush(); let Some(chain) = self.chain(region, &clips) else { return }; - let Some(c) = average(&tile.rgba) else { return }; + let Some(c) = self.averaged.entry(Arc::as_ptr(&tile)).or_insert_with(|| (Arc::downgrade(&tile), average(&tile.rgba))).1 else { + return; + }; self.warn(PATTERNS); let bp = self.path(&segs); if let Some(n) = self.path_node(bp, Some(c), None, even_odd) { diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 689037d277..69abf02e86 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -548,6 +548,29 @@ fn dual_emf_plus_files_draw_their_emf_plus_records() { assert!((f.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", f.opacity); } +#[test] +fn translucent_strokes_drawn_one_after_another_stay_apart() { + // EmfPlusObject: pen 0, 1 pixel wide, with a solid brush of `argb`; then two EmfPlusDrawLines + // with it, from A to B and from B back to A. + let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]); + let lines = |argb: u32| { + let pen = [le(&[0xDBC0_1002u32 as i32, 0, 0, 2]), le_f32(&[1.0]), le(&[0xDBC0_1002u32 as i32, 0, argb as i32])].concat(); + let a_to_b = [le(&[2]), le_f32(&[1000.0, 1000.0, 3000.0, 1000.0])].concat(); + let b_to_a = [le(&[2]), le_f32(&[3000.0, 1000.0, 1000.0, 1000.0])].concat(); + let comment = emf_plus(&[(0x4001, 0, header.clone()), (0x4008, 0x0200, pen), (0x400D, 0, a_to_b), (0x400D, 0, b_to_a), (0x4002, 0, vec![])]); + paths(&import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap().document) + }; + // Each translucent stroke keeps its own opacity, so where they overlap both show. + let p = lines(0x80FF_0000); + assert_eq!(p.len(), 2, "{p:?}"); + for n in &p { + let AppearanceItem::Stroke(st) = &n.appearance.items[0] else { panic!("a stroke") }; + assert!((st.opacity - 128.0 / 255.0).abs() < 1e-6, "{}", st.opacity); + } + // Opaque strokes still join into one path. + assert_eq!(lines(0xFFFF_0000).len(), 1); +} + #[test] fn pattern_brushes_fill_with_their_average_color() { // CREATEDIBPATTERNBRUSHPT: a 2 × 2 tile of 24-bit pixels, two red and two blue (bottom-up rows From d5e58b0e4bb6962218f3933ed168b95f5f605efa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:46:17 -0800 Subject: [PATCH 11/33] Metafile import: a clip of several figures along a box's sides still clips A clip path is left out only when it is one rectangle around the whole picture. Two open figures along the top and bottom of a box enclose nothing, and the objects under such a clip are no longer imported unclipped. --- crates/metafile/src/import.rs | 9 ++++----- crates/metafile/src/tests/import.rs | 7 +++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 43023e0183..dce77b2d7a 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -44,8 +44,9 @@ fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT) } -/// Is `path` an upright rectangle around the whole of `frame`? Writers clip to one first; it clips -/// nothing in the picture. +/// Is `path` one upright rectangle around the whole of `frame`? Writers clip to one first; it clips +/// nothing in the picture. A path of more than one figure is not one rectangle, even when its +/// figures run along the sides of a box. fn around(path: &BezPath, frame: Rect) -> bool { if path.elements().len() > 6 { return false; @@ -67,9 +68,7 @@ fn around(path: &BezPath, frame: Rect) -> bool { }; let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false }; if start { - if let (Some(f), Some(l)) = (first, last) - && !along(f, l) - { + if first.is_some() { return false; } first = Some(i); diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 69abf02e86..4dcb3020c4 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -524,8 +524,11 @@ fn a_clip_whose_box_holds_the_picture_still_clips() { // A bow tie through the four corners of a box around the picture. let mut bow_tie = le(&[0, 0, 0, 0, 4]); bow_tie.extend(le(&[-500, -500, 5500, 3500, 5500, -500, -500, 3500])); - for clip in [diamond, bow_tie] { - let records = vec![(59, vec![]), (3, clip), (60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]; + // Two open figures through the four corners, the top edge and the bottom edge, which enclose + // nothing: MOVETOEX, LINETO, MOVETOEX, LINETO. + let edges = vec![(27, le(&[-500, -500])), (54, le(&[5500, -500])), (27, le(&[5500, 3500])), (54, le(&[-500, 3500]))]; + for clip in [vec![(3, diamond)], vec![(3, bow_tie)], edges] { + let records = [vec![(59, vec![])], clip, vec![(60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]].concat(); let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let layer = back.document.layers[0].children().unwrap(); assert_eq!(layer.len(), 1); From 9e85368a444309e2385f639b6c413bbbd62d673c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:55:40 -0800 Subject: [PATCH 12/33] Metafile import: a file that reaches the most objects one file may hold says so The reader keeps at most 200,000 objects from one file and stops reading there. A picture that reaches that count now carries a warning that any objects after them were not read, and objects dropped past the import's own object limit carry a warning too. --- crates/metafile/src/import/picture.rs | 12 +++++++++++- crates/metafile/src/tests/import.rs | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 8373253ae4..4689572a62 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -36,6 +36,13 @@ use crate::{Imported, Kind}; const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; +const TOO_MANY: &str = "objects past the most one file may hold were left out"; +const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read"; + +/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the +/// limit and does not say whether more items followed, so a picture holding this many may have +/// been cut short. +const READER_ITEMS: usize = 200_000; /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; @@ -243,7 +250,7 @@ impl Mapper { fn push(&mut self, clips: Vec>, mut node: Node) { if self.out.len() >= MAX_NODES { - return; + return self.warn(TOO_MANY); } if !node.visual_bounds().is_none_or(sane) { return self.warn(FAR_AWAY); @@ -526,6 +533,9 @@ pub(crate) fn import(bytes: &[u8]) -> Result { if ends_early(bytes, kind) { m.warn(ENDS_EARLY); } + if pic.items.len() >= READER_ITEMS { + m.warn(AT_LIMIT); + } for item in pic.items { m.item(item); } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 4dcb3020c4..a1ddcc335e 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -370,6 +370,18 @@ fn damaged_files_fail_or_import_partly() { assert!(import(&huge).is_ok()); } +#[test] +fn a_file_with_more_objects_than_are_read_says_so() { + // RECTANGLE records: 10 more than the reader keeps, then a few under that. + let rect = (43, le(&[0, 0, 100, 100])); + let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]); + let back = import(&many).unwrap(); + assert_eq!(paths(&back.document).len(), 200_000); + assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings); + let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap(); + assert!(few.warnings.is_empty(), "{:?}", few.warnings); +} + /// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box. fn png_stretch_dibits(png: &[u8]) -> Vec { // Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start); From 6be8f3095b807366e104a4e24c2927c63465c619 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:14:18 -0800 Subject: [PATCH 13/33] Metafile import: a clip that runs back over its own edges still clips A clip path is left out only when it is one rectangle around the whole picture. One figure through a box's four corners that runs back over its edges encloses less than the box, and the objects under such a clip are no longer imported unclipped. --- crates/metafile/src/import.rs | 11 ++++++++++- crates/metafile/src/tests/import.rs | 6 +++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index dce77b2d7a..c87dd83d72 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -46,7 +46,8 @@ fn sane(r: Rect) -> bool { /// Is `path` one upright rectangle around the whole of `frame`? Writers clip to one first; it clips /// nothing in the picture. A path of more than one figure is not one rectangle, even when its -/// figures run along the sides of a box. +/// figures run along the sides of a box. Nor is one figure that runs back over its own edges, so +/// that it encloses less than the whole box. fn around(path: &BezPath, frame: Rect) -> bool { if path.elements().len() > 6 { return false; @@ -58,6 +59,7 @@ fn around(path: &BezPath, frame: Rect) -> bool { // neighbor (corners are in order around the box), never across it. let along = |i: usize, j: usize| (i + 4 - j) % 4 != 2; let mut seen = [false; 4]; + let mut points = Vec::with_capacity(6); let (mut first, mut last) = (None, None); for e in path.elements() { let (p, start) = match e { @@ -77,12 +79,19 @@ fn around(path: &BezPath, frame: Rect) -> bool { } last = Some(i); seen[i] = true; + points.push(corners[i]); } if let (Some(f), Some(l)) = (first, last) && !along(f, l) { return false; } + // Every edge runs along a side, so the figure winds the same number of times around every + // point inside the box: once, when its area is the box's. + let twice_area: f64 = points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| (*p - corners[0]).cross(*q - corners[0])).sum(); + if (twice_area.abs() - 2.0 * b.area()).abs() > 1e-6 * (1.0 + 2.0 * b.area()) { + return false; + } let b = b.inflate(0.5, 0.5); seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1)) } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index a1ddcc335e..55714c1f71 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -539,7 +539,11 @@ fn a_clip_whose_box_holds_the_picture_still_clips() { // Two open figures through the four corners, the top edge and the bottom edge, which enclose // nothing: MOVETOEX, LINETO, MOVETOEX, LINETO. let edges = vec![(27, le(&[-500, -500])), (54, le(&[5500, -500])), (27, le(&[5500, 3500])), (54, le(&[-500, 3500]))]; - for clip in [vec![(3, diamond)], vec![(3, bow_tie)], edges] { + // One figure through the four corners that runs back over its edges and encloses nothing: + // POLYLINE top-left, top-right, top-left, bottom-left, bottom-right, bottom-left. + let mut retraced = le(&[0, 0, 0, 0, 6]); + retraced.extend(le(&[-500, -500, 5500, -500, -500, -500, -500, 3500, 5500, 3500, -500, 3500])); + for clip in [vec![(3, diamond)], vec![(3, bow_tie)], edges, vec![(4, retraced)]] { let records = [vec![(59, vec![])], clip, vec![(60, vec![]), (67, le(&[5])), (43, le(&[0, 0, 5000, 3000]))]].concat(); let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let layer = back.document.layers[0].children().unwrap(); From ef74b358f6fec261637b89a2e89022615769e6f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:43:34 -0800 Subject: [PATCH 14/33] Docs: a clipping path that paints applies its fill and stroke effects after the group's The geometry effects of a clipping path's own fills and strokes stay live when the clipping path has a fill or stroke, so they reshape it after the geometry effects of the clip group and of the groups around it. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 385c6fa53a..c940da75e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1609,7 +1609,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, and type used as a clipping path keeps them when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. From e001227ce1aab5140080d1f35e17e4a85c4e6691 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:29:00 -0800 Subject: [PATCH 15/33] Selection: effects on a hidden member of a clipping group leave clicks alone A clipping path that is a group clips by its visible members only. A geometry effect on a hidden member made clicks inside the clip group count the group's type by its glyph outlines, where they count it by its frame when nothing has an effect. Clicks now ask `effects::reshaped_clip_outline`, which gives a region only when an object the clipping path clips by has a geometry effect. `clip_outline` uses the same function. --- crates/effects/src/clip.rs | 12 ++++++++---- crates/effects/src/lib.rs | 2 +- crates/engine/src/session/documents.rs | 13 +------------ crates/engine/src/tests/clip.rs | 26 ++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 37 insertions(+), 18 deletions(-) diff --git a/crates/effects/src/clip.rs b/crates/effects/src/clip.rs index 60cc3f2845..e210e097a9 100644 --- a/crates/effects/src/clip.rs +++ b/crates/effects/src/clip.rs @@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData}; /// fills and strokes: the region is then the union of the paths they give, as an export bakes them. /// `None` when there is nothing to clip by (the clipped art is then hidden). pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> { - match clip_effects_applied(clip, true) { - Some(m) => m.clip_outline(Some(&outline_text), &unite), - None => clip.clip_outline(Some(&outline_text), &unite), - } + reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite)) +} + +/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing +/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a +/// group or layer does not clip, so its effects are not counted. +pub fn reshaped_clip_outline(clip: &Node) -> Option> { + clip_effects_applied(clip, true).map(|m| m.clip_outline(Some(&outline_text), &unite)) } /// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c18a31d842..2de6a1d142 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -69,7 +69,7 @@ pub use adjust::{ is_channel, }; pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake}; -pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent}; +pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index a1a3fe5293..b4cecd44d5 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -25,7 +25,7 @@ impl Session { // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); // Clicks inside a clip group fall in the region its clipping path's effects give it. - vectorcraft_doc::hit::set_clip_region(reshaped_clip_region); + vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { @@ -493,17 +493,6 @@ impl Session { } } -/// The region clipping path `clip` clips to with its live geometry effects applied -/// ([`vectorcraft_render::effects::clip_outline`]), for clicks inside its clip group; `None` when -/// nothing in it has a visible geometry effect of its own or on a fill or stroke, so that clicks -/// count its plain shapes, type by its frame. -fn reshaped_clip_region(clip: &Node) -> Option> { - use vectorcraft_render::effects::has_geometry; - let mut reshaped = false; - clip.walk(&mut |n| reshaped |= has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(i.effects()))); - reshaped.then(|| vectorcraft_render::effects::clip_outline(clip)) -} - /// Whether some of type `t` is set in a font named (in any case) one of `names`, lowercased. fn sets_in_any(t: &TextObject, names: &HashSet) -> bool { !names.is_empty() && t.runs.iter().any(|r| names.contains(&r.style.font_family.to_lowercase())) diff --git a/crates/engine/src/tests/clip.rs b/crates/engine/src/tests/clip.rs index 7d500f6835..87af67d95d 100644 --- a/crates/engine/src/tests/clip.rs +++ b/crates/engine/src/tests/clip.rs @@ -128,6 +128,32 @@ fn text_on_top_clips_by_its_glyphs() { assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_))); } +#[test] +fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() { + // The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The + // hidden rectangle does not clip, so clicks inside the clip group still count the type by its + // frame, the counter of the "O" included. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap()); + let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap(); + select(&mut s, &[art, t]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + // Make Clipping Mask takes no group on top, so the group goes in place of the type. + let mut d = (*s.doc().unwrap().doc).clone(); + let mut rect = (*d.remove(r).unwrap()).clone(); + rect.visible = false; + let text = d.remove(t).unwrap(); + let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]); + d.insert(Some(g), 0, group).unwrap(); + let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf); + let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame"); + assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text"); +} + #[test] fn clicks_follow_the_region_a_clipping_paths_effects_give_it() { // Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c940da75e8..d23d645f3f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1610,7 +1610,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. - Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. `doc::hit::tests` and the engine's `tests::clip` cover it. + Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. From 11bd1659f5a5b6726cd82ced6e6ef9c73f1a2ca2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:51:22 -0800 Subject: [PATCH 16/33] Selection: symbol parts follow the region a clipping path's effects give it Direct Selection on a dynamic symbol's instance picked an object in the region its clipping path's effects give it, but cut the object's outline to the plain clipping path, so the outline came out empty or cut short. In a layer of the art whose Preview is off, it tested the effect-shaped region and the fills, where the canvas draws the plain clipping path and outlines. - `hit::symbol_part_outline` cuts to the bounds of the effect-shaped region. The new `hit::symbol_part_outline_in_view` takes the view's outline state, and the Direct Selection overlay passes it. - `hit::symbol_part_at` tests art in a layer whose Preview is off in outline. --- crates/doc/src/hit.rs | 67 +++++++++++++++++++++++++------------ crates/doc/src/hit/tests.rs | 44 ++++++++++++++++++++++++ crates/tools/src/direct.rs | 4 +-- docs/target-app-parity.md | 2 +- 4 files changed, 92 insertions(+), 25 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index c0a80a8964..d6888eb065 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1202,7 +1202,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// group's original shapes, which the canvas does not draw, and guide paths with /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not -/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`. +/// draw. Art in a layer of the symbol whose Preview is off is tested in outline +/// ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or +/// no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { struct Find<'a> { doc: &'a Document, @@ -1212,35 +1214,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> symbols: &'a SymbolBoxes<'a>, } impl Find<'_> { - fn hit(&self, n: &Node, whole: Option) -> bool { - self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some()) + fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> bool { + self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some()) } fn skips_guide(&self, n: &Node) -> bool { self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) } - fn find(&self, n: &Node, path: &mut Vec, whole: Option) -> bool { + /// `outline`: the view is in Outline, or a layer around `n` has Preview off. + fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> bool { if !n.visible || n.locked || n.is_template() || self.skips_guide(n) { return false; } - let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) }; + let outline = outline || previews_off(n); + let opt = HitOptions { outline, ..self.opt }; + let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) }; if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { - return self.hit(n, whole); + return self.hit(n, whole, opt); } let whole = self.art.whole(n, self.doc, whole); if n.clips() && let Some(first) = children.first() { let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false }; - if self.opt.clip_outlines - && first.visible - && !first.locked - && !self.skips_guide(first) - && clip_outline(&clip, self.p, self.opt).is_some() + if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some() { path.push(0); return true; } - if !clip_contains(&clip, self.p, self.opt.outline) { + if !clip_contains(&clip, self.p, outline) { return false; } } @@ -1251,7 +1252,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> } let Ok(i) = u32::try_from(i) else { continue }; path.push(i); - if self.find(c, path, whole) { + if self.find(c, path, whole, outline) { return true; } path.pop(); @@ -1262,7 +1263,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; - Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path) + Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, opt.outline).then_some(path) } /// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]), @@ -1271,9 +1272,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> /// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An /// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut /// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`] -/// picks it. +/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it +/// has any. /// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies. pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option { + symbol_part_outline_in_view(doc, inst, path, false) +} + +/// [`symbol_part_outline`] in the view the canvas shows: with `outline` (Outline view), and below a +/// layer of the art whose Preview is off, the outlines are cut to the bounds of the plain clipping +/// paths, without their live effects, as the clicks of [`HitOptions::outline`] count them. +pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], mut outline: bool) -> Option { let art = InstanceArt::of(doc, inst)?; let part = crate::symbol_overrides::part(&art.art, path)?; let mut out = BezPath::new(); @@ -1283,10 +1292,11 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< for &i in path { let children = n.children()?; whole = art.whole(n, doc, whole); + outline = outline || previews_off(n); if i != 0 && n.clips() && let Some(first) = children.first() - && let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds() + && let Some(clip) = clip_limit(&art.place_unclipped(first, doc, whole)?, outline) { match meet(Some(clip), limit) { Some(r) => limit = Some(r), @@ -1295,12 +1305,24 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< } n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, doc, whole)?, limit, &mut out); + outline_within(&art.place(part, doc, whole)?, limit, outline, &mut out); Some(out) } -/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one. -fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { +/// The box that the art clipped by `clip` is drawn in: the bounds of the region the live geometry +/// effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no such effects +/// and with `outline`, where the canvas draws no effects. +fn clip_limit(clip: &Node, outline: bool) -> Option { + use vectorcraft_geom::kurbo::Shape; + let region = if outline { None } else { clip_region(clip) }; + match region.as_deref() { + Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()), + _ => clip.geometric_bounds(), + } +} + +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. +fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; if let Some(pd) = n.path_data() { match limit { @@ -1314,20 +1336,21 @@ fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { out.extend(b.to_path(0.1)); } let Some(children) = n.children() else { return }; + let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { - let inner = match first.geometric_bounds() { + let inner = match clip_limit(first, outline) { Some(c) => match meet(Some(c), limit) { Some(r) => Some(r), None => return, }, None => limit, }; - rest.iter().for_each(|c| outline_within(c, inner, out)); + rest.iter().for_each(|c| outline_within(c, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, out)); + children.iter().for_each(|c| outline_within(c, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 4584421200..e0c2f8de4d 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1788,6 +1788,50 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() { assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}"); } +/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect +/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and +/// when the layer's Preview is off, the plain clipping path counts, as the canvas draws it. +#[test] +fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() { + set_clip_region(moved_clip_region); + let instance = |preview: bool| { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2)); + if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind { + (*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview); + } + layer.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]); + d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) }); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + (d, inst) + }; + let outline_box = |d: &Document, inst: NodeId, outline: bool| { + let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], outline).unwrap(); + vectorcraft_geom::kurbo::Shape::bounding_box(&o) + }; + let opt = HitOptions::default(); + let (d, inst) = instance(true); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region"); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was"); + let b = outline_box(&d, inst, false); + assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}"); + let b = outline_box(&d, inst, true); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}"); + // With the layer's Preview off, the art's top edge counts within the plain clipping path. + let (d, inst) = instance(false); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws"); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path"); + let b = outline_box(&d, inst, false); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off: the plain clipping path: {b:?}"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cee2c7dfa1..ebcbeb4489 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -55,7 +55,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overrides}; use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; @@ -1029,7 +1029,7 @@ impl Tool for DirectSelectionTool { out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id))); if !self.group { if let Some(sp) = &cx.selection.symbol_part - && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline(cx.doc, n, &sp.path)) + && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.outline)) { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d23d645f3f..1a1462788a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1610,7 +1610,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. - Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. `doc::hit::tests` and the engine's `tests::clip` cover it. + Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. From 1d94c974251ba3931fc411bea7570158eeefbc5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:30:12 -0800 Subject: [PATCH 17/33] Selection: symbol parts count the Preview of the instance's layers Direct Selection on a dynamic symbol's instance below a layer whose Preview is off tested and outlined the art in Preview, where the canvas draws it in outline with the plain clipping paths. When a clipping path's effects left no region, a selected object in its clip group kept an outline cut to the plain clipping path. - `hit::symbol_part_at` and `hit::symbol_part_outline_in_view` count the layers around the instance, the isolated container and the layers around it apart, as clicks outside symbols do. `symbol_part_outline_in_view` takes the click options in place of the outline flag. - The outline of an object is empty when the effects of a clipping path around it leave no region. --- crates/doc/src/hit.rs | 63 ++++++++++++++++++++++--------------- crates/doc/src/hit/tests.rs | 56 ++++++++++++++++++++++----------- crates/tools/src/direct.rs | 2 +- 3 files changed, 76 insertions(+), 45 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d6888eb065..dcb68378d1 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1202,8 +1202,8 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// group's original shapes, which the canvas does not draw, and guide paths with /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not -/// draw. Art in a layer of the symbol whose Preview is off is tested in outline -/// ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or +/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or /// no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { struct Find<'a> { @@ -1263,7 +1263,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; - Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, opt.outline).then_some(path) + let outline = opt.outline || below_preview_off(doc, inst, opt.scope); + Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path) +} + +/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks +/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it +/// does not count. +fn below_preview_off(doc: &Document, n: &Node, scope: Option) -> bool { + let Some(chain) = doc.ancestry(n.id) else { return false }; + let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off)) } /// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]), @@ -1276,15 +1286,19 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> /// has any. /// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies. pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option { - symbol_part_outline_in_view(doc, inst, path, false) + symbol_part_outline_in_view(doc, inst, path, HitOptions::default()) } -/// [`symbol_part_outline`] in the view the canvas shows: with `outline` (Outline view), and below a -/// layer of the art whose Preview is off, the outlines are cut to the bounds of the plain clipping -/// paths, without their live effects, as the clicks of [`HitOptions::outline`] count them. -pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], mut outline: bool) -> Option { +/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view +/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the +/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the +/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as +/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around +/// the object leave no region. +pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { let art = InstanceArt::of(doc, inst)?; let part = crate::symbol_overrides::part(&art.art, path)?; + let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; @@ -1296,12 +1310,9 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], mu if i != 0 && n.clips() && let Some(first) = children.first() - && let Some(clip) = clip_limit(&art.place_unclipped(first, doc, whole)?, outline) { - match meet(Some(clip), limit) { - Some(r) => limit = Some(r), - None => return Some(out), - } + let Some(within) = limit_within(&art.place_unclipped(first, doc, whole)?, limit, outline) else { return Some(out) }; + limit = within; } n = children.get(usize::try_from(i).ok()?)?; } @@ -1309,15 +1320,21 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], mu Some(out) } -/// The box that the art clipped by `clip` is drawn in: the bounds of the region the live geometry -/// effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no such effects -/// and with `outline`, where the canvas draws no effects. -fn clip_limit(clip: &Node, outline: bool) -> Option { +/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the +/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no +/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art +/// is drawn: the effects leave no region, or the box is outside `limit`. +fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option> { use vectorcraft_geom::kurbo::Shape; let region = if outline { None } else { clip_region(clip) }; - match region.as_deref() { + let bounds = match region.as_deref() { Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()), - _ => clip.geometric_bounds(), + Some(_) => return None, + None => clip.geometric_bounds(), + }; + match bounds { + Some(b) => meet(Some(b), limit).map(Some), + None => Some(limit), } } @@ -1340,13 +1357,7 @@ fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPat if n.clips() && let Some((first, rest)) = children.split_first() { - let inner = match clip_limit(first, outline) { - Some(c) => match meet(Some(c), limit) { - Some(r) => Some(r), - None => return, - }, - None => limit, - }; + let Some(inner) = limit_within(first, limit, outline) else { return }; rest.iter().for_each(|c| outline_within(c, inner, outline, out)); return; } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index e0c2f8de4d..4fadb84c86 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -111,10 +111,17 @@ fn half_clipped(d: &mut Document) -> (Node, Node) { } /// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping -/// path, its first shape moved 100 pt right; without one, no geometry effect. +/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip +/// by; without either, no geometry effect. fn moved_clip_region(clip: &Node) -> Option> { - let mut moves = false; - clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + let (mut moves, mut empty) = (false, false); + clip.walk(&mut |n| { + moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move"); + empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty"); + }); + if empty { + return Some(None); + } if !moves { return None; } @@ -1790,18 +1797,24 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() { /// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect /// is picked and outlined in the region the effect gives the clipping path. In Outline view, and -/// when the layer's Preview is off, the plain clipping path counts, as the canvas draws it. +/// when Preview is off for the layer in the art or for the layer the instance is on, the plain +/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline. #[test] fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() { set_clip_region(moved_clip_region); - let instance = |preview: bool| { + // The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that + // layer and of the document layer the instance is on. + let instance = |effect: &str, preview: [bool; 2]| { let mut d = Document::new(300.0, 200.0); + if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *p = preview[1]; + } let l = d.layers[0].id; let (mut mask, art) = half_clipped(&mut d); - mask.appearance.effects.push(test_move()); + mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() }); let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2)); if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind { - (*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview); + (*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]); } layer.set_clips(true); let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]); @@ -1810,26 +1823,33 @@ fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() { d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); (d, inst) }; - let outline_box = |d: &Document, inst: NodeId, outline: bool| { - let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], outline).unwrap(); + let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| { + let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap(); vectorcraft_geom::kurbo::Shape::bounding_box(&o) }; let opt = HitOptions::default(); - let (d, inst) = instance(true); + let (d, inst) = instance("test.move", [true, true]); let n = d.node(inst).unwrap(); assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region"); assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was"); - let b = outline_box(&d, inst, false); + let b = outline_box(&d, inst, opt); assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}"); - let b = outline_box(&d, inst, true); + let b = outline_box(&d, inst, HitOptions { outline: true, ..opt }); assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}"); - // With the layer's Preview off, the art's top edge counts within the plain clipping path. - let (d, inst) = instance(false); + // With Preview off, the art's top edge counts within the plain clipping path. + for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] { + let (d, inst) = instance("test.move", preview); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}"); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}"); + let b = outline_box(&d, inst, opt); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}"); + } + // An effect that leaves the clipping path no region hides the art: no pick and no outline. + let (d, inst) = instance("test.empty", [true, true]); let n = d.node(inst).unwrap(); - assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws"); - assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path"); - let b = outline_box(&d, inst, false); - assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off: the plain clipping path: {b:?}"); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None); + assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined"); } /// In a dynamic symbol's art that placing through its 9-slice guides could make more than diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index ebcbeb4489..69230dc050 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1029,7 +1029,7 @@ impl Tool for DirectSelectionTool { out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id))); if !self.group { if let Some(sp) = &cx.selection.symbol_part - && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.outline)) + && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.hit_options())) { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } From 9d8407b3deb2cca3235886615b43a0cdb38782fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:45:04 -0800 Subject: [PATCH 18/33] Metafile import: metric WMFs are read at 96 pixels an inch, and only round solid strokes join A WMF without a usable placeable box that draws in a metric map mode (MM_LOMETRIC to MM_TWIPS) is read at 96 pixels an inch, the scale craft_metafile plays those modes at, so a one-inch MM_TWIPS picture opens at 72 pt instead of 4.8 pt. The mode that more of the drawing records the reader plays are drawn in decides, with SAVEDC and RESTOREDC followed as the reader follows them; a file that draws nothing goes by its last mode. Opaque strokes drawn one after another now join into one path only when the pen is solid with round caps and round joins. A dashed stroke keeps its own dash phase, and flat or square caps and miter or bevel joins stay as the separate strokes drew them. --- crates/metafile/src/import/picture.rs | 102 +++++++++++++++++++++++--- crates/metafile/src/tests/import.rs | 87 ++++++++++++++++++++++ 2 files changed, 178 insertions(+), 11 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 4689572a62..5385d94153 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -2,8 +2,9 @@ //! picture, and the picture's items become document objects here. //! //! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit -//! and dashes from the pen). Opaque strokes drawn one after another, each starting where the -//! last one ended, with the same pen and clip, join into one path. +//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after +//! another, each starting where the last one ended, with the same pen and clip, join into one +//! path. Other strokes stay apart, each with its own caps and its own dashes. //! - A path filled with a pattern or hatched brush is filled with the average color of the //! brush's tile. //! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or @@ -14,8 +15,10 @@ //! the whole picture clips nothing and is left out. //! //! A WMF without a placeable header is read at 1440 units an inch, and one whose placeable box is -//! empty or inverted at the units an inch the header gives. An EMF without a usable frame is read -//! at its device's pixels a millimetre (96 pixels an inch when the header doesn't say). +//! empty or inverted at the units an inch the header gives. Either one that draws in a metric map +//! mode (MM_LOMETRIC to MM_TWIPS) is read at 96 pixels an inch, as `craft_metafile` plays those +//! modes. An EMF without a usable frame is read at its device's pixels a millimetre (96 +//! pixels an inch when the header doesn't say). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -46,11 +49,79 @@ const READER_ITEMS: usize = 200_000; /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; +/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them. +const SAVED_LEVELS: usize = 1024; +/// Points a pixel at 96 pixels an inch. +const PT_PER_PX: f64 = 72.0 / 96.0; /// Points a millimetre. const PT_PER_MM: f64 = 72.0 / 25.4; +/// WMF records that draw and that `craft_metafile` plays: lines, shapes, text, PATBLT and bitmaps. +const WMF_DRAWS: [u16; 16] = + [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0521, 0x0538, 0x061C, 0x061D, 0x0817, 0x081A, 0x0830, 0x0940, 0x0A32, 0x0B41, 0x0F43]; + +/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those +/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in +/// decides; a file that draws nothing goes by its last mode. `start` is where the standard header +/// begins. +fn wmf_metric(bytes: &[u8], start: usize) -> bool { + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let Some(words) = start.checked_add(2).and_then(u16_at) else { return false }; + let mut at = start.saturating_add(usize::from(words) * 2); + let mut mode = 1; + let metric = |mode: u16| (2..=6).contains(&mode); + // Drawing records played in a metric mode, and in any other. + let (mut in_metric, mut in_other) = (0usize, 0usize); + // The modes SAVEDC kept, which RESTOREDC brings back as the reader does. + let mut saved: Vec = Vec::new(); + // The records as the reader walks them: it stops at the end record, a record shorter than its + // header, one that runs past the file and a SAVEDC past its 1,024 levels. + while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) { + let size = (words as usize).saturating_mul(2); + let Some(next) = at.checked_add(size) else { break }; + if function == 0 || size < 6 || next > bytes.len() { + break; + } + match function { + // SETMAPMODE, when the record holds its mode. + 0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode), + // SAVEDC. + 0x001E => { + if saved.len() >= SAVED_LEVELS { + break; + } + saved.push(mode); + } + // RESTOREDC: a negative count pops that many levels, a positive one goes back to that + // level. One that names no saved level changes nothing. + 0x0127 if size >= 8 => { + let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes()))); + let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; + if let Some(level) = level + && let Some(m) = saved.get(level).copied() + { + mode = m; + saved.truncate(level); + } + } + f if WMF_DRAWS.contains(&f) => { + if metric(mode) { + in_metric += 1; + } else { + in_other += 1; + } + } + _ => {} + } + at = next; + } + if in_metric == in_other { metric(mode) } else { in_metric > in_other } +} + /// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an -/// EMF with a frame in points, and other files in their logical (WMF) or device (EMF) units. +/// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map +/// mode) or device units (EMF). fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]])); @@ -59,15 +130,20 @@ fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { let positive = |v: Option| v.filter(|v| *v > 0).map(f64::from); match kind { Kind::Wmf => { - if bytes.get(..4) != Some(&PLACEABLE_KEY.to_le_bytes()[..]) { - return (WMF_UNIT, WMF_UNIT); - } - if let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12)) + let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]); + if placeable + && let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12)) && r > l && b > t { return (1.0, 1.0); } + if wmf_metric(bytes, if placeable { 22 } else { 0 }) { + return (PT_PER_PX, PT_PER_PX); + } + if !placeable { + return (WMF_UNIT, WMF_UNIT); + } let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from); (k, k) } @@ -85,7 +161,7 @@ fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) { match px_mm { Some(_) if frame => (1.0, 1.0), Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y), - _ => (0.75, 0.75), + _ => (PT_PER_PX, PT_PER_PX), } } } @@ -330,10 +406,14 @@ impl Mapper { PathEl::MoveTo(p) => Some(*p), _ => None, }); - // A translucent stroke stays apart, so where strokes overlap each one shows. + // A translucent stroke stays apart, so where strokes overlap each one shows. So + // does a dashed one, whose dashes start at its own start, and one whose caps + // or joins aren't round: a join where two strokes meet is not their two caps. if let Some(p) = &mut self.pending && p.pen == pen && pen.color[3] == u8::MAX + && pen.line.dash.is_empty() + && matches!((&pen.line.cap, &pen.line.join), (Cap::Round, Join::Round)) && start.is_some() && p.path.elements().last().and_then(|e| e.end_point()) == start { diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 55714c1f71..a193997c4b 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -349,6 +349,66 @@ fn wmf_without_a_placeable_header_is_read_at_1440_units_an_inch() { assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{:?}", p[0].geometric_bounds()); } +#[test] +fn wmf_without_a_placeable_box_in_a_metric_map_mode_is_read_at_96_pixels_an_inch() { + // MM_TWIPS (y up) and a window of 1440 twips square: one inch. The rectangle is the whole window. + let records = vec![(0x0103, le16(&[6])), (0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), (0x041B, le16(&[1440, 1440, 0, 0]))]; + let boxed = hand_wmf(1440, 1440, &records); + let plain = boxed[22..].to_vec(); + // The box runs from right to left, so it gives no size. + let mut inverted = boxed; + inverted[6..8].copy_from_slice(&1440i16.to_le_bytes()); + inverted[10..12].copy_from_slice(&0i16.to_le_bytes()); + for bytes in [plain, inverted] { + let back = import(&bytes).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-4), "{:?}", p[0].geometric_bounds()); + } +} + +#[test] +fn wmf_whose_metric_map_mode_is_restored_away_is_read_at_1440_units_an_inch() { + // SAVEDC, MM_TWIPS, then RESTOREDC back to MM_TEXT, by a count of levels and by a level; the + // drawing is then the one in `wmf_without_a_placeable_header_is_read_at_1440_units_an_inch`. + for restore in [-1i16, 1] { + let records = vec![ + (0x001E, Vec::new()), + (0x0103, le16(&[6])), + (0x0127, le16(&[restore])), + (0x020B, le16(&[0, 0])), + (0x020C, le16(&[1440, 2880])), + (0x041B, le16(&[1440, 1440, 0, 0])), + ]; + let plain = hand_wmf(2880, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + assert!(near(back.document.artboards[0].rect, Rect::new(0.0, 0.0, 144.0, 72.0), 1e-6), "{restore}: {:?}", back.document.artboards[0].rect); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 72.0), 1e-6), "{restore}: {:?}", p[0].geometric_bounds()); + } +} + +#[test] +fn wmf_that_draws_in_a_metric_map_mode_and_restores_is_read_at_96_pixels_an_inch() { + // SAVEDC, MM_TWIPS, a one-inch rectangle, then RESTOREDC back to MM_TEXT with nothing more drawn. + let records = vec![ + (0x001E, Vec::new()), + (0x0103, le16(&[6])), + (0x020B, le16(&[0, 0])), + (0x020C, le16(&[1440, 1440])), + (0x041B, le16(&[1440, 1440, 0, 0])), + (0x0127, le16(&[-1])), + ]; + let plain = hand_wmf(1440, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "{b:?}"); +} + #[test] fn damaged_files_fail_or_import_partly() { let good = emf(&sample()).bytes; @@ -590,6 +650,33 @@ fn translucent_strokes_drawn_one_after_another_stay_apart() { assert_eq!(lines(0xFFFF_0000).len(), 1); } +#[test] +fn strokes_join_only_with_round_caps_round_joins_and_no_dashes() { + // CREATEPENINDIRECT: a 20-unit black pen of `style`, selected; then two lines one after the + // other that meet at a right angle. + let lines = |style: i16| { + let records = vec![ + (0x02FA, [le16(&[style, 20, 0]), 0u32.to_le_bytes().to_vec()].concat()), + (0x012D, le16(&[0])), + (0x0214, le16(&[100, 100])), + (0x0213, le16(&[100, 700])), + (0x0213, le16(&[700, 700])), + ]; + paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document) + }; + // Round caps and round joins, a solid line: one path, as a round join is the two round caps. + assert_eq!(lines(0).len(), 1); + // Flat caps and miter joins, flat caps alone and miter joins alone: each line keeps its caps. + for style in [0x2200, 0x0200, 0x2000] { + let p = lines(style); + assert_eq!(p.len(), 2, "style {style:#x}: {p:?}"); + } + // PS_DASH: each line's dashes start at its own start. + let p = lines(1); + assert_eq!(p.len(), 2, "{p:?}"); + assert!(p.iter().all(|n| n.appearance.stroke().is_some_and(|st| st.dash.is_some())), "{p:?}"); +} + #[test] fn pattern_brushes_fill_with_their_average_color() { // CREATEDIBPATTERNBRUSHPT: a 2 × 2 tile of 24-bit pixels, two red and two blue (bottom-up rows From 0b1e1e99a11bd7ffebbcd755ce68db4a24055fa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 10:22:45 -0800 Subject: [PATCH 19/33] =?UTF-8?q?Effects:=20Effect=20=E2=80=BA=20SVG=20Fil?= =?UTF-8?q?ters=20lists=20default=20filters?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Effect › SVG Filters and Apply SVG Filter list 14 default filters in every document, before the document's own. The set, the names and the values are VectorCraft's own, written with SVG 1.1 filter primitives (crates/effects/src/svg_filter/defaults.rs). A document holds none of the defaults until one is applied or edited there. svgFilter.apply with a default's name copies it into the document in the same undo step, and svgFilter.define with replace naming a default adds the edited copy under that name. The copy is listed in the default's place. svgFilter.delete refuses a default the document holds no copy of, and deleting the copy lists the default again. svgFilter.list also returns the defaults. svgFilter.apply takes index and item to put the filter in the place of an applied SVG filter, which the dialog's OK uses when it is opened for an applied effect; an index that is not an applied SVG filter, null included, is an error. --- crates/effects/src/svg_filter.rs | 1 + crates/effects/src/svg_filter/defaults.rs | 248 ++++++++++++++++++++++ crates/engine/src/cmd/effectcmd.rs | 2 +- crates/engine/src/cmd/svgfilter.rs | 137 +++++++++--- crates/engine/src/tests/svgfilter.rs | 176 +++++++++++++++ crates/engine/tests/command_sweep.rs | 4 + crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/svg_filter.rs | 229 +++++++++++++++----- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/effects-parity.md | 2 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 2 +- 12 files changed, 740 insertions(+), 85 deletions(-) create mode 100644 crates/effects/src/svg_filter/defaults.rs diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 3877a60ae9..0c4bff0f1d 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -16,6 +16,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2}; use crate::pixel::PixelSpace; use crate::util::{num, text}; +pub mod defaults; #[cfg(test)] mod tests; diff --git a/crates/effects/src/svg_filter/defaults.rs b/crates/effects/src/svg_filter/defaults.rs new file mode 100644 index 0000000000..5ce67fac6b --- /dev/null +++ b/crates/effects/src/svg_filter/defaults.rs @@ -0,0 +1,248 @@ +//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every +//! document. The set, the names and the values are VectorCraft's own, written with the filter +//! primitives of SVG 1.1 (). A default is not part of a +//! document until it is applied or edited there: the document then holds a copy under the +//! default's name, and that copy stands in the default's place in the lists. Every default computes +//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors. + +use vectorcraft_doc::SvgFilter; + +/// A default SVG filter: its name (the `` element's `id`) and the element's XML. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DefaultFilter { + pub name: &'static str, + pub xml: &'static str, +} + +/// The default filters, in the order the lists show them. +pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [ + DefaultFilter { + name: "Soft Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Heavy Blur", + xml: r#""#, + }, + DefaultFilter { + name: "Soft Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Hard Shadow", + xml: r#""#, + }, + DefaultFilter { + name: "Glow", + xml: r##""##, + }, + DefaultFilter { + name: "Bevel", + xml: r##""##, + }, + DefaultFilter { + name: "Emboss", + xml: r#""#, + }, + DefaultFilter { + name: "Thicken", + xml: r#""#, + }, + DefaultFilter { + name: "Thin", + xml: r#""#, + }, + DefaultFilter { + name: "Rough Edges", + xml: r#""#, + }, + DefaultFilter { + name: "Grain", + xml: r#""#, + }, + DefaultFilter { + name: "Grayscale", + xml: r#""#, + }, + DefaultFilter { + name: "Invert", + xml: r#""#, + }, + DefaultFilter { + name: "Hue Shift", + xml: r#""#, + }, +]; + +/// The default filter named `name`. +pub fn default_filter(name: &str) -> Option { + DEFAULT_FILTERS.iter().copied().find(|f| f.name == name) +} + +impl DefaultFilter { + /// The filter as a document holds it once it is applied or edited there. + pub fn to_filter(self) -> SvgFilter { + SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() } + } +} + +/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold. +#[derive(Clone, Debug, PartialEq)] +pub struct Listed { + pub filter: SvgFilter, + /// A default the document has no filter named for: applying or editing it adds a copy. + pub default: bool, +} + +/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`, +/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the +/// document's filter of that name in its place), then the document's other filters in their order. +pub fn listed(held: &[SvgFilter]) -> (Vec, usize) { + let mut out: Vec = DEFAULT_FILTERS + .iter() + .map(|d| match held.iter().find(|f| f.name == d.name) { + Some(f) => Listed { filter: f.clone(), default: false }, + None => Listed { filter: d.to_filter(), default: true }, + }) + .collect(); + let defaults = out.len(); + out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false })); + (out, defaults) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::Effect; + use vectorcraft_geom::{Affine, Point}; + + use super::*; + use crate::pixel::{Channels, PixelSpace}; + use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id}; + use crate::{PixelFx, RasterFx, raster_effects}; + + /// A `w` × `w` raster whose pixels are one point wide. + fn space(w: usize) -> PixelSpace { + let wd = w as f64; + PixelSpace { + to_doc: Affine::scale(1.0), + px: 1.0, + center: Point::new(wd / 2.0, wd / 2.0), + channels: Channels::Rgb, + line: 1.0, + extent: 0.5 * wd.hypot(wd), + } + } + + /// The default named `name` as the renderer reads it. + fn fx(name: &str) -> SvgFilterFx { + let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}")); + let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true }; + match raster_effects(&[e]).first() { + Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(), + other => panic!("{name}: {other:?}"), + } + } + + /// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`. + fn run(name: &str, rgb: [u8; 3]) -> Vec { + let mut data: Vec = (0..40usize) + .flat_map(|y| (0..40usize).map(move |x| (x, y))) + .flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] }) + .collect(); + fx(name).apply(&mut data, 40, 40, &space(40)); + data + } + + fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] { + let i = (y * 40 + x) * 4; + [d[i], d[i + 1], d[i + 2], d[i + 3]] + } + + #[test] + fn every_default_is_a_filter_the_check_takes_under_its_own_name() { + let mut seen = std::collections::BTreeSet::new(); + for d in DEFAULT_FILTERS { + assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name); + assert!(seen.insert(d.name), "{} is listed twice", d.name); + assert_eq!(d.name, d.name.trim()); + // Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is. + assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name); + assert_eq!(default_filter(d.name), Some(d)); + assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name); + } + assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX); + assert_eq!(default_filter("soft blur"), None, "names match exactly"); + } + + #[test] + fn every_default_draws_and_is_written_to_svg_as_a_filter() { + let plain = { + let mut d = vec![0u8; 40 * 40 * 4]; + for y in 10..30 { + for x in 10..30 { + d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]); + } + } + d + }; + for d in DEFAULT_FILTERS { + assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name); + assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name); + } + } + + /// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks. + #[test] + fn the_color_defaults_compute_what_svg_1_1_defines() { + let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1); + // feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11). + let inv = at(&run("Invert", [200, 60, 20]), 20, 20); + assert!(near(inv, [55, 195, 235, 255]), "{inv:?}"); + // feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10). + let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20); + let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8; + assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}"); + // feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave + // R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'. + let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20); + let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64); + let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8); + assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}"); + } + + /// The shape defaults against what their primitives define: an offset copy of the alpha behind + /// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20). + #[test] + fn the_shape_defaults_move_and_resize_the_alpha() { + let shadow = run("Hard Shadow", [200, 60, 20]); + assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top"); + // Right of and below the art by up to 3: black at 60% alpha (premultiplied 153). + assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]); + assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset"); + assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left"); + let thick = run("Thicken", [200, 60, 20]); + assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius"); + let thin = run("Thin", [200, 60, 20]); + assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius"); + let soft = run("Soft Shadow", [200, 60, 20]); + assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]); + let below = at(&soft, 33, 33); + assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}"); + } + + #[test] + fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() { + let (all, defaults) = listed(&[]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len())); + assert!(all.iter().all(|l| l.default)); + let mine = SvgFilter { name: "Mine".into(), xml: "".into() }; + let glow = SvgFilter { name: "Glow".into(), xml: "".into() }; + let (all, defaults) = listed(&[mine.clone(), glow.clone()]); + assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len())); + let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap(); + assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was"); + assert_eq!(all.last(), Some(&Listed { filter: mine, default: false })); + assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1); + } +} diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 65672f8b6b..974d876d2e 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -718,7 +718,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result { /// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one /// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still /// fit; a hidden one has its given values checked. → `{ids}`. -fn set_params(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.setParams"; let index = index_param(p, "index", C)?; let mut params = p.get("params").cloned().unwrap_or(Value::Null); diff --git a/crates/engine/src/cmd/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 98b29a6e27..43af8bce35 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -3,9 +3,14 @@ //! applied effect names the document's filter: editing the filter changes what every object that //! uses it draws, and deleting it leaves their effects in place, drawing nothing, until a filter of //! that name exists again. Each effect holds the definition it draws with, kept in step here. +//! +//! The default filters ([`svg_filter::defaults`]) are listed for every document. Applying or +//! editing one adds a copy to the document under the default's name, and from then on that copy is +//! the filter of that name. Deleting the copy lists the default again. use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, SvgFilter}; +use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter}; use vectorcraft_render::effects::{self, svg_filter}; use super::fileio::{absolute_path, read_file_head}; @@ -21,7 +26,7 @@ pub fn specs() -> Vec { "SVG Filters", [], None, - "{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order", + "{} → {filters: [{name, xml}…], defaults: [{name, xml, inDocument}…]} filters: the SVG filters the document holds, in the order they were added; defaults: the default filters every document lists (VectorCraft's own set), with inDocument true when the document holds a filter of that name, which then stands in the default's place. The SVG Filters submenu and Apply SVG Filter list the defaults first, then the document's other filters", has_doc, list ), @@ -30,7 +35,7 @@ pub fn specs() -> Vec { "New SVG Filter", [], None, - "{xml: one SVG element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter has is refused and a document holds at most 64 filters → {name, filters}", + "{xml: one SVG element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter of the document has is refused and a document holds at most 64 filters; replace with the name of a default filter the document does not hold adds the edited copy to the document under that name, and code equal to the default's adds nothing; a new filter may take a default's name, and then stands in its place → {name, filters}", has_doc, define ), @@ -39,7 +44,7 @@ pub fn specs() -> Vec { "Delete SVG Filter", [], None, - "{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again → {filters}", + "{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again, or the default of that name is applied; a default filter the document holds no copy of is refused (the defaults are not deleted), and deleting the document's copy of one lists the default again → {filters}", has_doc, delete ), @@ -57,7 +62,7 @@ pub fn specs() -> Vec { "Apply SVG Filter", [], None, - "{name, ids?|id?, item?} apply the document's SVG filter `name` (svgFilter.list) to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}", + "{name, ids?|id?, item?, index?} apply the document's SVG filter `name`, or the default filter of that name when the document holds none (svgFilter.list), to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}; with index, the filter takes the place of the applied svg.filter effect at index of item, like effect.setParams → {ids}; a default is copied into the document in the same undo step, which is refused when the document already holds 64 filters", has_doc, apply ), @@ -69,7 +74,10 @@ fn filters_json(d: &Document) -> Value { } fn list(s: &mut Session, _: &Value) -> Result { - Ok(json!({ "filters": filters_json(&s.doc()?.doc) })) + let d = &s.doc()?.doc; + let held = |name: &str| d.svg_filters.iter().any(|f| f.name == name); + let defaults: Vec = DEFAULT_FILTERS.iter().map(|f| json!({ "name": f.name, "xml": f.xml, "inDocument": held(f.name) })).collect(); + Ok(json!({ "filters": filters_json(d), "defaults": defaults })) } /// `p`'s `name`, trimmed and not empty. @@ -132,10 +140,12 @@ fn define(s: &mut Session, p: &Value) -> Result { }; svg_filter::check(&xml).map_err(|e| bad(C, e))?; let filters = &s.doc()?.doc.svg_filters; - let at = match &replace { - Some(r) => Some(filters.iter().position(|f| f.name == *r).ok_or_else(|| bad(C, format!("the document has no SVG filter named {r:?}")))?), - None => None, - }; + let at = replace.as_ref().and_then(|r| filters.iter().position(|f| f.name == *r)); + // A default the document does not hold: its edited copy is added under the default's name. + let default = replace.as_ref().filter(|_| at.is_none()).and_then(|r| default_filter(r)); + if let Some(r) = replace.as_ref().filter(|_| at.is_none() && default.is_none()) { + return Err(bad(C, format!("the document has no SVG filter named {r:?}"))); + } // An edited filter keeps its name, whatever id its new code gives it. let xml = match &replace { Some(r) => svg_filter::with_id(&xml, r).ok_or_else(|| bad(C, "give one element"))?, @@ -145,22 +155,28 @@ fn define(s: &mut Session, p: &Value) -> Result { if filters.iter().enumerate().any(|(i, f)| f.name == name && Some(i) != at) { return Err(bad(C, format!("the document already has an SVG filter named {name:?}"))); } + let new = SvgFilter { name: name.clone(), xml }; + // Nothing to record when the filter, and every object that uses it, is already as given: a + // default saved with its own code stays out of the document. + let as_given = match default { + Some(d) => d.to_filter() == new, + None => at.and_then(|i| filters.get(i)) == Some(&new), + }; + if as_given && !out_of_step(&s.doc()?.doc, &new.name, &new.xml) { + return Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) })); + } if at.is_none() && filters.len() >= SvgFilter::MAX { return Err(bad(C, format!("a document holds at most {} SVG filters", SvgFilter::MAX))); } - let new = SvgFilter { name: name.clone(), xml }; - // Nothing to record when the filter, and every object that uses it, is already as given. - if at.and_then(|i| filters.get(i)) != Some(&new) || out_of_step(&s.doc()?.doc, &new.name, &new.xml) { - let label = if at.is_some() { "Edit SVG Filter" } else { "New SVG Filter" }; - s.edit(label, |d, _| { - update_users(d, &new.name, &new.xml); - match at.and_then(|i| d.svg_filters.get_mut(i)) { - Some(f) => *f = new, - None => d.svg_filters.push(new), - } - Ok(()) - })?; - } + let label = if replace.is_some() { "Edit SVG Filter" } else { "New SVG Filter" }; + s.edit(label, |d, _| { + update_users(d, &new.name, &new.xml); + match at.and_then(|i| d.svg_filters.get_mut(i)) { + Some(f) => *f = new, + None => d.svg_filters.push(new), + } + Ok(()) + })?; Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) })) } @@ -168,6 +184,9 @@ fn delete(s: &mut Session, p: &Value) -> Result { const C: &str = "svgFilter.delete"; let name = name_param(p, C)?; if !s.doc()?.doc.svg_filters.iter().any(|f| f.name == name) { + if default_filter(&name).is_some() { + return Err(bad(C, format!("{name:?} is a default SVG filter, and the document holds no copy of it to delete"))); + } return Err(bad(C, format!("the document has no SVG filter named {name:?}"))); } s.edit("Delete SVG Filter", |d, _| { @@ -222,13 +241,79 @@ fn import(s: &mut Session, p: &Value) -> Result { fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "svgFilter.apply"; let name = name_param(p, C)?; - let f = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name).cloned(); - let f = f.ok_or_else(|| bad(C, format!("the document has no SVG filter named {name:?}")))?; - let mut q = json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }); + let filters = &s.doc()?.doc.svg_filters; + // The document's filter of that name, or the default of that name, which the document then takes. + let (f, copied) = match (filters.iter().find(|f| f.name == name), default_filter(&name)) { + (Some(f), _) => (f.clone(), false), + (None, Some(_)) if filters.len() >= SvgFilter::MAX => { + return Err(bad(C, format!("a document holds at most {} SVG filters, and applying a default filter adds it", SvgFilter::MAX))); + } + (None, Some(d)) => (d.to_filter(), true), + (None, None) => return Err(bad(C, format!("the document has no SVG filter named {name:?}"))), + }; + // A given `index`, null included, is checked as an index: only a missing one adds an effect. + let replaces = p.get("index").is_some(); + let mut q = match replaces { + true => json!({ "index": p["index"], "params": { "name": f.name, "xml": f.xml } }), + false => json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }), + }; for key in ["ids", "id", "item"] { if let Some(v) = p.get(key) { q[key] = v.clone(); } } - super::effectcmd::apply(s, &q) + if !copied { + return apply_as_given(s, p, &q, replaces, None); + } + // The effect and the copy are two edits joined into one step. The history keeps room for both + // until they are joined, so the application lets one old step go at most, as any edit does. + let limit = s.doc()?.history.limit; + if let Some(st) = s.active_mut() { + st.history.limit = limit.saturating_add(2); + } + let out = apply_as_given(s, p, &q, replaces, Some(f)); + if let Some(st) = s.active_mut() { + st.history.limit = limit; + st.history.trim(); + } + out +} + +/// [`apply`] once the filter is known: the effect added (`q`) or put in the applied filter's place +/// (`replaces`), and `copy`, a default's copy, added to the document in the same undo step. +fn apply_as_given(s: &mut Session, p: &Value, q: &Value, replaces: bool, copy: Option) -> Result { + const C: &str = "svgFilter.apply"; + let newest = s.doc()?.history.step().0; + let out = if replaces { + super::appearance::index_param(p, "index", C)?; + // Only an applied SVG filter gives its place: another effect would take the filter's + // parameters as its own. + let edited = super::effectcmd::set_params_effects(s, q); + if edited.is_empty() || edited.iter().any(|e| e != effects::SVG_FILTER) { + return Err(bad(C, "`index` must be the index of an applied SVG filter")); + } + super::effectcmd::set_params(s, q)? + } else { + super::effectcmd::apply(s, q)? + }; + if let Some(f) = copy { + // The copy joins the step that applied it, under that step's name. That step is found by + // its document, not its place: in an undo group both edits join the group's one step. + let h = &s.doc()?.history; + let applied = h.undo.last().filter(|_| h.step().0 != newest).map(|step| (step.label.clone(), step.doc.clone())); + let label = applied.as_ref().map_or_else(|| "SVG Filter".to_string(), |(l, _)| l.clone()); + s.edit(&label, |d, _| { + update_users(d, &f.name, &f.xml); + d.svg_filters.push(f); + Ok(()) + })?; + let undo = &s.doc()?.history.undo; + let below = undo.len().checked_sub(2); + if let (Some(at), Some((_, doc))) = (below, &applied) + && undo.get(at).is_some_and(|e| std::sync::Arc::ptr_eq(&e.doc, doc)) + { + super::menucmds::squash(s, at, &label); + } + } + Ok(out) } diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 10f0ad75ca..e42d7f9736 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() { assert_eq!((out.contains(" Vec<(String, bool)> { + let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default(); + listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect() +} + +/// Every document lists the default filters without holding them; applying one adds the effect and +/// the document's copy in one undo step. +#[test] +fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() { + use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS; + let mut s = session(); + let listed = defaults(&mut s); + assert_eq!(listed.len(), DEFAULT_FILTERS.len()); + assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them"); + assert!(names(&mut s).is_empty()); + let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap(); + assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false})); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let before = steps(&s); + let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"})); + assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0))); + assert_eq!(steps(&s), before + 1, "the effect and the copy are one step"); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter"); + assert_eq!(names(&mut s), ["Soft Shadow"]); + assert_eq!(drawn(&s, a), json!(soft.xml)); + assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true))); + // Applied again, the document's copy is the filter: nothing more is added. + run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]})); + assert_eq!(names(&mut s), ["Soft Shadow"]); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect"); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + run(&mut s, "edit.redo", json!({})); + assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml))); + // Nothing to apply it to: no copy and no step. + let mut s = session(); + assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected"); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly"); +} + +/// With a full history, applying a default lets one old step go, as any edit does: the copy joins +/// the step that applied it, and one Undo takes both back. +#[test] +fn a_default_applied_with_a_full_history_is_still_one_step() { + let mut s = session(); + s.active_mut().unwrap().history.limit = 3; + let a = rect(&mut s, 10.0); + rect(&mut s, 30.0); + rect(&mut s, 50.0); + assert_eq!(steps(&s), 3); + run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]})); + // The application takes one place in the history: only the oldest step went. + assert_eq!(steps(&s), 3); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter"); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty(), "the copy is undone with the effect"); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); +} + +/// Edit SVG Filter on a default saves the edited copy in the document under the default's name; +/// the document's filter then stands in the default's place, and deleting it lists the default again. +#[test] +fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() { + use vectorcraft_render::effects::svg_filter::defaults::default_filter; + let mut s = session(); + let glow = default_filter("Glow").unwrap(); + // Saved with its own code: nothing to keep, and no undo step. + run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"})); + assert_eq!((names(&mut s).len(), steps(&s)), (0, 0)); + let edited = r#""#; + assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow"); + assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1)); + assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter"); + let kept = r#""#; + assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name"); + // Applying the name now applies the document's filter. + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})); + assert_eq!(drawn(&s, a), json!(kept)); + // Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default. + run(&mut s, "svgFilter.delete", json!({"name": "Glow"})); + assert_eq!(drawn(&s, a), json!("")); + assert!(defaults(&mut s).contains(&("Glow".to_string(), false))); + // The default itself is not deleted. + let before = steps(&s); + assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter")); + assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named")); + assert_eq!(steps(&s), before); + // Applied again, the default is copied back, and the object that named it draws with it. + let b = rect(&mut s, 50.0); + run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]})); + assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml))); + assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application"); + // A new filter may take a default's name the document does not hold. + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": r#""#})); + assert!(defaults(&mut s).contains(&("Invert".to_string(), true))); + // An unknown name is still refused. + assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\"")); +} + +/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in +/// the same undo step; any other effect keeps its place. +#[test] +fn apply_with_an_index_replaces_an_applied_filter() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]})); + run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]})); + let before = steps(&s); + let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null})); + assert_eq!(r["ids"], json!([a.0])); + assert_eq!(steps(&s), before + 1, "one step"); + let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone(); + assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather")); + assert_eq!(names(&mut s), ["Shift", "Invert"]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&mut s), ["Shift"]); + assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift"); + // Not an SVG filter, no effect there, or not an index: refused, and the default is not copied. + let before = steps(&s); + for (index, why) in [ + (json!(1), "applied SVG filter"), + (json!(7), "applied SVG filter"), + (json!("x"), "`index`"), + (json!(-1), "`index`"), + (json!(null), "`index`"), + ] { + let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null})); + assert!(e.contains(why), "{index}: {e}"); + } + assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before)); +} + +/// A default needs room in the document: at 64 filters applying one is refused, and a filter the +/// document holds still applies. +#[test] +fn a_full_document_refuses_a_default_it_does_not_hold() { + let mut s = session(); + let a = rect(&mut s, 10.0); + for i in 0..64 { + run(&mut s, "svgFilter.define", json!({"xml": format!("")})); + } + let before = steps(&s); + assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters")); + let edited = r#""#; + assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters")); + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty()); + run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]})); +} + +/// A default applied in one document is written to SVG as a filter and read back from the native +/// format with the document's copy. +#[test] +fn an_applied_default_survives_svg_export_and_a_native_round_trip() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]})); + let out = svg(&mut s); + assert!(out.contains("", "replace": "Glow"})), + ("svgFilter.delete", json!({"name": "Glow"})), ("svgFilter.delete", json!({"name": ["a"]})), ( "effect.apply", diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index e801df4a7a..12c652061f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1234,7 +1234,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.svgFilterDialog", "Apply SVG Filter…", "", - "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file", + "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's defaults (the document's filter of a default's name in its place) and then the document's other filters; OK runs svgFilter.apply with selected, and with index and item for the applied effect; New and Edit open the code, Save runs svgFilter.define (replace: the filter edited, a default included), Delete runs svgFilter.delete (off for a default the document holds no copy of) and Import… svgFilter.import with a picked SVG file", ), ( "ui.importSvgFilter", diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index af6849de43..f092a55cc4 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -1,16 +1,22 @@ -//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the document's SVG filters in a -//! list. OK applies the selected one to the selection as a live effect (`svgFilter.apply`), or, -//! opened from the Appearance panel for an applied SVG filter, puts it in that effect's place -//! (`effect.setParams`). New and Edit open the filter's code under the list; Save adds the filter -//! or replaces the one being edited (`svgFilter.define`). Delete removes the selected filter -//! (`svgFilter.delete`) and Import… adds the filters of an SVG file (`svgFilter.import`). Those -//! act at once. Effect › SVG Filters lists the same filters below its first items. +//! Apply SVG Filter (Effect › SVG Filters › Apply SVG Filter…): the default SVG filters and the +//! document's own in a list, the defaults first. OK applies the selected one to the selection as a +//! live effect, or, opened from the Appearance panel for an applied SVG filter, puts it in that +//! effect's place (`svgFilter.apply`, with `index`). New and Edit open the filter's code under the +//! list; Save adds the filter or replaces the one being edited (`svgFilter.define`). Delete +//! removes the selected filter (`svgFilter.delete`) and Import… adds the filters of an SVG file +//! (`svgFilter.import`). Those act at once. Effect › SVG Filters lists the same filters below its +//! first items. +//! +//! A default is not in the document until it is applied or edited: the document then holds a copy +//! under the default's name, which is listed in the default's place. Delete is off for a default +//! the document holds no copy of. //! //! Fields: `selected` (a filter's name), `code` (the code being edited), `editing` (`""`, `"new"` //! or the name of the filter being edited), and with an applied effect `__index`, `__item` and //! `missing` (the name of a deleted filter the effect names). use serde_json::{Value, json}; +use vectorcraft_effects::svg_filter::defaults::{DEFAULT_FILTERS, Listed, default_filter, listed}; use vectorcraft_engine::doc::SvgFilter; use super::DialogSpec; @@ -25,20 +31,21 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Apply SVG Filter…").trim_end_matches('…').to_string(), body, confirm, - ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).iter().any(|f| f.name == d.str("selected"))), + ok_enabled: Some(|app, d| d.str("editing").is_empty() && filters(app).0.iter().any(|f| f.filter.name == d.str("selected"))), min_width: 440.0, ..DialogSpec::FORM }; -/// The active document's SVG filters. -fn filters(app: &VectorcraftApp) -> Vec { - app.session.active().map(|st| st.doc.svg_filters.clone()).unwrap_or_default() +/// The filters the dialog lists for the active document, and how many come first as the defaults. +fn filters(app: &VectorcraftApp) -> (Vec, usize) { + listed(app.session.active().map(|st| st.doc.svg_filters.as_slice()).unwrap_or_default()) } /// `ui.svgFilterDialog {index?, item?}`: open Apply SVG Filter for the active document; with /// `index`, for the applied SVG filter at `index` of `item` (null: the object's effects): the -/// document's filter of its name selected; when the document has none of its name, the name shown -/// above the list if the filter was deleted, or else its code open as a new filter. +/// document's filter of its name selected, or the default of its name when the effect draws with +/// the default's code or with nothing; when neither has its name, the name shown above the list if +/// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if app.session.active().is_none() { return Err("no document open".into()); @@ -53,17 +60,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let e = applied.get(k as usize).filter(|e| e.id == vectorcraft_effects::SVG_FILTER).ok_or_else(|| format!("no SVG filter at index {k}"))?; let name = e.params.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); let xml = e.params.get("xml").and_then(Value::as_str).unwrap_or_default().to_string(); - let held = filters(app).into_iter().find(|f| f.name == name); - match held { - // The document's filter it names: selected. - Some(_) => fields["selected"] = json!(name), + let held = app.session.active().is_some_and(|st| st.doc.svg_filters.iter().any(|f| f.name == name)); + // A default the document holds no copy of, when the effect draws with its code or with nothing. + let default = default_filter(&name).is_some_and(|d| xml.is_empty() || xml == d.xml); + if held || default { + // The filter it names: selected. + fields["selected"] = json!(name); + } else if xml.is_empty() { // Deleted from the document: shown above the list, not selectable; OK waits for a choice. - None if xml.is_empty() => fields["missing"] = json!(name), + fields["missing"] = json!(name); + } else { // A filter the document doesn't hold (from an opened file): its code, to add it. - None => { - fields["code"] = json!(xml); - fields["editing"] = json!("new"); - } + fields["code"] = json!(xml); + fields["editing"] = json!("new"); } fields["__index"] = json!(k); // As given: `null` is the object's own effects, and none is the active item's. @@ -75,33 +84,39 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// OK: the selected filter to the selection, or in the applied effect's place. +/// OK: the selected filter to the selection, or in the applied effect's place. A default the +/// document holds no copy of is copied into it in the same undo step. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let name = d.str("selected"); - let f = filters(app).into_iter().find(|f| f.name == name).ok_or("select an SVG filter")?; - let r = match d.fields.get("__index").and_then(Value::as_u64) { - Some(k) => { - let mut p = json!({ "index": k, "params": { "name": f.name, "xml": f.xml } }); - if let Some(item) = d.fields.get("__item") { - p["item"] = item.clone(); - } - app.run("effect.setParams", p)? + let f = filters(app).0.into_iter().find(|f| f.filter.name == name).ok_or("select an SVG filter")?; + let mut p = json!({ "name": f.filter.name }); + if let Some(k) = d.fields.get("__index").and_then(Value::as_u64) { + p["index"] = json!(k); + if let Some(item) = d.fields.get("__item") { + p["item"] = item.clone(); } - None => app.run("svgFilter.apply", json!({ "name": f.name }))?, - }; + } + let r = app.run("svgFilter.apply", p)?; app.ui.dialog = None; Ok(r) } -/// The active document's filter names, mirrored for the (static) menu tree ([`sync`]). +/// The names of the active document's filters that are not a default's, mirrored for the (static) +/// menu tree ([`sync`]). fn names_store() -> &'static std::sync::RwLock> { static NAMES: std::sync::OnceLock>> = std::sync::OnceLock::new(); NAMES.get_or_init(Default::default) } -/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). +/// The names of `held`, a document's filters, that are not a default's, in their order. +fn own_names(held: &[SvgFilter]) -> Vec { + held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| f.name.clone()).collect() +} + +/// Mirror the active document's SVG filter names for the menu tree (cheap when unchanged). A +/// filter with a default's name is the menu's entry of that name already. pub fn sync(app: &VectorcraftApp) { - let names: Vec = app.session.active().map(|st| st.doc.svg_filters.iter().map(|f| f.name.clone()).collect()).unwrap_or_default(); + let names: Vec = app.session.active().map(|st| own_names(&st.doc.svg_filters)).unwrap_or_default(); let same = names_store().read().map(|v| v.len() == names.len() && v.iter().zip(&names).all(|(a, b)| *a == b)).unwrap_or(true); if !same { if let Ok(mut v) = names_store().write() { @@ -111,20 +126,23 @@ pub fn sync(app: &VectorcraftApp) { } } -/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter… and then the active document's -/// filters, each applying itself to the selection. +/// Effect › SVG Filters: Apply SVG Filter…, Import SVG Filter…, the default filters and then the +/// active document's other filters, each applying itself to the selection. pub fn menu_items() -> Vec { items_for(names_store().read().map(|v| v.clone()).unwrap_or_default()) } -/// [`menu_items`] for filters named `names`. +/// [`menu_items`] for a document whose filters that are not a default's are named `names`. fn items_for(names: Vec<&'static str>) -> Vec { use crate::menus::Item; + let apply = |n: &'static str| Item::Cmd(n, "svgFilter.apply", json!({ "name": n })); let mut v = vec![Item::Cmd("Apply SVG Filter…", "ui.svgFilterDialog", Value::Null), Item::Cmd("Import SVG Filter…", "ui.importSvgFilter", Value::Null)]; + v.push(Item::Sep); + v.extend(DEFAULT_FILTERS.iter().map(|d| apply(d.name))); if !names.is_empty() { v.push(Item::Sep); - v.extend(names.into_iter().map(|n| Item::Cmd(n, "svgFilter.apply", json!({ "name": n })))); + v.extend(names.into_iter().map(apply)); } v } @@ -170,7 +188,8 @@ enum Action { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let list = filters(app); + let (list, defaults) = filters(app); + let held = list.iter().filter(|f| !f.default).count(); let selected = d.str("selected"); let editing = d.str("editing"); let mut act = None; @@ -184,7 +203,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if !missing.is_empty() { ui.add_enabled_ui(false, |ui| ui.selectable_label(false, missing.as_str())); } - for f in &list { + for (i, Listed { filter: f, .. }) in list.iter().enumerate() { + // The document's other filters follow the defaults, below a line. + if i == defaults && i > 0 { + ui.separator(); + } let r = ui.selectable_label(f.name == selected, f.name.as_str()); if r.double_clicked() && editing.is_empty() { act = Some(Action::Edit(f.name.clone())); @@ -195,17 +218,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); }); ui.add_space(6.0); - let has = list.iter().any(|f| f.name == selected); + let chosen = list.iter().find(|f| f.filter.name == selected); + let has = chosen.is_some(); + // A default the document holds no copy of has nothing to delete. + let deletable = chosen.is_some_and(|f| !f.default); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; let idle = editing.is_empty(); - if ui.add_enabled_ui(idle && list.len() < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() { + if ui.add_enabled_ui(idle && held < SvgFilter::MAX, |ui| widgets::flat_button(ui, tl!("New"), 64.0)).inner.clicked() { act = Some(Action::New); } if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Edit"), 64.0)).inner.clicked() { act = Some(Action::Edit(selected.clone())); } - if ui.add_enabled_ui(idle && has, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() { + if ui.add_enabled_ui(idle && deletable, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() { act = Some(Action::Delete); } if crate::picks::can(app, &PickRequest::Open(pick())) @@ -245,7 +271,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { Ok(()) } Some(Action::Edit(name)) => { - if let Some(f) = list.iter().find(|f| f.name == name) { + if let Some(f) = list.iter().map(|f| &f.filter).find(|f| f.name == name) { d.fields.insert("selected".into(), json!(f.name)); d.fields.insert("editing".into(), json!(f.name)); d.fields.insert("code".into(), json!(f.xml)); @@ -322,7 +348,9 @@ mod tests { crate::menus::invoke(&mut app, "ui.svgFilterDialog", json!({})); let mut d = app.ui.dialog.clone().unwrap(); assert_eq!(d.kind, KIND); - assert!(frame(&mut app, &mut d).iter().any(|t| t == "Shift"), "the filter's name, as it is"); + // Below the defaults, which fill the rows the list shows at first. + assert_eq!(filters(&app).0.last().map(|f| f.filter.name.as_str()), Some("Shift"), "the filter's name, as it is"); + assert!(!frame(&mut app, &mut d).is_empty()); assert!(!(SPEC.ok_enabled.unwrap())(&app, &d), "nothing selected"); d.fields.insert("selected".into(), json!("Shift")); assert!((SPEC.ok_enabled.unwrap())(&app, &d)); @@ -411,11 +439,30 @@ mod tests { use crate::menus::Item; let ids = |items: &[Item]| items.iter().map(|i| if let Item::Cmd(l, c, p) = i { format!("{l} {c} {p}") } else { "—".into() }).collect::>(); - assert_eq!(ids(&items_for(vec![])), ["Apply SVG Filter… ui.svgFilterDialog null", "Import SVG Filter… ui.importSvgFilter null"]); + // The defaults follow the commands in every document, and with no document. + let plain = ids(&items_for(vec![])); assert_eq!( - ids(&items_for(vec!["Shift", "A (1)"]))[2..], - ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"] + plain[..4], + [ + "Apply SVG Filter… ui.svgFilterDialog null", + "Import SVG Filter… ui.importSvgFilter null", + "—", + "Soft Blur svgFilter.apply {\"name\":\"Soft Blur\"}" + ] ); + assert_eq!(plain.len(), 3 + DEFAULT_FILTERS.len()); + assert_eq!(plain.last().map(String::as_str), Some("Hue Shift svgFilter.apply {\"name\":\"Hue Shift\"}")); + // The document's other filters come below them. + let with = ids(&items_for(vec!["Shift", "A (1)"])); + assert_eq!(with[..plain.len()], plain[..]); + assert_eq!(with[plain.len()..], ["—", "Shift svgFilter.apply {\"name\":\"Shift\"}", "A (1) svgFilter.apply {\"name\":\"A (1)\"}"]); + // A document's filter with a default's name is that default's entry. + let held = [ + SvgFilter { name: "Glow".into(), xml: String::new() }, + SvgFilter { name: "Shift".into(), xml: String::new() }, + SvgFilter { name: "glow".into(), xml: String::new() }, + ]; + assert_eq!(own_names(&held), ["Shift", "glow"]); let mut app = app(); assert!(!crate::menus::enabled(&app, "svgFilter.apply"), "nothing selected"); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); @@ -423,6 +470,88 @@ mod tests { assert_eq!(crate::menus::display_label(&app, "svgFilter.apply", "Shift"), "Shift", "a filter's name as it is"); } + /// The steps in the active document's undo history. + fn steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + #[test] + fn a_default_is_listed_first_and_ok_copies_it_into_the_document() { + let mut app = app(); + app.session.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + open(&mut app, &json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let (list, defaults) = filters(&app); + let names: Vec<&str> = list.iter().map(|f| f.filter.name.as_str()).collect(); + assert_eq!((defaults, names.len()), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len() + 1)); + assert_eq!((names[0], names[defaults - 1], names[defaults]), ("Soft Blur", "Hue Shift", "Shift"), "the defaults, then the document's own"); + assert!(frame(&mut app, &mut d).iter().any(|t| t == "Soft Blur"), "a default's name, as it is"); + d.fields.insert("selected".into(), json!("Soft Shadow")); + assert!((SPEC.ok_enabled.unwrap())(&app, &d), "a default can be applied"); + let before = steps(&app); + confirm(&mut app, &d).unwrap(); + assert_eq!(steps(&app), before + 1, "one undo step"); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.svg_filters.iter().map(|f| f.name.as_str()).collect::>(), ["Shift", "Soft Shadow"]); + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Soft Shadow"))); + assert_eq!(fx[0].params["xml"].as_str(), default_filter("Soft Shadow").map(|f| f.xml)); + // Opened for that effect, the document's copy is selected; OK with another default puts it + // in the effect's place and copies it, in one step. + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("selected").as_str(), d.str("editing").as_str()), ("Soft Shadow", "")); + d.fields.insert("selected".into(), json!("Invert")); + let before = steps(&app); + confirm(&mut app, &d).unwrap(); + assert_eq!(steps(&app), before + 1); + let doc = &app.session.active().unwrap().doc; + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!((fx.len(), fx[0].params["name"].as_str()), (1, Some("Invert")), "in its place, not added"); + assert_eq!(doc.svg_filters.len(), 3); + } + + /// Edit on a default opens its code, and Save keeps the edited copy in the document under the + /// default's name; an effect that names a default the document no longer holds selects it. + #[test] + fn an_edited_default_is_saved_in_the_document() { + let mut app = app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // Save, as its button does for the default being edited. + let edited = r#""#; + let r = app.run("svgFilter.define", json!({"xml": edited, "replace": "Thin"})).unwrap(); + assert_eq!(r["name"], "Thin"); + assert_eq!(filters(&app).0.iter().filter(|f| !f.default).map(|f| f.filter.xml.as_str()).collect::>(), [edited]); + assert_eq!(filters(&app).0.len(), DEFAULT_FILTERS.len(), "in the default's place"); + app.session.execute("svgFilter.apply", &json!({"name": "Thin"})).unwrap(); + // Deleted: the default is listed again, and the effect that names it selects the default. + app.session.execute("svgFilter.delete", &json!({"name": "Thin"})).unwrap(); + assert!(filters(&app).0.iter().all(|f| f.default)); + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("selected").as_str(), d.str("missing").as_str(), d.str("editing").as_str()), ("Thin", "", "")); + confirm(&mut app, &d).unwrap(); + let doc = &app.session.active().unwrap().doc; + let fx = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects; + assert_eq!(fx[0].params["xml"].as_str(), default_filter("Thin").map(|f| f.xml), "the default again"); + // An applied filter with a default's name and other code opens as code to save. + let e = vectorcraft_doc::Effect { + id: "svg.filter".into(), + params: json!({"name": "Glow", "xml": ""}), + visible: true, + }; + app.session + .edit("Plant", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects = vec![e]; + Ok(()) + }) + .unwrap(); + app.run("effect.dialog", json!({"effect": "svg.filter", "index": 0, "item": null})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.str("editing").as_str(), d.str("selected").as_str()), ("new", "")); + } + #[test] fn new_saves_the_code_and_selects_the_filter() { let mut app = app(); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d43d17220c..57a08e8ce0 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1235,7 +1235,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.svgFilterDialog", "Apply SVG Filter…", "", - "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file", + "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's defaults (the document's filter of a default's name in its place) and then the document's other filters; OK runs svgFilter.apply with selected, and with index and item for the applied effect; New and Edit open the code, Save runs svgFilter.define (replace: the filter edited, a default included), Delete runs svgFilter.delete (off for a default the document holds no copy of) and Import… svgFilter.import with a picked SVG file", ), ( "ui.importSvgFilter", diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 1457e35bc6..342a5171b6 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -27,7 +27,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | | Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | -| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists the document's own filters: VectorCraft ships no default filters. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | +| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning | | Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers diff --git a/docs/mcp.md b/docs/mcp.md index 37ffd74300..e77c63da33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5172,8 +5172,19 @@ it. The native format keeps the events and the files. ## SVG filters -Effect › SVG Filters lists the document's SVG filters below Apply SVG Filter… and Import SVG Filter…; choosing one -applies it to the selection. `svgFilter.list {}` returns them as `filters: [{name, xml}]`. Each is one `` +Effect › SVG Filters lists the default SVG filters and then the document's other filters below Apply SVG Filter… and +Import SVG Filter…; choosing one applies it to the selection +([apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html)). +The 14 defaults are VectorCraft's own set, written with [SVG 1.1 filter primitives](https://www.w3.org/TR/SVG11/filters.html): +Soft Blur, Heavy Blur, Soft Shadow, Hard Shadow, Glow, Bevel, Emboss, Thicken, Thin, Rough Edges, Grain, Grayscale, +Invert and Hue Shift. Every document lists them, and a document holds none of them until one is applied or edited +there. `svgFilter.apply` with a default's name copies the default into the document in the same undo step (refused +when the document already holds 64 filters), and `svgFilter.define` with `replace` naming a default adds the edited +copy under that name (code equal to the default's adds nothing). The document's filter of a default's name is then +listed in the default's place. `svgFilter.delete` refuses a default the document holds no copy of; deleting the copy +lists the default again, and applying the default again makes the effects that still name it draw with it. +`svgFilter.list {}` returns the document's filters as `filters: [{name, xml}]` and the defaults as +`defaults: [{name, xml, inDocument}]`. Each filter is one `` element whose `id` is its name, with 1 to 64 primitives and at most 64 KB of XML (`feTurbulence` octaves up to 10, `feConvolveMatrix` kernels up to 9 cells a side, `feMorphology` radii and `kernelUnitLength` up to 100 and `stdDeviation` up to 500 user units, elements nested at most 16 deep). It holds only filter primitives, @@ -5184,8 +5195,9 @@ a filter after the others, or with `replace` replaces the filter of that name, w filter has is refused, and the same filter again records no undo step. `svgFilter.delete {name}` removes one, and `svgFilter.import {path?|svg?}` adds the `` elements of an SVG file (at most 16 MB, not SVGZ, the first 256 filters) or of SVG text, leaving out the names the document already has and the filters `svgFilter.define` would refuse (`{added, skipped}`). Each change is one undo -step. `svgFilter.apply {name, ids?|id?, item?}` applies one as the live effect `svg.filter`, as `effect.apply` does, -in one undo step. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes +step. `svgFilter.apply {name, ids?|id?, item?, index?}` applies one as the live effect `svg.filter`, as `effect.apply` does, +in one undo step; with `index` it puts the filter in the place of the applied `svg.filter` effect at that index of +`item`, as `effect.setParams` does, and an index that is not an applied SVG filter is an error. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes what every object that uses it draws, in the edit's one undo step, and an application after an edit takes the edited filter. Deleting a filter that objects use leaves their effects in place, still named, drawing nothing (their `xml` empty) until a filter of that name is defined or imported again. A pasted effect that names one of the document's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9ba8866a8c..ecfafece5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1920,7 +1920,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`). - **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html). - **Rasterize colour models:** Object › Rasterize with the Grayscale colour model makes a grayscale image (a gray PNG, with alpha over a transparent background), and with Bitmap a 1-bit image (a TIFF), or a black-and-white gray PNG with alpha over a transparent background; `image.info` and the Control bar say Grayscale, and a fill color colorizes the image, in RGB and CMYK documents (#6969). Expand Appearance and PDF export of a Rasterize effect make the same images. Regression coverage: `rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image` (`crates/engine/src/tests/rastersettings.rs`) and `gray_and_bilevel_images_store_gray` (`crates/render/src/encode/tests.rs`). Scores and estimates unchanged. -- **SVG filters:** Effect › SVG Filters lists the document's own SVG filters below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). VectorCraft ships no default filters. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). +- **SVG filters:** Effect › SVG Filters lists 14 default SVG filters and then the document's own below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). The public page names no default set: the defaults (Soft Blur to Hue Shift, `crates/effects/src/svg_filter/defaults.rs`) are VectorCraft's own, written with SVG 1.1 primitives. A default is copied into the document when it is applied or edited, and Delete does not remove a default. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). - **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames. From a067279ee9fca3a969be1b33e8c231b5c5693ed9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:31:49 -0800 Subject: [PATCH 20/33] Docs: legacy .ai Insert Aki warning applies only to type written as text With outlineText the legacy .ai save writes the type as outlines, which keep the Insert Aki spacing, and does not warn that the values are left out. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 1d487c511e..60328627e6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8815,8 +8815,9 @@ justification keeps that width. Live SVG text places each character the space mo Insert Aki is written as outlines. An SVG saved without Preserve Editing (`preserveEditing`) reopens without the Insert Aki values; save it with Preserve Editing to keep them editable. An `.ai` file's text document keeps both values, and opening the file reads them back. The stored values are read in thousandths of an em and a negative -value opens as 0; these are VectorCraft's own rules. A legacy `.ai` save writes type with Insert Aki as text without the values and warns that they are left -out. +value opens as 0; these are VectorCraft's own rules. When a legacy `.ai` save writes type as text, it writes type with +Insert Aki without the values and warns that they are left out. With `outlineText: true` it writes the type as outlines, +which keep the space Insert Aki adds, and does not warn that the values are left out. ```json {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"akiRight":500}}} From 15867198980a09e6f294901515104e3858b27b0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:47:23 -0800 Subject: [PATCH 21/33] Tests: Insert Aki fixture sets kinsoku_sets main added Texts::kinsoku_sets; the a_run_keeps_its_insert_aki fixture now sets it to an empty list, as the other Texts fixtures do. --- crates/eps/src/import/ate.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 8e9bbe96c1..a45c203d75 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -1958,6 +1958,7 @@ mod tests { para_sheets: vec![], frames: vec![], patterns: HashMap::new(), + kinsoku_sets: vec![], }; let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| { let s = texts(defaults, normal).style(Some(&read(run).unwrap())); From 025711215832ffbdc079c523da8fef4dacc34ae9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:16:35 -0800 Subject: [PATCH 22/33] TIFF: JPEG strips larger than their strip and oversized strip tables are refused before decoding oversized_tiff now also refuses a TIFF whose JPEG-compressed strip or tile (Compression 7) declares a frame wider or taller than the strip or tile, one with more than MAX_TIFF_CHUNKS strips or tiles, and one whose JPEG headers take more than 16,777,216 steps to read. It reads BigTIFF directories, follows the layout and the repeated tags the decoder reads, and refuses offsets of types it does not read. --- crates/doc/src/cmyk.rs | 503 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 466 insertions(+), 37 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 8cd3f85a4f..77454f64a1 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -56,19 +56,114 @@ fn is_tiff(bytes: &[u8]) -> bool { bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") } -/// The width and height of the first image of TIFF `bytes` when it has more strips or tiles than -/// the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles per plane -/// times planes past `usize::MAX`. A file that stores one plane per channel (PlanarConfiguration 2) -/// has a plane for each channel; other files have one. The decoder multiplies these counts without -/// a check, which panics where overflow checks are on. Such an image, when it is at least a pixel -/// wide, claims at least 2^32 samples. -/// Where a tag repeats, the value giving the most strips or tiles counts. `None` for other images +/// What [`jpeg_frames`] found in a JPEG's headers. +enum Frames { + /// Every frame header declares a size the check accepts, or there is none. + Fit, + /// The width and height of the first frame header the check refuses. + Misfit(u16, u16), + /// The steps ran past [`MAX_JPEG_HEADER_STEPS`]. + OverBudget, +} + +/// Checks the width and height each 8-bit baseline, extended or progressive frame header in the +/// headers of a JPEG declares with `fits`. The JPEG is the bytes after its start-of-image marker: +/// `parts[0]` followed by `parts[1]`. The headers are read as the decoder reads them, up to the +/// first start-of-scan or end-of-image marker: every other marker is followed by its segment's +/// length, and bytes between segments are passed over, as are fill bytes (0xFF, and 0x00 after +/// one) before a marker. `steps` counts each byte looked at and each segment passed over. +fn jpeg_frames(parts: [&[u8]; 2], steps: &mut u64, fits: impl Fn(u16, u16) -> bool) -> Frames { + let byte = |i: usize| match i.checked_sub(parts[0].len()) { + None => parts[0].get(i).copied(), + Some(j) => parts[1].get(j).copied(), + }; + let u16_at = |i: usize| Some(u16::from_be_bytes([byte(i)?, byte(i.checked_add(1)?)?])); + let mut p = 0usize; + loop { + *steps += 1; + if *steps > MAX_JPEG_HEADER_STEPS { + return Frames::OverBudget; + } + let Some(b) = byte(p) else { return Frames::Fit }; + p += 1; + if b != 0xFF { + continue; + } + while matches!(byte(p), Some(0xFF | 0)) { + p += 1; + *steps += 1; + if *steps > MAX_JPEG_HEADER_STEPS { + return Frames::OverBudget; + } + } + let Some(marker) = byte(p) else { return Frames::Fit }; + p += 1; + if matches!(marker, 0xDA | 0xD9) { + return Frames::Fit; + } + // Length (2 bytes), then for a frame header its precision, height and width. + let Some(len) = u16_at(p) else { return Frames::Fit }; + if matches!(marker, 0xC0..=0xC2) + && byte(p.saturating_add(2)) == Some(8) + && let (Some(h), Some(w)) = (u16_at(p.saturating_add(3)), u16_at(p.saturating_add(5))) + && !fits(w, h) + { + return Frames::Misfit(w, h); + } + if len < 2 { + return Frames::Fit; + } + p = p.saturating_add(usize::from(len)); + } +} + +/// Most strips or tiles the first image of a TIFF may have: VectorCraft's own limit, 1/1024 of +/// [`crate::MAX_RASTER_ALLOC`] (524,288 in the web app, 2,097,152 on the desktop). The decoder +/// reads an offset and a byte count of 8 bytes each for every one into memory before anything else. +pub const MAX_TIFF_CHUNKS: u64 = crate::MAX_RASTER_ALLOC / 1024; + +/// Most pixels the JPEG of a JPEG-compressed TIFF tile may declare when it declares more pixels +/// than the whole image has: VectorCraft's own limit (2048 × 2048, 16 MB as CMYK). +pub const MAX_JPEG_TILE_PIXELS: u64 = 1 << 22; + +/// Most steps reading the JPEG headers of a TIFF's strips or tiles may take (a byte looked at, a +/// segment passed over or a strip offset read): VectorCraft's own limit. +const MAX_JPEG_HEADER_STEPS: u64 = 1 << 24; + +/// The width and height of the first image of TIFF or BigTIFF `bytes` when it has more strips or +/// tiles than the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles +/// per plane times planes past `usize::MAX`. A file that stores one plane per channel +/// (PlanarConfiguration 2) has a plane for each channel; other files have one. The decoder +/// multiplies these counts without a check, which panics where overflow checks are on. Such an +/// image, when it is at least a pixel wide, claims at least 2^32 samples. +/// It also gives them for an image with more than [`MAX_TIFF_CHUNKS`] strips or tiles, counted from +/// its size or from the number of values its StripOffsets and StripByteCounts tags hold, or its +/// TileOffsets and TileByteCounts tags for a tiled image. An image the decoder reads as strips (it +/// has both strip tables and neither tile table) counts strips, and one it reads as tiles counts +/// tiles; the decoder refuses an image with any other mix of these tags before it reads a table. +/// For a JPEG-compressed image (Compression 7) it gives the width and height a strip's or tile's +/// JPEG declares in a frame header (in the JPEGTables, or in the strip or tile before its first +/// scan) when they are wider or taller than the strip or tile, or, for a tile, when they make more +/// than [`MAX_JPEG_TILE_PIXELS`] pixels and more than the image has. The decoder allocates the +/// pixels the JPEG declares. It gives the image's width and height when reading those headers +/// takes more than 16,777,216 steps (a byte looked at, a segment passed over or a strip offset +/// read), when the strip or tile offsets are of a type other than BYTE, UNDEFINED, SHORT, LONG, +/// IFD, LONG8 or IFD8, and when the image's width and height, a striped image's RowsPerStrip or a +/// tiled image's tile size isn't a single value of one of those types. +/// Where a tag repeats, the value giving the most strips or tiles counts, and the JPEG check uses +/// the last entry of a field type the decoder knows, as the decoder does. `None` for other images /// and for bytes that aren't a TIFF. pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { - let le = bytes.starts_with(b"II*\0"); - if !le && !bytes.starts_with(b"MM\0*") { + let le = bytes.starts_with(b"II"); + let head = bytes.get(..4)?; + // A BigTIFF counts and points with 8 bytes where a TIFF uses 4, so its entries are 20 bytes. + let big = if head == b"II*\0" || head == b"MM\0*" { + false + } else if head == b"II+\0" || head == b"MM\0+" { + true + } else { return None; - } + }; let u16_at = |at: usize| -> Option { let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?; Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) @@ -77,32 +172,71 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) }; - let ifd = usize::try_from(u32_at(4)?).ok()?; - // (tag, the entry's single BYTE, SHORT, LONG or IFD value, which sits in the entry, or its - // single LONG8 or IFD8 value that fits in 32 bits, which sits where the entry points) - let entry = |i: usize| -> Option<(u16, Option)> { - let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?; - let (ty, count, at) = (u16_at(e.checked_add(2)?)?, u32_at(e.checked_add(4)?)?, e.checked_add(8)?); - let value = match (ty, count) { - (1, 1) => bytes.get(at).map(|&b| u32::from(b)), - (3, 1) => u16_at(at).map(u32::from), - (4 | 13, 1) => u32_at(at), - (16 | 18, 1) => { - let at = usize::try_from(u32_at(at)?).ok()?; - let (lo, hi) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); - let wide = if le { u64::from(hi) << 32 | u64::from(lo) } else { u64::from(lo) << 32 | u64::from(hi) }; - u32::try_from(wide).ok() - } + let u64_at = |at: usize| -> Option { + let b: [u8; 8] = bytes.get(at..at.checked_add(8)?)?.try_into().ok()?; + Some(if le { u64::from_le_bytes(b) } else { u64::from_be_bytes(b) }) + }; + let word_len: usize = if big { 8 } else { 4 }; + let word = |at: usize| if big { u64_at(at) } else { u32_at(at).map(u64::from) }; + // The bytes one value of each field type takes; 0 for types the decoder doesn't know. + let width_of = |ty: u16| -> usize { + match ty { + 1 | 2 | 6 | 7 => 1, + 3 | 8 => 2, + 4 | 9 | 11 | 13 => 4, + 5 | 10 | 12 | 16..=18 => 8, + _ => 0, + } + }; + let ifd = usize::try_from(word(if big { 8 } else { 4 })?).ok()?; + let entries = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) }; + let first = ifd.checked_add(if big { 8 } else { 2 })?; + // (tag, field type, number of values, where the values are: in the entry when they fit in its + // last word, otherwise where that word points) + let entry = |i: usize| -> Option<(u16, u16, u64, Option)> { + let e = first.checked_add(i.checked_mul(4 + 2 * word_len)?)?; + let (tag, ty, count) = (u16_at(e)?, u16_at(e.checked_add(2)?)?, word(e.checked_add(4)?)?); + let at = e.checked_add(4 + word_len)?; + let fits = u64::try_from(width_of(ty)).ok()?.checked_mul(count).is_some_and(|n| n <= word_len as u64); + let values = if fits { Some(at) } else { word(at).and_then(|p| usize::try_from(p).ok()) }; + Some((tag, ty, count, values)) + }; + // Value `i` of an entry's BYTE, UNDEFINED, SHORT, LONG, IFD, LONG8 or IFD8 values at `at`. + let nth = |ty: u16, at: usize, i: u64| -> Option { + let p = at.checked_add(usize::try_from(i).ok()?.checked_mul(width_of(ty))?)?; + match ty { + 1 | 7 => bytes.get(p).map(|&b| u64::from(b)), + 3 => u16_at(p).map(u64::from), + 4 | 13 => u32_at(p).map(u64::from), + 16 | 18 => u64_at(p), _ => None, - }; - Some((u16_at(e)?, value)) + } }; let (mut width, mut height, mut planes, mut planar) = (0u32, 0u32, 1u32, false); let (mut rows, mut tile_w, mut tile_h) = (None::, None::, None::); + // The most values a strip table and a tile table hold. + let (mut strip_chunks, mut tile_chunks) = (0u64, 0u64); + // The decoder keeps the last entry of a tag whose field type it knows. These are the last such + // entries (type, count, where) of the tags `LAST` lists. + const LAST: [u16; 11] = [256, 257, 259, 278, 322, 323, 273, 279, 324, 325, 347]; + let mut last = [None::<(u16, u64, Option)>; LAST.len()]; let least = |was: Option, v: u32| Some(was.map_or(v, |w| w.min(v))); - for i in 0..usize::from(u16_at(ifd)?) { - let Some((tag, value)) = entry(i) else { break }; - let Some(v) = value else { continue }; + // The entry's single BYTE, UNDEFINED, SHORT, LONG or IFD value, or its single LONG8 or IFD8 + // value when that fits in 32 bits. + let single = |ty: u16, count: u64, at: Option| at.filter(|_| count == 1).and_then(|at| nth(ty, at, 0)).and_then(|v| u32::try_from(v).ok()); + for i in 0..usize::try_from(entries).unwrap_or(usize::MAX) { + let Some((tag, ty, count, at)) = entry(i) else { break }; + match tag { + 273 | 279 => strip_chunks = strip_chunks.max(count), + 324 | 325 => tile_chunks = tile_chunks.max(count), + _ => {} + } + if width_of(ty) > 0 + && let Some(slot) = LAST.iter().position(|&t| t == tag).and_then(|k| last.get_mut(k)) + { + *slot = Some((ty, count, at)); + } + let Some(v) = single(ty, count, at) else { continue }; match tag { 256 => width = width.max(v), 257 => height = height.max(v), @@ -115,13 +249,87 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { } } let planes = if planar { u128::from(planes) } else { 1 }; - let tiles = match (tile_w, tile_h) { - (Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes > usize::MAX as u128, - _ => false, + let tiled = match (tile_w, tile_h) { + (Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes, + _ => 0, }; + let tiles = tiled > usize::MAX as u128; let rows = rows.unwrap_or(height); - let strips = rows > 0 && u128::from(height.saturating_sub(1) / rows + 1) * planes > u128::from(u32::MAX); - (tiles || strips).then_some((width, height)) + let striped = height.saturating_sub(1).checked_div(rows).map_or(0, |n| u128::from(n + 1) * planes); + let strips = striped > u128::from(u32::MAX); + if tiles || strips { + return Some((width, height)); + } + let last_of = |tag: u16| LAST.iter().position(|&t| t == tag).and_then(|k| last.get(k).copied().flatten()); + // The single value the decoder reads from the last entry of `tag`: `None` without one, and + // `Some(None)` when that entry doesn't hold a single value read here. + let value_of = |tag: u16| last_of(tag).map(|(ty, count, at)| single(ty, count, at)); + // The decoder reads strips when the image has both strip tables and neither tile table, tiles + // in the opposite case, and refuses every other image before it reads a table. + let layout = match [273, 279, 324, 325].map(|tag| last_of(tag).is_some()) { + [true, true, false, false] => Some((273, striped.max(u128::from(strip_chunks)))), + [false, false, true, true] => Some((324, tiled.max(u128::from(tile_chunks)))), + _ => None, + }; + let (offsets_tag, chunks) = layout?; + if chunks > u128::from(MAX_TIFF_CHUNKS) { + return Some((width, height)); + } + if value_of(259) != Some(Some(7)) { + return None; + } + // The JPEG check uses the sizes the decoder reads. A size it needs that isn't a single value + // read here refuses the image. + let (Some(Some(w_img)), Some(Some(h_img))) = (value_of(256), value_of(257)) else { return Some((width, height)) }; + let tile = offsets_tag == 324; + // RowsPerStrip, which the decoder reads only for strips. + let rows = if tile { Some(h_img) } else { value_of(278).unwrap_or(Some(h_img)) }; + let Some(rows) = rows else { return Some((width, height)) }; + let (tw, th) = match (value_of(322).flatten(), value_of(323).flatten()) { + (Some(tw), Some(th)) => (tw, th), + _ if tile => return Some((width, height)), + _ => (0, 0), + }; + // A strip is as wide as the image and RowsPerStrip tall (at most the image's height); a tile's + // JPEG may be as large as the tile, which the edge tiles of the image overhang. + let fits = |w: u16, h: u16| { + let (w, h) = (u32::from(w), u32::from(h)); + if tile { + let pixels = u64::from(w) * u64::from(h); + w <= tw && h <= th && (pixels <= MAX_JPEG_TILE_PIXELS || pixels <= u64::from(w_img) * u64::from(h_img)) + } else { + w <= w_img && h <= rows.min(h_img) + } + }; + // The decoder reads the JPEGTables after their start-of-image marker and without their last two + // bytes, followed by each strip or tile after its first two bytes; without JPEGTables, each + // strip or tile after its start-of-image marker. + let tables = last_of(347) + .and_then(|(_, count, at)| { + let at = at?; + let end = at.checked_add(usize::try_from(count).ok()?)?.min(bytes.len()); + bytes.get(at.checked_add(2)?..end.checked_sub(2)?) + }) + .unwrap_or_default(); + let (ty, count, at) = last_of(offsets_tag)?; + let at = at?; + // The decoder also takes offsets of other types (a RATIONAL or ASCII value), which aren't read + // here: such an image is refused. + if !matches!(ty, 1 | 3 | 4 | 7 | 13 | 16 | 18) { + return Some((width, height)); + } + let mut steps = 0u64; + for i in 0..count { + steps += 1; + let Some(at) = nth(ty, at, i).and_then(|o| usize::try_from(o).ok()) else { break }; + let part = bytes.get(at.saturating_add(2)..).unwrap_or_default(); + match jpeg_frames([tables, part], &mut steps, fits) { + Frames::Fit => {} + Frames::Misfit(w, h) => return Some((u32::from(w), u32::from(h))), + Frames::OverBudget => return Some((width, height)), + } + } + None } /// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. @@ -891,7 +1099,7 @@ mod tests { f }; assert_eq!(oversized_tiff(&header(2)), Some((u32::MAX, u32::MAX))); - assert_eq!(oversized_tiff(&header(1)), None, "one plane: (2^32 − 1)² tiles can be counted in 64 bits"); + assert_eq!(oversized_tiff(&header(1)), Some((u32::MAX, u32::MAX)), "one plane: countable, but past MAX_TIFF_CHUNKS"); assert!(tiff(&header(2)).is_none(), "not decoded"); } @@ -933,6 +1141,227 @@ mod tests { } } + /// A little-endian TIFF, or BigTIFF when `big`, holding `data` right after its header (from + /// byte 8, or 16 in a BigTIFF), then one directory of `entries` (tag, field type, values). An + /// entry's values sit in the entry when they fit, otherwise after the directory. + fn tiff_file(big: bool, entries: &[(u16, u16, Vec)], data: &[u8]) -> Vec { + let (word, head) = if big { (8, 16) } else { (4, 8) }; + let put = |f: &mut Vec, v: u64, n: usize| f.extend(&v.to_le_bytes()[..n]); + let mut f = if big { b"II+\0\x08\0\0\0".to_vec() } else { b"II*\0".to_vec() }; + let ifd = head + data.len(); + put(&mut f, ifd as u64, word); + f.extend(data); + put(&mut f, entries.len() as u64, if big { 8 } else { 2 }); + let after = f.len() + entries.len() * (4 + 2 * word) + word; + let mut tail = vec![]; + for (tag, ty, values) in entries { + let width = match ty { + 1 | 7 => 1, + 3 => 2, + 4 => 4, + _ => 8, + }; + f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat()); + put(&mut f, values.len() as u64, word); + let mut v = vec![]; + for &x in values { + put(&mut v, x, width); + } + if v.len() <= word { + v.resize(word, 0); + f.extend(v); + } else { + put(&mut f, (after + tail.len()) as u64, word); + tail.extend(v); + } + } + put(&mut f, 0, word); + f.extend(tail); + f + } + + /// A JPEG of four components whose progressive frame header declares `w` × `h` pixels, with a + /// scan header and no scan data. + fn jpeg_header(w: u16, h: u16) -> Vec { + let mut j = vec![0xFF, 0xD8, 0xFF, 0xC2, 0, 20, 8]; + j.extend(h.to_be_bytes()); + j.extend(w.to_be_bytes()); + j.push(4); + for id in 1..=4 { + j.extend([id, 0x11, 0]); + } + j.extend([0xFF, 0xDA, 0, 14, 4, 1, 0, 2, 0, 3, 0, 4, 0, 0, 63, 0, 0xFF, 0xD9]); + j + } + + /// The directory of a 1 × 1 CMYK image with alpha, JPEG-compressed in one strip of `len` bytes + /// at byte `at`. + fn jpeg_strip_entries(at: u64, len: u64) -> Vec<(u16, u16, Vec)> { + vec![ + (256, 4, vec![1]), + (257, 4, vec![1]), + (258, 3, vec![8; 5]), + (259, 3, vec![7]), + (262, 3, vec![5]), + (273, 4, vec![at]), + (277, 3, vec![5]), + (278, 4, vec![1]), + (279, 4, vec![len]), + (338, 3, vec![2]), + ] + } + + /// A strip's JPEG that declares more pixels than the strip holds would have the decoder + /// allocate them: a 1 × 1 image whose JPEG claims 16384 × 16384 is refused before any decoder + /// opens it, in a TIFF or a BigTIFF, with fill bytes or other bytes before the frame header, + /// and with the frame header in the JPEGTables. + #[test] + fn a_jpeg_strip_declaring_more_than_its_strip_is_refused() { + let big = jpeg_header(16384, 16384); + let file = tiff_file(false, &jpeg_strip_entries(8, big.len() as u64), &big); + assert_eq!(oversized_tiff(&file), Some((16384, 16384))); + assert!(tiff(&file).is_none(), "not decoded"); + let bigtiff = tiff_file(true, &jpeg_strip_entries(16, big.len() as u64), &big); + assert_eq!(oversized_tiff(&bigtiff), Some((16384, 16384)), "BigTIFF"); + // The decoder reads the last ImageWidth and ImageLength: 1 × 1 after 16384 × 16384, in one + // strip without RowsPerStrip. + let mut entries = jpeg_strip_entries(8, big.len() as u64); + entries.retain(|e| e.0 != 278); + entries.splice(0..0, [(256, 4, vec![16384]), (257, 4, vec![16384])]); + assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some((16384, 16384)), "repeated sizes"); + // StripOffsets as a BYTE, which the decoder reads, and as a RATIONAL, which it reads as two + // offsets. + for (ty, expected) in [(1, (16384, 16384)), (5, (1, 1))] { + let mut entries = jpeg_strip_entries(8, big.len() as u64); + for e in &mut entries { + if e.0 == 273 { + e.1 = ty; + } + } + assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some(expected), "StripOffsets of type {ty}"); + } + let one = jpeg_header(1, 1); + assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, one.len() as u64), &one)), None, "a JPEG as large as its strip"); + let wide = jpeg_header(2, 1); + assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, wide.len() as u64), &wide)), Some((2, 1)), "one pixel too wide"); + for (what, prefix) in [("fill bytes", &[0xFF, 0x00, 0xFF][..]), ("other bytes", &[0x12, 0x34][..])] { + let mut j = big[..2].to_vec(); + j.extend(prefix); + j.extend(&big[2..]); + let file = tiff_file(false, &jpeg_strip_entries(8, j.len() as u64), &j); + assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "{what} before the frame header"); + } + // The JPEGTables hold the frame header; the strip holds only the scan. + let tables = [&big[..24], &[0xFF, 0xD9][..]].concat(); + let scan = [&[0xFF, 0xD8][..], &big[24..]].concat(); + let mut entries = jpeg_strip_entries(8 + tables.len() as u64, scan.len() as u64); + entries.push((347, 7, tables.iter().map(|&b| u64::from(b)).collect())); + let file = tiff_file(false, &entries, &[tables, scan].concat()); + assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "frame header in the JPEGTables"); + // An encoder's 8 × 8 RGB JPEG, with its own segments before the frame header, in an + // 8 × 8 image of one strip, and of strips 4 rows tall. + let mut real = Vec::new(); + image::codecs::jpeg::JpegEncoder::new(&mut real).encode(&[90; 8 * 8 * 3], 8, 8, image::ExtendedColorType::Rgb8).unwrap(); + let rgb = |rows: u64| { + let entries = [ + (256, 4, vec![8]), + (257, 4, vec![8]), + (258, 3, vec![8; 3]), + (259, 3, vec![7]), + (262, 3, vec![2]), + (273, 4, vec![8]), + (277, 3, vec![3]), + (278, 4, vec![rows]), + (279, 4, vec![real.len() as u64]), + ]; + oversized_tiff(&tiff_file(false, &entries, &real)) + }; + assert_eq!(rgb(8), None, "an encoder's JPEG as large as its strip"); + assert_eq!(rgb(4), Some((8, 8)), "an encoder's JPEG taller than its strip"); + } + + /// A tile's JPEG may be as large as the tile, which overhangs the image, and when it is more + /// than MAX_JPEG_TILE_PIXELS, no larger than the image. + #[test] + fn a_jpeg_tile_declaring_more_than_its_tile_is_refused() { + let tiled_with = |tile: u64, j: &[u8], rows: Vec| { + let mut entries: Vec<_> = jpeg_strip_entries(0, 0).into_iter().filter(|e| !matches!(e.0, 273 | 278 | 279)).collect(); + if !rows.is_empty() { + entries.push((278, 4, rows)); + } + entries.extend([(322, 4, vec![tile]), (323, 4, vec![tile]), (324, 4, vec![8]), (325, 4, vec![j.len() as u64])]); + oversized_tiff(&tiff_file(false, &entries, j)) + }; + let tiled = |tile: u64, j: &[u8]| tiled_with(tile, j, vec![]); + assert_eq!(tiled_with(16, &jpeg_header(16, 16), vec![1, 1]), None, "RowsPerStrip, unread in a tiled image"); + assert_eq!(tiled(16, &jpeg_header(16, 16)), None, "as large as the tile"); + assert_eq!(tiled(16, &jpeg_header(17, 16)), Some((17, 16)), "wider than the tile"); + assert_eq!(tiled(16, &jpeg_header(16, 17)), Some((16, 17)), "taller than the tile"); + assert_eq!(tiled(4096, &jpeg_header(2048, 2048)), None, "MAX_JPEG_TILE_PIXELS"); + assert_eq!(tiled(4096, &jpeg_header(2048, 2049)), Some((2048, 2049)), "past MAX_JPEG_TILE_PIXELS and the image"); + } + + /// The decoder reads every strip's offset and byte count before anything else: an image with + /// more than MAX_TIFF_CHUNKS strips, counted from its size or from its tables, is refused. + #[test] + fn tiffs_with_more_strips_than_their_tables_may_hold_are_refused() { + let file = |height: u64, count: u32| { + let entries = [ + (256, 4, vec![1]), + (257, 4, vec![height]), + (258, 3, vec![8]), + (262, 3, vec![1]), + (273, 4, vec![8]), + (278, 4, vec![1]), + (279, 4, vec![1]), + ]; + let mut f = tiff_file(false, &entries, &[0]); + // StripOffsets' count, its values left out of the file. + let at = 8 + 1 + 2 + 4 * 12 + 4; + f[at..at + 4].copy_from_slice(&count.to_le_bytes()); + f + }; + let most = MAX_TIFF_CHUNKS; + assert_eq!(oversized_tiff(&file(most, 1)), None, "MAX_TIFF_CHUNKS rows of a strip each"); + assert_eq!(oversized_tiff(&file(most + 1, 1)), Some((1, u32::try_from(most + 1).unwrap())), "one strip more"); + assert_eq!(oversized_tiff(&file(1, u32::try_from(most).unwrap())), None, "MAX_TIFF_CHUNKS offsets"); + assert_eq!(oversized_tiff(&file(1, u32::try_from(most + 1).unwrap())), Some((1, 1)), "one offset more"); + assert!(tiff(&file(1, 1 << 25)).is_none(), "not decoded"); + // Tile sizes without tile tables: the decoder reads the strips and never counts the + // 4,194,304 tiles of a pixel the sizes give. + let strips_with_tile_sizes = |offsets: Option| { + let mut entries = vec![ + (256, 4, vec![2048]), + (257, 4, vec![2048]), + (258, 3, vec![8]), + (262, 3, vec![1]), + (273, 4, vec![8]), + (279, 4, vec![2048 * 2048]), + (322, 4, vec![1]), + (323, 4, vec![1]), + ]; + entries.extend(offsets.map(|tag| (tag, 4, vec![8]))); + entries.sort_by_key(|e| e.0); + oversized_tiff(&tiff_file(false, &entries, &[0])) + }; + assert_eq!(strips_with_tile_sizes(None), None, "a strip image with tile sizes of one pixel"); + assert_eq!(strips_with_tile_sizes(Some(324)), None, "strip and tile tables: the decoder refuses it unread"); + } + + /// Strips whose JPEG headers take more than MAX_JPEG_HEADER_STEPS steps to read refuse the + /// file: here every strip points at the same 1 MB without a marker. + #[test] + fn jpeg_strips_that_take_too_long_to_read_are_refused() { + let file = |strips: u64| { + let mut entries = jpeg_strip_entries(0, 0); + entries.retain(|e| !matches!(e.0, 257 | 273 | 279)); + entries.extend([(257, 4, vec![strips]), (273, 4, vec![8; strips as usize]), (279, 4, vec![1 << 20; strips as usize])]); + tiff_file(false, &entries, &std::iter::repeat_n(0, 1 << 20).collect::>()) + }; + assert_eq!(oversized_tiff(&file(8)), None, "about 8 million steps"); + assert_eq!(oversized_tiff(&file(17)), Some((1, 17)), "about 17 million steps"); + } + fn inks() -> Inks { Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap() } From 9fb5abfbc6dab30a81516c28fac89fb8259b87fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:28:34 -0800 Subject: [PATCH 23/33] Export: hidden PDF layers place symbol art effects when a long page raises the version A PDF/A-2b export at PDF 1.4 with Create PDF Layers and a page longer than 14,400 pt is written as PDF 1.6, which has PDF layers. The export decided which layers place their instances' symbol art before it raised the version, so a hidden layer, written as a PDF layer that is off, kept its instances' art without the art's live effects. The version a long page needs is now settled before the document is baked. The pages come from the artboards, which baking leaves as they are. --- crates/pdf/src/export/entry.rs | 8 +++++--- crates/pdf/src/tests/layers.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 6cf8677269..00ac16a3fe 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -45,6 +45,11 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let set = &opts.settings; set.check()?; vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; + // The pages come from the artboards, which baking leaves as they are. The version a long page + // raises the file to decides whether the layers are written, so it is settled before baking. + let pages = pages(doc, opts)?; + let raised = for_long_pages(set, &pages)?; + let set = raised.as_ref().unwrap_or(set); // Live geometry effects export as their result, in symbols' art too; raster effects are // reported below. // Only the layers this export writes place their instances' art (see `ex.non_printing` and @@ -57,9 +62,6 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // Baking stops early when cancelled, leaving a half-baked copy that must not be written. vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let doc = baked.as_ref().unwrap_or(doc); - let pages = pages(doc, opts)?; - let raised = for_long_pages(set, &pages)?; - let set = raised.as_ref().unwrap_or(set); // The file's Title is File Info's; the page information names the document, as its tab does. let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.info_title().to_owned())); diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index 0650e3f0ef..b11cbc47d8 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -131,6 +131,37 @@ fn pdf_layers_import_back_as_layers() { } } +/// A hidden layer written as a PDF layer places the live effects of its instances' symbol art, +/// also in a PDF/A-2b file at PDF 1.4 whose 17,000 pt page has it written as PDF 1.6: the symbol's +/// square from x = 10 to 40, which a Transform effect moves 100 pt right, is written from x = 110 +/// to 140. +#[test] +fn a_hidden_layer_places_symbol_art_effects_when_a_long_page_raises_the_version() { + let mut d = Document::new(17_000.0, 300.0); + d.layers.clear(); + let mut square = rect(&mut d, 10.0, RED); + square.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: square.into() }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut l = Node::layer(d.alloc_id(), "Hidden", LayerColor::Preset(0)); + l.visible = false; + if let NodeKind::Layer { children, .. } = &mut l.kind { + children.push(instance.into()); + } + d.layers.push(l.into()); + for compatibility in [Compatibility::Pdf14, Compatibility::Pdf16] { + let settings = PdfSettings { standard: Standard::PdfA2b, compatibility, create_layers: true, ..PdfSettings::default() }; + let r = export_with_report(&d, &PdfOptions { settings, created: Some(1_791_200_000), ..Default::default() }).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.6"), "{compatibility:?}"); + let back = import_with_report(&r.bytes, &ImportOptions::default()).unwrap().document; + let hidden = back.layers.iter().find(|l| l.name.as_deref() == Some("Hidden")).expect("the hidden layer"); + let art = hidden.children().unwrap(); + assert_eq!(art.len(), 1, "{compatibility:?}"); + let b = art[0].geometric_bounds().unwrap(); + assert!((b.x0 - 110.0).abs() < 0.1 && (b.x1 - 140.0).abs() < 0.1, "{compatibility:?}: {b:?}"); + } +} + /// The rows of `nodes` in paint order, depth first: `depth name visible` for layers, `depth fill` /// for art. fn tree(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { From f4a5d65f6b31edd048a1f9c2c95f49b00b45dff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:55:52 -0800 Subject: [PATCH 24/33] Type: Glyphs panel menu draws the selected characters in an East Asian glyph form With Show East Asian Options on, the Glyphs panel menu lists Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms. Each form draws the selected characters with the font's OpenType feature for it (trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid). A form is checked when every selected character has it and disabled when none of the faces that draw the selected text, fallback faces included, has the feature. The form is a new character attribute, glyphForm, one form at a time (text.setFormat, text.setRangeStyle). It is saved only when set, character styles carry it, and runs that differ only in their form shape as one piece of text. SVG writes it in font-feature-settings; PDF draws the glyphs from the layout. --- crates/doc/src/lib.rs | 1 + crates/doc/src/text.rs | 4 +- crates/doc/src/text/char_style.rs | 94 +++++++++++ crates/engine/src/cmd/panelcmds.rs | 7 +- crates/engine/src/cmd/textedit.rs | 22 ++- crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/typecmd/area_tests.rs | 49 ++++++ crates/svg/src/css.rs | 4 + crates/text/src/features.rs | 3 + crates/text/src/fontdb/gsub.rs | 14 ++ crates/text/src/harakat.rs | 1 + crates/text/src/shape.rs | 10 +- crates/text/src/tests/typo.rs | 37 +++++ crates/ui-egui/src/panels/character.rs | 14 ++ crates/ui-egui/src/panels/glyphs.rs | 163 +++++++++++++++++++- docs/mcp.md | 21 +++ docs/target-app-parity.md | 1 + docs/type-parity.md | 1 + 18 files changed, 438 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c286492236..9389bdc965 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -118,6 +118,7 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption pub use style_libs::StyleLibrary; pub use text::FontHeightReference; pub use text::GlyphChoice; +pub use text::GlyphForm; pub use text::WarichuAlign; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c3c1464cfc..89388d8598 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -18,8 +18,8 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; pub use char_style::{ - CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, - WARICHU_SCALE, WarichuAlign, + CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, + WARICHU_LINES, WARICHU_SCALE, WarichuAlign, }; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index ef3cf29dc9..97f744dba8 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -205,6 +205,99 @@ pub struct CharStyle { /// default glyph otherwise. Saved only when set. #[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")] pub glyph_alternate: Option, + /// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East + /// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the + /// font's default glyphs. The text keeps its characters. Saved only when set. + /// + #[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")] + pub glyph_form: GlyphForm, +} + +/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's +/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time. +/// +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GlyphForm { + /// The font's default glyphs. + #[default] + Default, + /// Traditional forms (`trad`). + Traditional, + /// Expert forms (`expt`). + Expert, + /// JIS 2004 forms (`jp04`). + Jis04, + /// JIS 90 forms (`jp90`). + Jis90, + /// JIS 78 forms (`jp78`). + Jis78, + /// JIS 83 forms (`jp83`). + Jis83, + /// Monospaced full-width forms (`fwid`). + FullWidth, + /// Monospaced half-width forms (`hwid`). + HalfWidth, + /// Monospaced third-width forms (`twid`). + ThirdWidth, + /// Monospaced quarter-width forms (`qwid`). + QuarterWidth, +} + +impl GlyphForm { + /// Every form, in menu order, the default last. + pub const ALL: [GlyphForm; 11] = [ + GlyphForm::Traditional, + GlyphForm::Expert, + GlyphForm::Jis04, + GlyphForm::Jis90, + GlyphForm::Jis78, + GlyphForm::Jis83, + GlyphForm::FullWidth, + GlyphForm::HalfWidth, + GlyphForm::ThirdWidth, + GlyphForm::QuarterWidth, + GlyphForm::Default, + ]; + + /// The name files and commands give this form (as it is saved). + pub fn id(self) -> &'static str { + match self { + GlyphForm::Default => "default", + GlyphForm::Traditional => "traditional", + GlyphForm::Expert => "expert", + GlyphForm::Jis04 => "jis04", + GlyphForm::Jis90 => "jis90", + GlyphForm::Jis78 => "jis78", + GlyphForm::Jis83 => "jis83", + GlyphForm::FullWidth => "fullWidth", + GlyphForm::HalfWidth => "halfWidth", + GlyphForm::ThirdWidth => "thirdWidth", + GlyphForm::QuarterWidth => "quarterWidth", + } + } + + /// The form [`GlyphForm::id`] names; `None` for any other name. + pub fn from_id(id: &str) -> Option { + GlyphForm::ALL.into_iter().find(|f| f.id() == id) + } + + /// The OpenType feature that draws this form; `None` for the default glyphs. + pub fn feature(self) -> Option<&'static [u8; 4]> { + Some(match self { + GlyphForm::Default => return None, + GlyphForm::Traditional => b"trad", + GlyphForm::Expert => b"expt", + GlyphForm::Jis04 => b"jp04", + GlyphForm::Jis90 => b"jp90", + GlyphForm::Jis78 => b"jp78", + GlyphForm::Jis83 => b"jp83", + GlyphForm::FullWidth => b"fwid", + GlyphForm::HalfWidth => b"hwid", + GlyphForm::ThirdWidth => b"twid", + GlyphForm::QuarterWidth => b"qwid", + }) + } } /// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it @@ -586,6 +679,7 @@ impl Default for CharStyle { no_break: false, language: None, glyph_alternate: None, + glyph_form: GlyphForm::Default, } } } diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 2383d05a3a..b37121ad8f 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -592,6 +592,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "standardVerticalRoman", "noBreak", "digits", + "glyphForm", "fontHeightReference", "language", "fontAxes", @@ -626,6 +627,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let char_align = super::textedit::char_align_param(p, C)?; let char_direction = super::textedit::char_direction_param(p, C)?; let digits = super::textedit::digits_param(p, C)?; + let glyph_form = super::textedit::glyph_form_param(p, C)?; let language = super::textedit::language_param(p, C)?; let font_axes = super::textedit::font_axes_param(p, C)?; let font_height_reference = super::textedit::font_height_reference_param(p, C)?; @@ -796,6 +798,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = digits { st.digits = v; } + if let Some(v) = glyph_form { + st.glyph_form = v; + } if let Some(v) = &language { st.language.clone_from(v); } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 9ed7f3252b..ee843df8dd 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -473,6 +473,7 @@ pub(crate) struct CharChange { standard_vertical_roman: Option, no_break: Option, digits: Option, + glyph_form: Option, /// The language to set: a tag, or `None` for the default. language: Option>, font_axes: Option, @@ -571,6 +572,20 @@ pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result Result> { + use vectorcraft_doc::GlyphForm; + let Some(v) = p.get("glyphForm").filter(|v| !v.is_null()) else { return Ok(None) }; + let Some(f) = v.as_str().and_then(GlyphForm::from_id) else { + let ids: Vec = GlyphForm::ALL.iter().map(|f| format!("\"{}\"", f.id())).collect(); + return Err(bad(cmd, format!("`glyphForm` must be one of {}", ids.join(", ")))); + }; + Ok(Some(f)) +} + /// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to /// set ([`vectorcraft_doc::CharStyle::language`]: `None` inside for the default). pub(crate) fn language_param(p: &Value, cmd: &str) -> Result>> { @@ -840,6 +855,7 @@ impl CharChange { standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, + glyph_form: glyph_form_param(p, cmd)?, language: language_param(p, cmd)?, font_axes: font_axes_param(p, cmd)?, font_height_reference: font_height_reference_param(p, cmd)?, @@ -905,6 +921,7 @@ impl CharChange { && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() + && self.glyph_form.is_none() && self.language.is_none() && self.font_axes.is_none() && self.font_height_reference.is_none() @@ -1070,6 +1087,9 @@ impl CharChange { if let Some(v) = self.digits { st.digits = v; } + if let Some(v) = self.glyph_form { + st.glyph_form = v; + } if let Some(v) = self.font_height_reference { st.font_height_reference = v; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 17d453abf4..18f87d44f7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -228,6 +228,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("digits", json!(v.digits)), ("fontHeightReference", json!(v.font_height_reference)), ("language", json!(v.language)), + ("glyphForm", json!(v.glyph_form)), ] { m.insert(k.into(), x); } diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 36a0f965b7..ca9e4dc2ed 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1925,6 +1925,55 @@ fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() { assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman)); } +/// The East Asian glyph form (Glyphs panel menu) is one character attribute, `glyphForm`: one +/// form replaces another, "default" (Revert To Default Forms) takes it away, and it is saved +/// only when set. A call that changes nothing records no undo step, an unknown form is refused, +/// and character styles carry it. +#[test] +fn glyph_form_is_one_character_attribute_saved_only_when_set() { + use vectorcraft_doc::GlyphForm; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖芦"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let forms = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none()); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap(); + assert_eq!(forms(&s), [("亜".into(), GlyphForm::Default), ("唖".into(), GlyphForm::Jis78), ("芦".into(), GlyphForm::Default)]); + assert_eq!(serde_json::to_value(&runs(&s)[1].style).unwrap()["glyphForm"], "jis78"); + // Saved and reopened as it was. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), forms(&s)); + // Another form replaces it: one form at a time. + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth)); + let n = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n, "nothing changed, no undo step"); + for bad in [json!("jis2004"), json!(78), json!(true), json!("Traditional")] { + let e = s.execute("text.setFormat", &json!({"glyphForm": bad})).unwrap_err().to_string(); + assert!(e.contains("`glyphForm` must be one of \"traditional\""), "{bad}: {e}"); + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": bad})).is_err(), "{bad}"); + } + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth), "a refused call changes nothing"); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["glyphForm"], "fullWidth"); + s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default)); + assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none()); + // A character style carries the form. + s.execute("charStyle.new", &json!({"name": "Old forms", "attrs": {"glyphForm": "jis83"}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Old forms", "id": id})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Jis83)); + assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"glyphForm": "jis2004"}})).is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default)); +} + /// No Break is a character attribute, saved only when on. #[test] fn no_break_is_a_character_attribute_saved_only_when_on() { diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index f7e067aa30..5b0b921e32 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -194,6 +194,10 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { if st.proportional_metrics { v.push("\"palt\" 1".into()); } + // The East Asian glyph form: its one feature. + if let Some(tag) = st.glyph_form.feature().and_then(|t| std::str::from_utf8(t).ok()) { + v.push(format!("\"{tag}\" 1")); + } if !v.is_empty() { p.push(("font-feature-settings", v.join(", "))); } diff --git a/crates/text/src/features.rs b/crates/text/src/features.rs index 9f2b555e23..112573104d 100644 --- a/crates/text/src/features.rs +++ b/crates/text/src/features.rs @@ -319,6 +319,9 @@ impl OtFeatures { v.push(f(&t, u32::from(s.extra_values.get(i).copied().unwrap_or(0).max(1)))); } } + if let Some(tag) = st.glyph_form.feature() { + v.push(f(tag, true)); + } if self.vertical { // Not `vrt2`: its glyphs are already turned on their side, and the layout turns Latin // and digits itself (they would lie upside down, and tate-chu-yoko break). diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index 888c89ab09..bcc19f74b0 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -304,6 +304,20 @@ impl FontFace { self.gsub.get_or_init(|| GsubIndex::read(self)) } + /// Does the face's `GSUB` table have feature `tag` with at least one lookup? At most + /// [`MAX_FEATURES`] feature records are read; false when the face has no `GSUB` table or it + /// cannot be read. + pub fn has_substitution_feature(&self, tag: [u8; 4]) -> bool { + let Some(font) = self.skrifa() else { return false }; + let Some(features) = font.gsub().ok().and_then(|g| g.feature_list().ok()) else { return false }; + features + .feature_records() + .iter() + .take(MAX_FEATURES) + .filter(|r| r.feature_tag().to_be_bytes() == tag) + .any(|r| r.feature(features.offset_data()).is_ok_and(|f| !f.lookup_list_indices().is_empty())) + } + /// What the features `aalt`, `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, /// `jalt`, `nalt`, `ornm` and `titl` of the face's `GSUB` table substitute for glyph `gid`, in /// that order of features and within a feature in lookup order: the glyph of each single diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index 0f8ce4facd..ab5aa593bd 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -86,6 +86,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { no_break, language, glyph_alternate, + glyph_form: _, fill, stroke, stroke_width, diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index befcbed41f..88d40eb1e8 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1028,6 +1028,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { no_break, language, glyph_alternate, + // An OpenType feature over its own characters, like `features`. + glyph_form: _, } = a; // Keep PartialEq's non-reflexive behavior for ignored numeric fields, without cloning styles. let offsets = (standard_vertical_roman, tcy_up_down, tcy_left_right); @@ -1096,7 +1098,7 @@ pub(crate) fn warichu_alike(a: &CharStyle, b: &CharStyle) -> bool { /// character style's name, leading, baseline shift, rotation, Character Alignment, Character /// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its /// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]), -/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features (each run's apply to its own characters, as features +/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features /// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops /// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]). fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { @@ -1159,6 +1161,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { no_break, language, glyph_alternate, + // Applied as a feature over its run's own characters, with `features`. + glyph_form: _, } = a; *font_family == b.font_family && warichu_alike(a, b) @@ -1442,8 +1446,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let mut ranged = Vec::new(); for (r, run_style) in runs.get(source_runs.clone()).unwrap_or_default() { let (a, b) = (r.start.max(range.start), r.end.min(range.end)); - if run_style.features != base_style.features && a < b { - let own = variant(&CharStyle { features: run_style.features.clone(), ..base_style.clone() }); + if (run_style.features != base_style.features || run_style.glyph_form != base_style.glyph_form) && a < b { + let own = variant(&CharStyle { features: run_style.features.clone(), glyph_form: run_style.glyph_form, ..base_style.clone() }); ranged_features(base, &own, a..b, &mut ranged); } } diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 4790b642af..351c698451 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -2041,3 +2041,40 @@ fn soft_return_breaks_line_even_inside_no_break() { let lay = layout(db(), &t); assert_eq!(lay.lines.len(), 2, "soft return honors line break despite no_break"); } + +/// An East Asian glyph form (the Glyphs panel menu's Traditional Forms, JIS 78 Forms, …) draws +/// the characters with the font's glyphs of that form, and Default with its default glyphs. Needs +/// craft-fonts' BIZ UDMincho, which has traditional, expert, JIS 78, 83 and 90, full-width and +/// half-width forms and no JIS 04 forms (skipped without it). A form on one character of a run +/// changes that character only. +#[test] +fn glyph_forms_draw_the_fonts_east_asian_forms() { + use vectorcraft_doc::GlyphForm; + const FAMILY: &str = "BIZ UDMincho"; + if db().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + let st = |form| CharStyle { size: 20.0, font_family: FAMILY.into(), glyph_form: form, ..CharStyle::default() }; + let glyphs = |text: &str, form| layout(db(), &TextObject::point(Point::ZERO, text, st(form))).glyphs; + let gids = |text: &str, form| glyphs(text, form).iter().map(|g| g.gid).collect::>(); + for (form, text) in + [(GlyphForm::Traditional, "亜"), (GlyphForm::Expert, "唖"), (GlyphForm::Jis78, "唖"), (GlyphForm::Jis83, "芦"), (GlyphForm::Jis90, "芦")] + { + assert_ne!(gids(text, form), gids(text, GlyphForm::Default), "{form:?} {text}"); + } + // The font has no JIS 04 forms, so the characters keep their glyphs. + assert_eq!(gids("亜唖芦", GlyphForm::Jis04), gids("亜唖芦", GlyphForm::Default)); + // Full-width Latin takes a whole em, half-width punctuation half of one. + let advance = |text: &str, form| glyphs(text, form).first().map_or(0.0, |g| g.advance); + assert!(advance("A", GlyphForm::Default) < 15.0, "{}", advance("A", GlyphForm::Default)); + assert!((advance("A", GlyphForm::FullWidth) - 20.0).abs() < 0.01, "{}", advance("A", GlyphForm::FullWidth)); + assert!((advance("、", GlyphForm::Default) - 20.0).abs() < 0.01, "{}", advance("、", GlyphForm::Default)); + assert!((advance("、", GlyphForm::HalfWidth) - 10.0).abs() < 0.01, "{}", advance("、", GlyphForm::HalfWidth)); + // Traditional Forms on the middle character only. + let mut t = TextObject::point(Point::ZERO, "亜亜亜", st(GlyphForm::Default)); + edit::style_range(&mut t.runs, 3, 6, |s| s.glyph_form = GlyphForm::Traditional); + let ids: Vec = layout(db(), &t).glyphs.iter().map(|g| g.gid).collect(); + let (plain, traditional) = (gids("亜", GlyphForm::Default), gids("亜", GlyphForm::Traditional)); + assert_eq!(ids, [plain[0], traditional[0], plain[0]]); +} diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index d003fbcbce..904bb26dcb 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -108,6 +108,20 @@ pub(crate) fn shared(app: &VectorcraftApp, f: impl Fn(&CharStyle) shared_styles(app, |_, _, style, _| Some(f(style))) } +/// The fonts (family and style) of the character styles the panels act on ([`shared`]), each +/// once, in the order the runs come. +pub(crate) fn selected_fonts(app: &VectorcraftApp) -> Vec<(String, String)> { + let fonts = std::cell::RefCell::new(Vec::<(String, String)>::new()); + shared_styles(app, |_, _, style, _| { + let mut fonts = fonts.borrow_mut(); + if !fonts.iter().any(|(family, face)| *family == style.font_family && *face == style.font_style) { + fonts.push((style.font_family.clone(), style.font_style.clone())); + } + Some(()) + }); + fonts.into_inner() +} + /// Dimensional controls use document units and tolerate arithmetic roundoff when comparing /// compensated runs. Keep raw styles available to font/paragraph controls and style definitions, /// even if a collapsed affine prevents editing dimensions. diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 7c0a18d14f..4fbdc4ed9a 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -9,12 +9,14 @@ //! that glyph as one of its alternates in its word. A glyph no feature reaches whose name does //! not belong to another letter is applied as a glyph choice, which may not join. Other glyphs //! are drawn dimmed, and their tooltips say why they cannot be applied to the selection. +//! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph +//! form ([`glyph_form_items`]). use std::collections::HashMap; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; -use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, GlyphForm, NodeId, NodeKind}; use vectorcraft_geom::{Affine, BezPath, PathEl}; use vectorcraft_text::FontDb; @@ -781,11 +783,115 @@ fn zoom_button(ui: &mut Ui, id: &str, label: &str, tip: &str, enabled: bool) -> resp.on_hover_text(tl!(tip)).clicked() && enabled } -pub fn menu(_app: &mut VectorcraftApp, ui: &mut Ui) { +/// The menu label of East Asian glyph form `form` ([`GlyphForm::ALL`]). +fn glyph_form_label(form: GlyphForm) -> &'static str { + match form { + GlyphForm::Traditional => "Traditional Forms", + GlyphForm::Expert => "Expert Forms", + GlyphForm::Jis04 => "JIS 04 Forms", + GlyphForm::Jis90 => "JIS 90 Forms", + GlyphForm::Jis78 => "JIS 78 Forms", + GlyphForm::Jis83 => "JIS 83 Forms", + GlyphForm::FullWidth => "Monospaced Full-Width Forms", + GlyphForm::HalfWidth => "Monospaced Half-Width Forms", + GlyphForm::ThirdWidth => "Monospaced Third-Width Forms", + GlyphForm::QuarterWidth => "Monospaced Quarter-Width Forms", + GlyphForm::Default => "Revert To Default Forms", + } +} + +/// The ids of the faces that draw the characters [`glyph_form_items`] acts on: the faces the +/// fonts of their styles name, and the faces layout draws them with, fallback faces included: +/// the Type tool's selected range (every frame of its story after Select All in threaded text, +/// the whole text object at a caret), else every frame of the selected stories. Laid out once for +/// each document revision, selection and set of fonts while the menu is open, overflow text +/// included. +fn selection_faces(app: &VectorcraftApp, ui: &Ui) -> Vec { + type Key = (u64, u64, u64, Option<(NodeId, usize, usize)>, Vec); + let editing = super::character::text_editing(app).map(|(id, a, b)| (id, a.min(b), a.max(b))); + let Some(state) = app.session.active() else { return vec![] }; + let story = super::character::text_story(app); + let stories = match editing { + Some(_) => story.clone().unwrap_or_default(), + None => super::character::selected_stories(app), + }; + let db = FontDb::global(); + let key: Key = (state.uid, state.revision, db.generation(), editing, stories); + let slot = ui.scope_id().with("gl-form-faces"); + if let Some((cached, ids)) = ui.ctx().data(|d| d.get_temp::<(Key, Vec)>(slot)) + && cached == key + { + return ids; + } + let mut ids: Vec = + super::character::selected_fonts(app).iter().filter_map(|(family, style)| db.face(family, style)).map(|f| f.id()).collect(); + let mut add = |t: &vectorcraft_doc::TextObject, range: Option<(usize, usize)>| { + // Laid out as point type, so that text overflowing its area or path counts too. + let mut all = t.clone(); + all.kind = vectorcraft_doc::TextKind::Point; + for g in vectorcraft_text::layout(db, &all).glyphs { + // A glyph counts when its characters overlap the range (a ligature may start before it). + if range.is_none_or(|(a, b)| g.byte < b && g.byte + g.len.max(1) > a) && !ids.contains(&g.font_id) { + ids.push(g.font_id); + } + } + }; + let text = |id: NodeId| match state.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t), + _ => None, + }; + match (editing, story) { + // After Select All in threaded text: every frame of the story. + (Some(_), Some(frames)) => frames.into_iter().filter_map(text).for_each(|t| add(t, None)), + (Some((id, a, b)), None) => { + if let Some(t) = text(id) { + // A caret applies the form to all the text of the object. + add(t, (a < b).then_some((a, b))); + } + } + (None, _) => super::character::selected_story_texts(app).into_iter().for_each(|t| add(t, None)), + } + ui.ctx().data_mut(|d| d.insert_temp(slot, (key, ids.clone()))); + ids +} + +/// The East Asian glyph forms of the panel menu, with Show East Asian Options: each draws the +/// selected characters (all the text of the selected type objects without a Type tool range) in +/// one form of their font, and is checked when they all have it; a form none of the faces that +/// draw the selected text has a feature for ([`selection_faces`]) is disabled. Revert To Default +/// Forms draws the font's default glyphs. +/// Public behavior: [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) +/// (Replace Asian characters with a different glyph form). +fn glyph_form_items(app: &mut VectorcraftApp, ui: &mut Ui) { + let has = super::character::text_style(app).is_some(); + let db = FontDb::global(); + let faces: Vec<_> = selection_faces(app, ui).into_iter().filter_map(|id| db.face_by_id(id)).collect(); + let current = super::character::shared(app, |s| s.glyph_form); + for form in GlyphForm::ALL { + let enabled = match form.feature() { + Some(tag) => faces.iter().any(|f| f.has_substitution_feature(*tag)), + None => has, + }; + let checked = form != GlyphForm::Default && current == Some(form); + if form == GlyphForm::Default { + ui.separator(); + } + // Choosing the form every selected character already has changes nothing. + if menu_item(ui, tl!(glyph_form_label(form)), enabled, checked) && current != Some(form) { + super::character::format(app, json!({"glyphForm": form.id()})); + } + } +} + +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Use the Selected Text's Font"), true, false) { set_pstate::>(ui.ctx(), "gl-font", None); } ui.separator(); + if app.session.prefs.show_east_asian_options { + glyph_form_items(app, ui); + ui.separator(); + } for (i, (name, _, _)) in SUBSETS.iter().enumerate() { let cur: usize = pstate(ui.ctx(), "gl-subset"); if menu_item(ui, tl!(name), true, cur == i) { @@ -979,6 +1085,59 @@ mod tests { text_anchors(&shapes(ctx, app, vec![])).into_iter().map(|(t, _)| t).collect() } + /// With Show East Asian Options, the panel menu lists the East Asian glyph forms; choosing one + /// draws the Type tool's selected characters in it, checks it, and Revert To Default Forms + /// takes it away. A form the font has no feature for is disabled. The second half needs + /// craft-fonts' BIZ UDMincho, which has JIS 78 forms and no JIS 04 forms (skipped without it). + #[test] + fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { + let (mut app, id) = editing("亜唖"); + let ctx = egui::Context::default(); + let labels = |app: &mut VectorcraftApp| menu_texts(&ctx, app, vec![]).into_iter().map(|(t, _)| t).collect::>(); + let plain = |l: &String| l.trim_start_matches(['✓', ' ']).to_string(); + app.session.prefs.show_east_asian_options = false; + assert!(!labels(&mut app).iter().map(plain).any(|l| l == "JIS 78 Forms"), "hidden without Show East Asian Options"); + app.session.prefs.show_east_asian_options = true; + let shown: Vec = labels(&mut app).iter().map(plain).collect(); + for form in GlyphForm::ALL { + assert!(shown.iter().any(|l| l == glyph_form_label(form)), "{form:?} in {shown:?}"); + } + const FAMILY: &str = "BIZ UDMincho"; + if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + app.run("text.setRangeStyle", json!({"id": id, "font": FAMILY})).unwrap(); + let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap_or(0))).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), + _ => panic!("text"), + }; + select(&mut app, 3, 6); + choose(&ctx, &mut app, "JIS 78 Forms"); + assert_eq!(forms(&app), [("亜".to_string(), GlyphForm::Default), ("唖".to_string(), GlyphForm::Jis78)]); + assert!(labels(&mut app).iter().any(|l| l.starts_with('✓') && l.ends_with("JIS 78 Forms")), "checked"); + // A selection whose first font has no JIS 83 forms, and whose second one does, takes them. + let fallback = vectorcraft_text::FALLBACK_FAMILY; + if FontDb::global().face(fallback, "Regular").is_some_and(|f| !f.has_substitution_feature(*b"jp83")) { + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap(); + select(&mut app, 0, 6); + choose(&ctx, &mut app, "JIS 83 Forms"); + assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app)); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap(); + select(&mut app, 3, 6); + choose(&ctx, &mut app, "JIS 78 Forms"); + } + // Choosing it again changes nothing, and the font has no JIS 04 forms: that item is disabled. + let n = app.session.active().unwrap().history.undo.len(); + choose(&ctx, &mut app, "JIS 78 Forms"); + choose(&ctx, &mut app, "JIS 04 Forms"); + assert_eq!(app.session.active().unwrap().history.undo.len(), n); + assert_eq!(forms(&app)[1].1, GlyphForm::Jis78); + choose(&ctx, &mut app, "Revert To Default Forms"); + assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app)); + } + /// Show › Alternates for Current Selection lists the selected character's alternates from the /// font of its text, whatever font the panel browses; a double-click draws the character with /// one. A character without alternates, no selected character and a missing font each show a diff --git a/docs/mcp.md b/docs/mcp.md index 2e43c14d0e..8eca254a8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8965,6 +8965,27 @@ as outlines. {"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"tsume":50}}} ``` +## East Asian glyph forms + +`text.setFormat` and `text.setRangeStyle {glyphForm}` set the East Asian glyph form the characters are drawn in +([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): `"traditional"`, +`"expert"`, `"jis04"`, `"jis90"`, `"jis78"`, `"jis83"`, `"fullWidth"`, `"halfWidth"`, `"thirdWidth"` or +`"quarterWidth"`, which draw them with the font's OpenType feature `trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, +`fwid`, `hwid`, `twid` or `qwid` ([feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), +or `"default"`, the font's default glyphs. A character holds one form at a time, so setting one replaces another. The +text keeps its characters, and a character the font has no glyph of that form for keeps its own. Runs that differ only +in their form are shaped as one piece of text. The form is saved only when it is not `"default"`, character styles +carry it, PDF draws the glyphs the canvas draws, and live SVG text writes it in `font-feature-settings`. Another value +is refused with `` `glyphForm` must be one of "traditional", … ``. One undo step, and a `text.setFormat` call that +gives the form the characters already have records none. With Show East Asian Options on, the Glyphs panel menu lists +the ten forms and Revert To Default Forms: a form is checked when every selected character has it, choosing it again +does nothing, and it is disabled when none of the faces that draw the selected text, fallback faces included, has a +feature for it. + +```json +{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":0,"end":3,"glyphForm":"jis78"}}} +``` + ## Composite Fonts A composite font sets each class of character in a font of its own diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6375f3aa3..0a06409298 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1428,6 +1428,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. + The Glyphs panel menu (with the East Asian options) offers Traditional, Expert, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); each draws the selected characters with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`), one form at a time, and a form none of the faces that draw the selected text has a feature for is disabled. `text.setFormat` and `text.setRangeStyle {glyphForm}` set it; the native file, character styles, the canvas, PDF and SVG (`font-feature-settings`) keep it (`tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs` tests). Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. Character panel › Insert Aki Left and Insert Aki Right (with the East Asian options; `text.setFormat` or `text.setRangeStyle {akiLeft, akiRight}`, thousandths of an em from 0 to 1000, 0 by default) add space before and after each selected character, measured as tracking is, and kept as set through justification ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); before and after follow the reading order in vertical and right-to-left type, character styles carry both values (Character Style Options › Advanced Character Formats edits them), and a file holding a value outside the range opens with the nearer end. diff --git a/docs/type-parity.md b/docs/type-parity.md index 72b8bcfc9d..862e36ed3e 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -69,6 +69,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` | | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | +| CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for is disabled, and Revert To Default Forms draws the default glyphs. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form` | | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per class; SVG and legacy `.ai` write it as outlines. Not yet: custom character sets, the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | From 55615be12c45af749c077bb4b3a0e97654c05b4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:51:29 -0800 Subject: [PATCH 25/33] Export: an HP-GL plot of the art's bounds leaves out images in dynamic symbols A plot of the art's bounds now leaves placed images, objects at 0% opacity and unpainted paths out of the art of a dynamic symbol, as it does for other symbols. An object that an instance's fill, stroke or opacity makes the plot draw is measured for that instance only, and an instance whose symbol holds nothing else is left out, so a document with only such instances is refused. --- crates/engine/src/cmd/fileio/encode.rs | 223 ++++++++++++++++++--- crates/engine/src/cmd/fileio/tests_hpgl.rs | 84 ++++++++ docs/mcp.md | 5 +- 3 files changed, 281 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 0bb18483cb..c823b8866f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -2,13 +2,13 @@ //! (unknown keys are ignored, so one params object can carry the options of several formats). use std::borrow::Cow; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde::Deserialize; use serde::de::DeserializeOwned; use serde_json::Value; -use vectorcraft_doc::{Artboard, Document, Node, NodeKind}; +use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride}; use vectorcraft_geom::Rect; use vectorcraft_render::AntiAlias; use vectorcraft_render::encode::jpeg::{self, JpegOptions}; @@ -450,31 +450,85 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option { /// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden /// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out /// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol -/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole: -/// an instance can paint its objects, and finds them by their places in the art. +/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that +/// make the same appearance changes to its art are measured on a copy of the symbol of their own, +/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of +/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects +/// they change. fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option { - // The symbols instances show (the first of each name) that aren't dynamic. + // The symbols instances show (the first of each name). let mut names = HashSet::new(); - let shown: Vec<(usize, &vectorcraft_doc::Symbol)> = - doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect(); + let shown: Vec = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect(); + // The sets of appearance changes the drawn instances of each dynamic symbol make to its art; + // `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole. + let mut sets: HashMap<&str, Option>>> = + shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect(); + if !sets.is_empty() { + let mut walked = HashSet::new(); + for l in &doc.layers { + drawn_changes(doc, l, left_out, true, &mut walked, &mut sets); + } + } + // Each set of changes gets a copy of its symbol, appended after the symbols, which the instances + // that make those changes show instead. + let variant = |symbol: &str, n: &Node| -> Option { + let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?; + Some(format!("{symbol}\u{0}{k}")) + }; + let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new(); + let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| { + let mut d = doc.clone(); + for l in &mut d.layers { + if let Some(n) = remapped(l, &variant) { + *l = n; + } + } + for s in &mut d.symbols { + if let Some(n) = remapped(&s.art, &variant) { + s.art = n; + } + } + for i in &shown { + let Some(s) = d.symbols.get(*i).cloned() else { continue }; + for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() { + copies.push((d.symbols.len(), c.as_slice())); + d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() }); + } + } + d + }); + let src = remapped_doc.as_ref().unwrap_or(doc); + // The symbols to measure with the changes their instances make (`None` for a static symbol), + // without the dynamic symbols measured whole. + let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown + .iter() + .filter_map(|i| src.symbols.get(*i).map(|s| (*i, s))) + .filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some)) + .map(|(i, s)| (i, s.dynamic.then_some(&[][..]))) + .chain(copies.iter().map(|(i, c)| (*i, Some(*c)))) + .collect(); // The symbols whose art `left_out` leaves nothing of, those that only hold instances of such // symbols included. let mut empty: HashSet<&str> = HashSet::new(); - while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) { + while let Some(s) = entries.iter().find_map(|(i, c)| { + src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new())) + }) { empty.insert(&s.name); } let left_out = &|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n)); - let layers = hidden_nodes(&doc.layers, left_out); - let symbols: Vec<(usize, Arc)> = shown + let layers = hidden_nodes(&src.layers, left_out); + let symbols: Vec<(usize, Arc)> = entries .iter() - .filter(|(_, s)| !empty.contains(s.name.as_str())) - .filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art))) + .filter_map(|(i, c)| { + let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?; + without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art)) + }) .collect(); if layers.is_none() && symbols.is_empty() { - return vectorcraft_render::encode::art_bounds(doc); + return vectorcraft_render::encode::art_bounds(src); } - let mut d = doc.clone(); + let mut d = remapped_doc.unwrap_or_else(|| doc.clone()); if let Some(layers) = layers { d.layers = layers; } @@ -486,22 +540,126 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option Vec<&SymbolOverride> { + n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect() +} + +/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's +/// symbol and the instance) made an instance of that symbol; `None` when none is. +fn remapped(n: &Arc, variant: &dyn Fn(&str, &Node) -> Option) -> Option> { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let name = variant(symbol, n)?; + let mut m = (**n).clone(); + if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind { + *symbol = name; + } + return Some(Arc::new(m)); + } + let children = n.children()?; + let mut out: Option>> = None; + for (i, c) in children.iter().enumerate() { + if let Some(new) = remapped(c, variant) + && let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i) + { + *slot = new; + } + } + out.map(|c| { + let mut m = (**n).clone(); + if let Some(children) = m.children_mut() { + *children = c; + } + Arc::new(m) + }) +} + /// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a /// layer or a group holding only such objects (its clipping path among them when it clips). A /// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none -/// of these unless it is hidden or picked. -fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool { +/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes +/// an instance makes to it; `n` is at place `at`), each object is judged with those changes +/// ([`as_drawn`]). +fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec) -> bool { + let m = as_drawn(n, changed, at); !n.visible - || left_out(n) - || !has_effects(n) + || left_out(&m) + || !has_effects(&m) && n.extras().shaper.is_none() && match &n.kind { - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| { + at.push(i as u32); + let out = all_left_out(c, left_out, empty, changed, at); + at.pop(); + out + }), NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()), _ => false, } } +/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of +/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the +/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or +/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and +/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`. +fn drawn_changes<'a>( + doc: &'a Document, + n: &'a Node, + left_out: &dyn Fn(&Node) -> bool, + hidden: bool, + walked: &mut HashSet<&'a str>, + sets: &mut HashMap<&'a str, Option>>>, +) { + if hidden && !n.visible || left_out(n) { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + let changes = own_changes(n); + if let Some(entry) = sets.get_mut(symbol.as_str()) + && !changes.is_empty() + { + let full = match entry { + Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => { + list.push(changes); + false + } + Some(list) => !list.contains(&changes), + None => false, + }; + if full { + *entry = None; + } + } + if walked.insert(symbol.as_str()) + && let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) + { + drawn_changes(doc, &s.art, left_out, false, walked, sets); + } + } + for c in n.children().into_iter().flatten() { + drawn_changes(doc, c, left_out, hidden, walked, sets); + } +} + +/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of +/// appearance changes its instances make; a symbol whose instances make more sets is measured whole. +const MAX_ART_COPIES: usize = 64; + +/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an +/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not +/// dynamic (`changed` is `None`) and when no change names `at`. +fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> { + let here: Vec = + changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect(); + if here.is_empty() { + return Cow::Borrowed(n); + } + let mut m = n.clone(); + vectorcraft_doc::symbol_overrides::apply(&mut m, &here); + Cow::Owned(m) +} + /// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can /// take part in. fn has_effects(n: &Node) -> bool { @@ -511,25 +669,32 @@ fn has_effects(n: &Node) -> bool { /// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the /// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or /// group keeps its clipping path, its first object, and a Shaper group and a layer or group with -/// effects, fills or strokes of its own keep all they hold. -fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool) -> Option> { +/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol +/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place +/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves +/// an empty group in its place. +fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec) -> Option> { let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None }; - if has_effects(n) || n.extras().shaper.is_some() { + if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() { return None; } - let mut changed = false; + let mut taken = false; let kept: Vec> = children .iter() .enumerate() .filter_map(|(i, c)| { - if left_out(c) && !(*clip && i == 0) { - changed = true; - return None; - } - Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone())) + at.push(i as u32); + let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) { + taken = true; + changed.map(|_| Arc::new(Node::group(c.id, Vec::new()))) + } else { + Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone())) + }; + at.pop(); + out }) .collect(); - changed.then(|| { + taken.then(|| { let mut new = (**n).clone(); if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind { *children = kept; diff --git a/crates/engine/src/cmd/fileio/tests_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs index a7fe16690e..82957468d8 100644 --- a/crates/engine/src/cmd/fileio/tests_hpgl.rs +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -254,6 +254,90 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() { } } +/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as +/// well, until an instance paints the path, and a document whose only other visible art is an +/// instance of a dynamic symbol of an image is refused. +#[test] +fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() { + let mut s = two_boards(); + let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v)); + let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap(); + let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6) + }; + let printing = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.new", &json!({})).unwrap(); + let mut png = vec![]; + image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone(); + let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap(); + let before = bounds(&s); + let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone(); + let after = bounds(&s); + assert!(same(before, after), "{before:?} {after:?}"); + + // A change of the path's blending mode leaves it painting nothing; once the instance paints the + // path, the path is measured. + let art = s.doc().unwrap().doc.symbols[0].art.clone(); + let x0 = |c: &std::sync::Arc| c.visual_bounds().map_or(f64::MIN, |b| b.x0); + let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap(); + s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap(); + let blended = bounds(&s); + assert!(same(before, blended), "{before:?} {blended:?}"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap(); + let painted = bounds(&s); + assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}"); + // A later change to the same object, as a file can hold, takes the paint off again. + { + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let n = d.node_mut(id).unwrap(); + let mut overrides = n.extras().symbol_overrides.clone(); + overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() }); + n.extras_mut().symbol_overrides = overrides.clone(); + let taken_off = bounds(&s); + assert!(same(before, taken_off), "{before:?} {taken_off:?}"); + overrides.pop(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides; + } + // Another instance, far above, that doesn't paint the path is measured without it, whether or + // not the first one paints it. + let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone(); + let with_paint = bounds(&s); + s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap(); + let without_paint = bounds(&s); + assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = bounds(&s); + assert!(same(undone, with_paint), "{undone:?} {with_paint:?}"); + s.execute("select.set", &json!({"ids": [other]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + + s.execute("select.set", &json!({"ids": [inst]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap(); + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); + + // An instance that brings a group at 0% opacity back to full opacity still draws nothing when + // the group holds only an image. + let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone(); + let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone(); + s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone(); + let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().extras_mut().symbol_overrides = + [vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect(); + let e = plot(&mut s).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + /// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left /// out when it would take more cells than the effect makes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index cf41f3aaab..1e4591b906 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1091,8 +1091,9 @@ way. `document.exportPdf {useArtboards: false}` writes that one page as well, an art's bounds is measured without what the plot leaves out: non-printing layers, objects at 0% opacity, placed images, gradient meshes whose every point is at 0% opacity, and paths without effects whose fills and strokes paint nothing. An image or a mesh with a Crop Marks effect, or with a Vector Halftone effect that makes dots, is measured. -Such objects in the art of a symbol that is not dynamic are left out of its instances too, and an instance whose -symbol holds nothing else is left out. +Such objects in the art of a symbol are left out of its instances too, and an instance whose symbol holds nothing +else is left out. In the art of a dynamic symbol, an object that an instance's fill, stroke or opacity makes +the plot draw is measured. A document whose only visible art is left out is refused, and Export As refuses an HP-GL plot of it before the save dialog. A PDF of that page, from either command, carries no Preserve Editing data; when Preserve Editing is on (as it is in VectorCraft Default), the export comes back with a warning that says so. A `.ai` export with From 25b451acecb86991d1b45b8cbf103cb5dc47db87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:34:15 -0800 Subject: [PATCH 26/33] Effects: a clip group with its own paint exports the clip its clipping path's effects shape A clip group with a fill or stroke of its own and no geometry effect is baked through bake_pieces, which baked the clipping path like any other member instead of applying the geometry effects in it as the canvas clips by it. A compound clipping path whose member has a Transform effect with copies then baked into nested compound paths, and SVG, PDF and the other exports dropped the moved member and its copies from the clip. bake_pieces now applies with_clip_effects_applied to the clipping path first, as the plain clip group route already does. Clipping type keeps its own handling. --- crates/effects/src/bake.rs | 10 ++++--- crates/effects/src/tests/clipfx.rs | 42 ++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d648dd9258..b0c50d5042 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -476,14 +476,18 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { /// `m`, art evaluated from an object, with its children baked and then given ids of their own (the /// pieces copied from the source keep the source's ids until then). The pieces are baked with the -/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. +/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When +/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the +/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]). fn bake_pieces(d: &mut Document, mut m: Node) -> Node { let mut seen = std::collections::HashSet::from([m.id]); + let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_)))); let children = m.children().cloned().unwrap_or_default(); let children = children .into_iter() - .map(|c| { - let c = Arc::unwrap_or_clone(c); + .enumerate() + .map(|(i, c)| { + let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c)); let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c); fresh_ids(d, &mut c, &mut seen); Arc::new(c) diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 370f32fa81..bf63df61ab 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() { assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}"); } +#[test] +fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() { + // A clip group with a fill or a stroke of its own and no effects: the export turns its paint + // into art and still clips by the outline the canvas clips by, Transform copies included. + let items = [ + vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))), + vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)), + ]; + let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1})); + let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false})); + // A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`. + let ring = |hole_fx: Vec, own: Vec| { + let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default()); + let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default()); + hole.appearance.effects = hole_fx; + let mut c = + Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd }); + c.appearance.effects = own; + c + }; + let clips = [ + ("copies", clipping_path(2, vec![copies()])), + ("roughen", clipping_path(2, vec![roughen])), + ("a compound path's copies", ring(vec![], vec![copies()])), + ("a compound path member's copies", ring(vec![copies()], vec![])), + ]; + for item in &items { + for (what, clip) in &clips { + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + let live = clip_outline(clip).unwrap(); + let mut group = clip_group(1, clip.clone()); + group.appearance.items.push(item.clone()); + d.insert(Some(layer), 0, group).unwrap(); + let exported = clip_outline(&baked_clip(&d)).unwrap(); + assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes"); + } + } + let b = bounds(&clips[0].1); + assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}"); +} + #[test] fn nested_effects_apply_before_the_clip_groups() { // The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a From 2212af9653438b55104f37ed28f6762e578792f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:38:31 -0800 Subject: [PATCH 27/33] Text: a COLR fill that paints nothing keeps the clip around the glyph after it A fill in a glyph's clip marked the clip as filled before the fill was added. When the fill painted nothing (a palette index past the palette, or a radial gradient that draws no circle), the next glyph painted in the same clip became the clip's only child, and closing the clip kept that glyph on its own, so it drew outside the clip. The clip is now marked filled only when the fill adds the clip's first child, and a fill that adds nothing leaves the mark as it was. --- crates/text/src/colr.rs | 15 ++++++++---- crates/text/src/tests/colr.rs | 43 +++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 281ef8a65f..637dd9c243 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -508,12 +508,17 @@ impl ColorPainter for Tree<'_> { 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(); - } + let innermost = at + 1 == self.groups.len(); + let before = self.groups.last().map_or(0, |g| g.children.len()); self.fill_path(&clip, &brush); + // Flooded only when this fill added the group's first child. A fill that paints nothing + // adds none and leaves the flag as it was, so the clip stays around what comes after it. + if innermost + && let Some(g) = self.groups.last_mut() + && g.children.len() > before + { + g.flooded = before == 0; + } } /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index c6c4696f16..e59fb390c9 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -288,6 +288,49 @@ fn a_glyph_filled_with_one_colour_is_one_path() { assert_eq!(fill(only), Paint::solid(rgb(COLR_RED))); } +/// A fill that paints nothing (a palette index past the palette) followed by another glyph +/// inside the same glyph's clip keeps the clip: the second glyph is drawn clipped to the first, +/// not on its own. +#[test] +fn a_fill_that_paints_nothing_keeps_the_clip_around_the_glyph_after_it() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::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 paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O')); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into(); + colr.layer_list = Some(LayerList::new(2, vec![solid(99), ColrPaint::glyph(solid(0), gid('I'))])).into(); + let font = crate::test_fonts::colr_font_with("Colrtest Empty Fill", &colr).unwrap(); + let root = art(&font, COLOUR_CHAR); + let [clipped] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(clipped.kind, NodeKind::Group { clip: true, .. }), "the `O` still clips: {}", clipped.kind_label()); + let [clip, inner] = children(clipped) else { panic!("{:?}", children(clipped).iter().map(|c| c.kind_label()).collect::>()) }; + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{}", clip.kind_label()); + assert_eq!(fill(inner), Paint::solid(rgb(COLR_RED))); +} + +/// A fill that paints nothing after a colour flooding the glyph leaves it that glyph filled: +/// one path, as without the empty fill. +#[test] +fn a_fill_that_paints_nothing_after_a_flood_keeps_one_path() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::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 paint = ColrPaint::glyph(ColrPaint::colr_layers(2, 0), gid('O')); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(gid(COLOUR_CHAR), paint)])).into(); + colr.layer_list = Some(LayerList::new(2, vec![solid(0), solid(99)])).into(); + let font = crate::test_fonts::colr_font_with("Colrtest Flood Then Empty", &colr).unwrap(); + let root = art(&font, COLOUR_CHAR); + let [only] = children(&root) else { panic!("{:?}", children(&root).iter().map(|c| c.kind_label()).collect::>()) }; + 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] From c61d27b825f0eb38ec7a9f74a674551f1167ddf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:21:29 -0800 Subject: [PATCH 28/33] Metafile import: hidden WMF records leave the scale alone, and a far stroke keeps the strokes before it A WMF without a placeable box picks its scale from the map mode its drawing records are played in. Lines and shapes drawn under R2_NOP or R2_XORPEN, and PATBLT records the reader does not fill, no longer count, with the mix mode saved and restored with SAVEDC and RESTOREDC. An open stroke that reaches far outside the picture is left out before it joins the strokes waiting to be joined, so the strokes drawn before it are still added. --- crates/engine/tests/import_fuzz.rs | 10 ++++- crates/metafile/src/import/picture.rs | 61 +++++++++++++++++++++------ crates/metafile/src/tests/import.rs | 51 ++++++++++++++++++++++ 3 files changed, 107 insertions(+), 15 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index e22f8ac5cd..a768785abf 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2904,9 +2904,9 @@ fn arb_body() -> impl Strategy> { } /// WMF record functions VectorCraft reads, and one it doesn't. -const WMF_FUNCTIONS: [u16; 33] = [ +const WMF_FUNCTIONS: [u16; 35] = [ 0x0324, 0x0325, 0x0538, 0x041B, 0x0418, 0x061C, 0x0817, 0x081A, 0x0830, 0x0416, 0x0415, 0x02FA, 0x02FC, 0x02FB, 0x012D, 0x01F0, 0x0521, 0x0A32, - 0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0999, + 0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0103, 0x0104, 0x0999, ]; proptest! { @@ -2933,6 +2933,12 @@ proptest! { survive_metafile("WMF records", "x.wmf", &wmf_of(&records))?; } + #[test] + fn random_headerless_wmf_records_never_panic(records in prop::collection::vec((prop::sample::select(WMF_FUNCTIONS.to_vec()), arb_body()), 0..32)) { + // Without the placeable header, the map and mix modes the records set decide the scale. + survive_metafile("headerless WMF records", "x.wmf", &wmf_of(&records)[22..])?; + } + #[test] fn random_emf_plus_records_never_panic(records in prop::collection::vec((0x4001u16..0x403B, any::(), arb_body()), 0..32)) { // One comment of EMF+ records (type, flags, data) after an EmfPlusHeader. diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 5385d94153..03a2e5628e 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -56,25 +56,39 @@ const PT_PER_PX: f64 = 72.0 / 96.0; /// Points a millimetre. const PT_PER_MM: f64 = 72.0 / 25.4; -/// WMF records that draw and that `craft_metafile` plays: lines, shapes, text, PATBLT and bitmaps. -const WMF_DRAWS: [u16; 16] = - [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0521, 0x0538, 0x061C, 0x061D, 0x0817, 0x081A, 0x0830, 0x0940, 0x0A32, 0x0B41, 0x0F43]; +/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode +/// lets them draw. +const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830]; +/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode. +const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43]; +/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN +/// and R2_NOP. +const WMF_MIX_SKIPS: [u16; 2] = [7, 11]; +/// The mix mode a WMF starts in (R2_COPYPEN). +const WMF_MIX_START: u16 = 13; +/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode +/// allows), BLACKNESS and WHITENESS. +const PATCOPY: u32 = 0x00F0_0021; +const BLACKNESS: u32 = 0x0000_0042; +const WHITENESS: u32 = 0x00FF_0062; /// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those /// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in -/// decides; a file that draws nothing goes by its last mode. `start` is where the standard header -/// begins. +/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or +/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode. +/// `start` is where the standard header begins. fn wmf_metric(bytes: &[u8], start: usize) -> bool { let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); let Some(words) = start.checked_add(2).and_then(u16_at) else { return false }; let mut at = start.saturating_add(usize::from(words) * 2); let mut mode = 1; + let mut mix = WMF_MIX_START; let metric = |mode: u16| (2..=6).contains(&mode); // Drawing records played in a metric mode, and in any other. let (mut in_metric, mut in_other) = (0usize, 0usize); - // The modes SAVEDC kept, which RESTOREDC brings back as the reader does. - let mut saved: Vec = Vec::new(); + // The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does. + let mut saved: Vec<(u16, u16)> = Vec::new(); // The records as the reader walks them: it stops at the end record, a record shorter than its // header, one that runs past the file and a SAVEDC past its 1,024 levels. while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) { @@ -86,12 +100,14 @@ fn wmf_metric(bytes: &[u8], start: usize) -> bool { match function { // SETMAPMODE, when the record holds its mode. 0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode), + // SETROP2, when the record holds its mix mode. + 0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix), // SAVEDC. 0x001E => { if saved.len() >= SAVED_LEVELS { break; } - saved.push(mode); + saved.push((mode, mix)); } // RESTOREDC: a negative count pops that many levels, a positive one goes back to that // level. One that names no saved level changes nothing. @@ -99,20 +115,31 @@ fn wmf_metric(bytes: &[u8], start: usize) -> bool { let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes()))); let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; if let Some(level) = level - && let Some(m) = saved.get(level).copied() + && let Some((m, x)) = saved.get(level).copied() { mode = m; + mix = x; saved.truncate(level); } } - f if WMF_DRAWS.contains(&f) => { - if metric(mode) { + f => { + let draws = match f { + _ if WMF_DRAWS.contains(&f) => true, + _ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix), + // PATBLT: its raster operation, when the record holds one. + 0x061D => match u32_at(at + 6).filter(|_| size >= 10) { + Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix), + Some(rop) => rop == BLACKNESS || rop == WHITENESS, + None => false, + }, + _ => false, + }; + if draws && metric(mode) { in_metric += 1; - } else { + } else if draws { in_other += 1; } } - _ => {} } at = next; } @@ -401,6 +428,14 @@ impl Mapper { if let (None, Some((c, w))) = (fill, stroke) && !segs.iter().any(|s| matches!(s, Seg::Close)) { + // A stroke that reaches too far is left out here, before it joins the strokes + // waiting, so they are still added. + let half = f64::from(w) * self.k; + let half = if half > 0.0 && half.is_finite() { half / 2.0 } else { HAIRLINE / 2.0 }; + if !sane(bp.bounding_box().inflate(half, half)) { + self.flush(); + return self.warn(FAR_AWAY); + } let pen = Pen { color: c, width: w, line, even_odd, chain: chain.iter().map(|c| c.id).collect() }; let start = bp.elements().first().and_then(|e| match e { PathEl::MoveTo(p) => Some(*p), diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index a193997c4b..f5870c5f95 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -409,6 +409,57 @@ fn wmf_that_draws_in_a_metric_map_mode_and_restores_is_read_at_96_pixels_an_inch assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "{b:?}"); } +#[test] +fn wmf_records_the_mix_mode_keeps_from_drawing_do_not_set_its_scale() { + // A rectangle of 1440 units in MM_TEXT; then SAVEDC, MM_TWIPS, a mix mode and two records that + // draw nothing under it, and RESTOREDC. + let rect = (0x041B, le16(&[1440, 1440, 0, 0])); + let patblt = |rop: u32| (0x061D, [rop.to_le_bytes().to_vec(), le16(&[100, 100, 0, 0])].concat()); + let cases = [ + // R2_NOP and R2_XORPEN: rectangles draw nothing. + (11i16, [rect.clone(), rect.clone()]), + (7, [rect.clone(), rect.clone()]), + // R2_NOP: PATBLT with PATCOPY fills nothing. + (11, [patblt(0x00F0_0021), patblt(0x00F0_0021)]), + // R2_COPYPEN: PATBLT with DSTINVERT is not drawn. + (13, [patblt(0x0055_0009), patblt(0x0055_0009)]), + ]; + for (mix, hidden) in cases { + let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone()]; + records.extend([(0x001E, Vec::new()), (0x0103, le16(&[6])), (0x0104, le16(&[mix]))]); + records.extend(hidden); + records.push((0x0127, le16(&[-1]))); + let plain = hand_wmf(1440, 1440, &records)[22..].to_vec(); + let back = import(&plain).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "mix {mix}: {p:?}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "mix {mix}: {b:?}"); + } + // R2_NOP, then SAVEDC, R2_COPYPEN and RESTOREDC bring R2_NOP back: the MM_TWIPS rectangle after + // them draws nothing. + let mut records = vec![(0x020B, le16(&[0, 0])), (0x020C, le16(&[1440, 1440])), rect.clone(), (0x0104, le16(&[11]))]; + records.extend([(0x001E, Vec::new()), (0x0104, le16(&[13])), (0x0127, le16(&[-1])), (0x0103, le16(&[6])), rect]); + let back = import(&hand_wmf(1440, 1440, &records)[22..]).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "{p:?}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.width() - 72.0).abs() < 1e-4 && (b.height() - 72.0).abs() < 1e-4, "restored: {b:?}"); +} + +#[test] +fn a_stroke_that_reaches_too_far_leaves_the_strokes_before_it() { + // The black pen draws from (0, 500) to (100, 500), then on to a point far outside the picture. + let records = vec![(37, le(&[0x8000_0007u32 as i32])), (27, le(&[0, 500])), (54, le(&[100, 500])), (54, le(&[100_000_000, 500]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let p = paths(&back.document); + assert_eq!(p.len(), 1, "{p:?}"); + let mm = 72.0 / 25.4; + let b = p[0].geometric_bounds().unwrap(); + assert!((b.x0).abs() < 0.01 && (b.x1 - mm).abs() < 0.01 && (b.y0 - 5.0 * mm).abs() < 0.01, "{b:?}"); + assert!(back.warnings.iter().any(|w| w.contains("far outside")), "{:?}", back.warnings); +} + #[test] fn damaged_files_fail_or_import_partly() { let good = emf(&sample()).bytes; From b12c78a7312a1d15ef2a568c002cbefae2a8e36f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:46 -0800 Subject: [PATCH 29/33] Graphs: Outline Stroke and a graph left with only labels keep the plot in place - Outline Stroke on a graph's strokes, including Object > Expand with Stroke on, adjusts the bounds the graph keeps, the same way Create Outlines on its labels does. Before, the stroke outlines changed the bounds of the art without type, and the next redraw stretched the plot by the width the outlines added. - A graph that keeps `placedArt` and has no art other than type left is no longer measured on the bounds of all its art. A label edit on such a graph moved and stretched the plot at the next redraw; the plot now stays where it is. - A redraw no longer measures a move or scale on art that has no width or no height now, such as a graph left with one axis line. Before, the plot collapsed to no width. - A clipping group in a graph that holds type is measured on its clip when the clip does not depend on type, so moving art outside the clip does not change the bounds. Blends, envelopes and repeats are measured whole, as they are drawn. - The doc crate's helper is named `graph_art_without_type` and sits with the file's other free functions. - docs/mcp.md lists Outline Stroke and states that moving an outlined label, a swatch, an axis or a tick mark on its own can move or scale the plot, and that a graph left with only labels, or with art that has no width or height, does not follow a move. - Tests: a scale of the graph made before outlining a label, a move of a graph opened from `.ai` after its label is restyled and moved, Outline Stroke after a move, a graph left with only its labels or with one line, and clipping groups holding type. --- crates/doc/src/graph.rs | 65 ++++++----- crates/engine/src/cmd/graph/edit.rs | 36 ++++-- crates/engine/src/cmd/graph/tests.rs | 147 ++++++++++++++++++++++++- crates/engine/src/cmd/pathops.rs | 3 + crates/eps/src/import/ai/read/graph.rs | 2 +- docs/mcp.md | 12 +- 6 files changed, 222 insertions(+), 43 deletions(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 0b726cd0c1..a74f6d0f18 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -527,7 +527,7 @@ pub struct GraphSpec { /// Bounds of the art when it was last generated (detects moves/scales of the graph group). #[serde(skip_serializing_if = "Option::is_none")] pub placed: Option, - /// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph + /// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph /// group are measured on these when present; graphs saved without them are measured on [`Self::placed`]. #[serde(skip_serializing_if = "Option::is_none")] pub placed_art: Option, @@ -546,6 +546,43 @@ fn edge_to_edge_before_the_option() -> bool { true } +/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend +/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these. +pub fn graph_art_without_type(children: &[std::sync::Arc]) -> Option { + children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b)) +} + +/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A +/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the +/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them, +/// give their own bounds. +fn without_type(n: &crate::Node) -> (Option, bool) { + use crate::NodeKind::{Compound, Group, Layer, Text}; + if matches!(n.kind, Text(_)) { + return (None, true); + } + let children: &[std::sync::Arc] = match &n.kind { + Group { clip: true, children } | Layer { clip: true, children, .. } => children, + Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(), + _ => return (n.geometric_bounds(), false), + }; + let mut bounds: Option = None; + let mut had_type = false; + let mut clip_has_type = false; + let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. }); + for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) { + let (b, t) = without_type(c); + had_type |= t; + clip_has_type |= i == 0 && t; + bounds = match (bounds, b) { + (Some(a), Some(b)) => Some(a.union(b)), + (a, b) => a.or(b), + }; + } + let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. }); + if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) } +} + impl GraphSpec { /// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's. pub fn series_kind(&self, s: usize) -> GraphKind { @@ -614,32 +651,6 @@ impl GraphSpec { } } -/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend -/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these. -pub fn art_bounds(children: &[std::sync::Arc]) -> Option { - children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b)) -} - -/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type -/// gives its own bounds, so a clipping group gives the bounds of its clip. -fn art_bounds_of(n: &crate::Node) -> (Option, bool) { - if matches!(n.kind, crate::NodeKind::Text(_)) { - return (None, true); - } - let Some(children) = n.children() else { return (n.geometric_bounds(), false) }; - let mut bounds: Option = None; - let mut had_type = false; - for c in children { - let (b, t) = art_bounds_of(c); - had_type |= t; - bounds = match (bounds, b) { - (Some(a), Some(b)) => Some(a.union(b)), - (a, b) => a.or(b), - }; - } - if had_type { (bounds, true) } else { (n.geometric_bounds(), false) } -} - impl Default for GraphSpec { fn default() -> Self { Self { diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index e1c5c336b3..77ce7a7b2a 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -1,4 +1,4 @@ -use vectorcraft_doc::graph::art_bounds; +use vectorcraft_doc::graph::graph_art_without_type as art_bounds; use super::axis::{MAX_TICK_MARKS, count_given, one_line}; use super::data::apply_data; @@ -21,12 +21,16 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result>> { /// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now: /// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such -/// bounds with a width and a height, or has no art without type now. +/// bounds with a width and a height. `None` when the art measured has no width or no height now, or the graph keeps +/// bounds of its art without type and has no such art now. fn measured(n: &Node) -> Option<(Rect, Rect)> { let kept = n.extras().graph.as_deref()?; let c = n.children()?; - let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c)); - art.or_else(|| kept.placed.zip(children_bounds(c))) + let solid = |r: &Rect| r.width() > 1e-9 && r.height() > 1e-9; + match kept.placed_art.filter(solid) { + Some(placed) => art_bounds(c).filter(solid).map(|now| (placed, now)), + None => kept.placed.zip(children_bounds(c).filter(solid)), + } } /// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them. @@ -39,14 +43,28 @@ fn carried(r: Rect, from: Rect, to: Rect) -> Option { Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy)) } -/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to -/// [`keep_placed`] after an edit that changes a graph's art without moving the graph. +/// The graphs holding objects `ids`, that are among them or that are inside them, each with the bounds of its art +/// without type and of all its art. Give them to [`keep_placed`] after an edit that changes a graph's art without +/// moving the graph. pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option, Option)> { - let mut out: Vec<(NodeId, Option, Option)> = vec![]; + let is_graph = |n: &Node| n.extras().graph.is_some(); + let mut found: Vec = vec![]; for id in ids { let Some(chain) = d.ancestry(*id) else { continue }; - let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some())); - let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue }; + found.extend(chain.iter().rev().copied().find(|a| d.node(*a).is_some_and(is_graph))); + if let Some(n) = d.node(*id) { + n.walk(&mut |c| { + if is_graph(c) { + found.push(c.id); + } + }); + } + } + let mut out: Vec<(NodeId, Option, Option)> = vec![]; + for gid in found { + if out.iter().any(|(o, ..)| *o == gid) { + continue; + } let children = d.node(gid).and_then(Node::children); out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)))); } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c160a78833..7737477ae9 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5796,6 +5796,141 @@ fn outlining_a_graphs_labels_leaves_the_plot_in_place() { let moved = spec(&s, id).rect; assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}"); assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); + // A scale of the graph made before outlining is still followed. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 50, "origin": [moved.x0, moved.y0]})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q3").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let scaled = spec(&s, id).rect; + assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}"); + assert!((scaled.width() - 1.5 * rect.width()).abs() < 1e-6 && (scaled.height() - 0.5 * rect.height()).abs() < 1e-6, "{scaled:?}"); +} + +/// Outline Stroke on a graph's strokes leaves the plot where it is when the graph is drawn again, and a move of the +/// graph made before it is still followed. +#[test] +fn outlining_a_graphs_strokes_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 20, "dy": 10})).unwrap(); + s.execute("object.path.outlineStroke", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 20.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 10.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); +} + +/// A graph left with only its labels, or with its labels and one vertical line, leaves the plot where it is when it is +/// drawn again after a label edit. +#[test] +fn a_graph_left_with_only_its_labels_leaves_the_plot_in_place() { + for keep_a_line in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let (mut art, mut line) = (vec![], None); + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| { + if n.children().is_none() && !matches!(n.kind, NodeKind::Text(_)) { + let vertical = n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0); + if keep_a_line && vertical && line.is_none() { + line = n.geometric_bounds(); + } else { + art.push(n.id.0); + } + } + }); + assert!(!art.is_empty() && line.is_some() == keep_a_line); + s.execute("select.set", &json!({"ids": art})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let left = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert_eq!(vectorcraft_doc::graph::graph_art_without_type(left.children().unwrap()), line, "{:#?}", left.children()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 20})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "keeping a line: {keep_a_line}"); + } +} + +/// A graph saved without the bounds of its art without type, left with one vertical line, keeps its plot's size when +/// it is drawn again. +#[test] +fn a_graph_saved_with_only_its_whole_bounds_and_left_with_a_line_keeps_its_plot() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut old = spec(&s, id); + old.placed_art = None; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old)); + let (mut art, mut line) = (vec![], None); + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| { + if n.children().is_none() { + let vertical = !matches!(n.kind, NodeKind::Text(_)) && n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0); + if vertical && line.is_none() { + line = Some(n.id); + } else { + art.push(n.id.0); + } + } + }); + assert!(line.is_some()); + s.execute("select.set", &json!({"ids": art})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect); +} + +/// The bounds a graph measures moves on take a clipping group holding type at the bounds of its clip, so art outside the +/// clip does not change them; a clipping group whose clip is type is measured on its other art. +#[test] +fn a_clipping_group_holding_type_is_measured_on_its_clip() { + use std::sync::Arc; + use vectorcraft_doc::graph::graph_art_without_type as measure; + use vectorcraft_geom::Affine; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label: Arc = + group(&n, "Legend").children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().clone(); + let mut paths = vec![]; + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) { + paths.push(c.clone()); + } + }); + let (clip, art) = (Arc::new(paths[0].clone()), paths[1].clone()); + let clipped = |dx: f64, first: Arc, second: Arc| { + let mut far = art.clone(); + far.transform(Affine::translate((dx, 0.0)), false); + let mut g = vectorcraft_doc::Node::group(NodeId(999_999), vec![first, second, Arc::new(far)]); + if let NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + measure(&[Arc::new(g)]) + }; + assert_eq!(clipped(500.0, clip.clone(), label.clone()), clip.geometric_bounds()); + assert_eq!(clipped(500.0, clip.clone(), label.clone()), clipped(900.0, clip.clone(), label.clone())); + // A clip that is type leaves the other art to measure. + assert_ne!(clipped(500.0, label.clone(), clip.clone()), clipped(900.0, label.clone(), clip.clone())); + // A clip that is a clipping group holding type in its clipped art is measured on its own clip. + let mut inner = vectorcraft_doc::Node::group(NodeId(999_998), vec![clip.clone(), label.clone()]); + if let NodeKind::Group { clip, .. } = &mut inner.kind { + *clip = true; + } + let inner = Arc::new(inner); + assert_eq!(clipped(500.0, inner.clone(), label.clone()), clip.geometric_bounds()); + assert_eq!(clipped(500.0, inner.clone(), label.clone()), clipped(900.0, inner.clone(), label.clone())); + // A blend holding type is measured whole, as it is drawn. + let blend = vectorcraft_doc::Node::new(NodeId(999_997), NodeKind::Blend { children: vec![clip.clone(), label.clone()], spec: Box::default() }); + assert_eq!(measure(&[Arc::new(blend.clone())]), blend.geometric_bounds()); } /// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art. @@ -7113,9 +7248,17 @@ fn a_graph_opened_from_ai_measures_moves_without_its_labels() { assert_eq!((graphs.len(), labels.len()), (1, 1)); let (id, label) = (graphs[0], labels[0]); let before = spec(&s, id); - assert!(before.placed_art.is_some()); s.execute("select.set", &json!({"ids": [label.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 30})).unwrap(); s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap(); s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); - assert_eq!(spec(&s, id).rect, before.rect); + let rect = spec(&s, id).rect; + assert_eq!(rect, before.rect, "after restyling and moving a label"); + // A move of the whole opened graph is still followed. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 15, "dy": 25})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 15.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 25.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 878b3743cf..b5267fa990 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -1188,6 +1188,8 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { let roots = selected_roots(s)?; let ids = s.edit("Outline Stroke", |d, sel| { let before = d.clone(); + // Outlining the strokes in a graph does not move or scale its plot at the next redraw. + let graphs = super::graph::graphs_holding(d, &roots); // A dimension selected with the art it measures keeps its own lines: it is out of the // document while the art is outlined. let lifted = super::dimension::lift(d, &roots); @@ -1207,6 +1209,7 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result { if changed == 0 || (kept && d.layers == before.layers) { return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into())); } + super::graph::keep_placed(d, &graphs); sel.set(new_sel.iter().copied()); Ok(new_sel) })?; diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 9fb60408c7..609713fe16 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -631,7 +631,7 @@ impl<'a> Reader<'a> { let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false }; spec.series_paints = paints; spec.placed = Some(placed); - spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c)); + spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c)); tag_series(art, &tags); art.extras_mut().graph = Some(Box::new(spec)); true diff --git a/docs/mcp.md b/docs/mcp.md index fc03d070b6..76d53693cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -870,10 +870,14 @@ leaves room for a legend label's stored indents, spacing and leading. When a graph is drawn again, its plot moves and scales with any move or scale of the graph made since it was last drawn. The graph saves the bounds of its art other than type as `placedArt` (and the bounds of all of its art as -`placed`), and measures the move or scale on those. Changing the size, indents or spacing of the labels, moving a label -on its own and `type.createOutlines` on labels do not move or scale the plot. A graph opened from a `.ai` file saves -`placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is measured on -`placed`. +`placed`), and measures the move or scale on those. Changing the size or indents of the labels, moving a label on its +own, `type.createOutlines` on labels and `object.path.outlineStroke` on the graph's strokes do not move or scale the +plot. Outlined labels are no longer type: moving one of them on its own, like moving a swatch, an axis or a tick mark on +its own, can move or scale the plot at the next redraw. When all of a graph's art other than type has been deleted, or +the art measured has no width or no height, a redraw leaves the plot where it is and does not follow a move or scale of +the graph. A graph opened from a `.ai` file +saves `placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is +measured on `placed`. The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, and the paint, stroke, gradient and transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its From f1cffdd8c09340edb069d17f3da8575b29b9c1e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:46:56 -0800 Subject: [PATCH 30/33] Type: a warichu line holds the ascent and descent of its outer block lines A block's line took the tallest ascent and deepest descent of its characters, or the height of the stack's em boxes, whichever was larger. The top block line's characters reach above the stack by their ascent past the em box, and the bottom line's below it by their descent, so with a wide Line Gap the line was too short for them. The line's ascent and descent now also take in each character's reach from its own block line's baseline. --- crates/text/src/layout/warichu.rs | 11 ++++++++--- crates/text/src/tests/warichu.rs | 18 ++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/text/src/layout/warichu.rs b/crates/text/src/layout/warichu.rs index dd816599c6..b68b69efd9 100644 --- a/crates/text/src/layout/warichu.rs +++ b/crates/text/src/layout/warichu.rs @@ -287,6 +287,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool)) let rtl = !vertical && g.first().is_some_and(|gl| gl.level.is_rtl()); let (inset, outset) = if rtl { (after, before) } else { (before, after) }; let length = inset + block + outset; + // How far the glyphs reach above and below the line's baseline, each from its block line's + // baseline. + let above = g.iter().zip(&places).map(|(gl, p)| gl.ascent - p.1).fold(0.0, f64::max); + let below = g.iter().zip(&places).map(|(gl, p)| gl.descent + p.1).fold(0.0, f64::max); let glyphs = g.len(); for (i, (gl, (along, across, advance))) in g.iter_mut().zip(places).enumerate() { let em = gl.face.units_per_em() * gl.sy / r; @@ -300,9 +304,10 @@ fn place_block(g: &mut [SGlyph], s: &WariStyle, (vertical, whole): (bool, bool)) if i + 1 < glyphs { gl.keeps_next = true; } - // The line keeps the height of the block's own size, and holds the whole stack. - gl.ascent = (ascent / r).max(-top); - gl.descent = (descent / r).max(bottom); + // The line keeps the height of the block's own size, and holds the whole stack with each + // block line's glyphs. + gl.ascent = (ascent / r).max(-top).max(above); + gl.descent = (descent / r).max(bottom).max(below); if s.auto_leading { gl.leading /= r; } diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index 6aee052cbd..cbefb86bb5 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -626,6 +626,24 @@ fn a_block_of_several_fonts_keeps_the_tallest_of_them() { assert!(first_short.0 >= plain[pair.0].0 - 1e-6 && first_short.1 >= deepest - 1e-6, "{first_short:?} {plain:?}"); } +/// The line holds each block line's characters at their own height: with a wide Line Gap, the +/// ascent of the top block line's characters and the descent of the bottom one's stay inside the +/// line. +#[test] +fn a_wide_line_gap_keeps_the_outer_block_lines_inside_the_line() { + let small = layout(db(), &point("x", style(10.0))); + let (ascent, descent) = (small.lines[0].ascent, small.lines[0].descent); + for lines in [2, 3] { + let l = layout(db(), &with_block("cdefgh", CharStyle { warichu_lines: lines, warichu_gap: 20.0, ..marked(20.0) })); + let line = &l.lines[0]; + let block = &l.glyphs[2..8]; + let top = block.iter().map(|g| g.origin.y).fold(f64::INFINITY, f64::min); + let bottom = block.iter().map(|g| g.origin.y).fold(f64::NEG_INFINITY, f64::max); + assert!(line.baseline - line.ascent <= top - ascent + 1e-6, "{lines}: {} {} {top} {ascent}", line.baseline, line.ascent); + assert!(line.baseline + line.descent >= bottom + descent - 1e-6, "{lines}: {} {} {bottom} {descent}", line.baseline, line.descent); + } +} + /// Warichu Settings on characters not marked Warichu leave their shaping alone: "fi" keeps its /// ligature when only the f has other settings. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index fc03d070b6..b37f162985 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8965,7 +8965,8 @@ Options). Warichu characters are set at `warichuScale` percent of their size (10 `warichuLines` lines (a whole number from 1 to 6, default 2) inside their line: one above the other in horizontal type and side by side across the column in vertical type, the first line above or to the right. `warichuGap` is the space between the lines in points (0 to 100, default 0, document points as `baselineShift`). The stack is centered across the -line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size. +line on the center of the line's ideographic em box, and the line keeps the height of the characters' own size, or +more when the stack needs it: the line's ascent and descent take in the characters of the outer lines. A stretch of warichu characters is one block that takes the settings of its first character; a character with other settings, another size or the other kind of leading (Auto or a number) starts a new one, and a tab, a forced line break or a tate-chu-yoko character ends it. In vertical type a character marked `tateChuYoko` as well is set as tate-chu-yoko at its own size, and two or three digits From dfc4db7a9b0f78040e24b4aa82eb3d6bdde6658d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:47:36 -0800 Subject: [PATCH 31/33] Docs: Japanese messages are listed as partial, with the report's count The Japanese row in docs/localization-parity.md said every message is translated, and the Japanese catalog line in docs/target-app-parity.md said 38 messages were missing, one of them waiting on #7214, which has merged. On main the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks. Both lines now give the counted rows and the report's count, and name the open pull requests that translate part of them. --- docs/localization-parity.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 1fededbc4e..ca00fd7816 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -37,7 +37,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 6,825 rows, 1,036 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 60 missing menu strings, 35 `tl!` literals and 13 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,508; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | -| Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | +| Japanese | `ja` | 4,004 / 4,020 (99.6%) | partial (3,562 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks; open #7116 and #7211 translate 35 of them) | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (3,563 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 52 missing messages for it, which open #7116, #7211 and #7378 translate) | Latin | contributor-written, not reviewed | full | — (review) | | Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) | | Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | dialogs and tooltips all; messages partial (1,750 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 1,875 messages without a Vietnamese row, 53 of which open #7211, #7378, #7405 and #7434 translate) | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a1f7c81b8..6d3bf3b90f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -917,7 +917,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,421 `@msg` rows: a row for each status and error message the untranslated report (`untranslated_report`) finds in the sources, except 38. The report lists those 38 for Japanese: the 36 composite font errors that open #7211 translates, `select a path` (open #7214) and the justification order error (open #7116). The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. + - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). - The Hungarian catalog (`crates/ui-egui/src/i18n/hu.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,444 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Hungarian messages: the composite font, justification order and connect end errors that open #7211, #7116 and #7330 translate, and two messages that no catalog has a row for. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. From a750c997be40fb14e1c7aa083c78fffc925f0e0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:51:09 -0800 Subject: [PATCH 32/33] Scripts: a property name converted from an object stays counted while its getter or setter runs A computed name such as o[key], where key's toString returns a rope, is flattened into a copy that only native code held. A getter or setter that started a collection dropped that copy from the heap estimate, so the live heap could pass the limit by one name per nested access. Indexed reads, ++ and -- on an indexed property, and Object.defineProperty now keep the converted name reachable while the accessor runs. --- crates/js/src/builtins/object.rs | 9 +++++---- crates/js/src/interp.rs | 18 ++++++++++++++---- crates/js/src/text_tests.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 969a9c6094..af41bb7782 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -166,10 +166,11 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - let k = interp.to_key(&arg(args, 1))?; - let desc = to_desc(interp, &arg(args, 2))?; - let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))?; + interp.with_key(&arg(args, 1), |interp, k| { + let desc = to_desc(interp, &arg(args, 2))?; + let roots = desc_values(&desc); + interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + })?; Ok(Value::Object(o)) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index edc5282fe5..aa4a4c5c78 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1779,8 +1779,7 @@ impl Interp { return self.replace(2, v); } self.check_coercible(&base, &[])?; - let name = self.to_key(&k)?; - let v = self.get_value(&base, &name)?; + let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } } @@ -1852,8 +1851,7 @@ impl Interp { return self.replace(2, Value::Number(if prefix { new } else { old })); } self.check_coercible(&base, &[])?; - let name = self.to_key(&k)?; - let r = self.inc_property(&base, name, prefix, dec)?; + let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; self.replace(2, r) } @@ -2670,6 +2668,18 @@ impl Interp { } } + /// Runs `f` with the property name [`Self::to_key`] makes from `v`. A name converted from a + /// value that is not a string is kept reachable while `f` runs, so a collection that a getter + /// or setter starts still counts its units. + pub(crate) fn with_key(&mut self, v: &Value, f: impl FnOnce(&mut Self, Key) -> JsResult) -> JsResult { + let name = self.to_key(v)?; + if matches!(v, Value::String(_)) { + return f(self, name); + } + let root = Value::String(Str::from_rc(name.clone())); + self.rooted(&[root], |i| f(i, name)) + } + /// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that /// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays /// rooted while the copy is reserved; everything else the caller still needs must be diff --git a/crates/js/src/text_tests.rs b/crates/js/src/text_tests.rs index 01fc613cc3..62145b6117 100644 --- a/crates/js/src/text_tests.rs +++ b/crates/js/src/text_tests.rs @@ -434,6 +434,32 @@ fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() { assert_eq!(realm.run(src), Ok(JsValue::Number(1.0))); } +#[test] +fn a_computed_key_stays_counted_while_its_getter_or_setter_runs() { + // `o` has an accessor named by a flat string of 131,073 units. `key`'s toString returns a new + // rope with the same units, so using `key` as a name makes a second flat copy, which must stay + // counted while an accessor makes a third. The heap has room for one more copy, not two. + let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \ + function copy() { var g = f('g'); g[0]; return 1; } var o = {}, name = f('k'); name[0]; \ + Object.defineProperty(o, name, { get: copy, set: copy }); \ + var key = { toString: function () { return f('k'); } }; 0"; + let realm = || { + let mut realm = Realm::with_options(Options::default(), Limits::default()); + assert_eq!(realm.run(build), Ok(JsValue::Number(0.0))); + let interp = realm.interp(); + interp.collect_garbage(); + let copy = crate::heap::string_bytes(131_073); + interp.limits.heap_bytes = interp.heap.bytes + copy + copy / 2; + interp.reset_gc_threshold(); + realm + }; + assert_eq!(realm().run("o[name]"), Ok(JsValue::Number(1.0)), "the accessor's own copy fits"); + for read in ["o[key]", "o[key] = 1", "o[key]++", "Object.defineProperty({}, key, { get value() { return copy(); } })"] { + let result = realm().run(read); + assert!(matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{read}: {result:?}"); + } +} + #[test] fn compiling_a_pattern_counts_against_the_heap() { let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length"; From aaae3fe37844964cb215ccb0ff5b09c49499ed05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:43:04 -0800 Subject: [PATCH 33/33] Links: rows of images in stored brush art show their thumbnails The panel collected the objects for its nested rows from the document as it is between commands, where the art of the stored brushes is not set, so rows whose owner is a brush found no object and drew a blank thumbnail. When an id is not found otherwise, the panel now sets that art on a copy of the document, as links.list does, and collects the objects from it. A recheck of the files at the same revision keeps the objects collected before. --- crates/ui-egui/src/panels/links.rs | 63 +++++++++++++++++++----- crates/ui-egui/src/panels/tests_links.rs | 22 +++++++++ 2 files changed, 73 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index f9d9b524c9..2c54b843a8 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -92,28 +92,29 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< let mut c: Cache = pstate(ctx, "links-cache"); let stale = c.key != key || now - c.at > RECHECK; if stale { + let same_doc = c.key == key; c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; (c.key, c.at) = (key, now); // One pass over the stored art for the rows outside the layer tree and the objects whose - // opacity masks hold them, not one per frame. - let mut want: std::collections::HashSet = c.list["links"] + // opacity masks hold them, not one per frame. An object in the layer tree is looked up by + // its index when drawn. + let doc = app.session.active().map(|st| &st.doc); + let want: std::collections::HashSet = c.list["links"] .as_array() .into_iter() .flatten() .filter(|r| nested_row(r)) .flat_map(|r| [r["id"].as_u64(), r["owner"]["maskOf"].as_u64()]) .flatten() + .filter(|id| doc.is_some_and(|d| d.node(NodeId(*id)).is_none())) .collect(); - c.nested.clear(); - if !want.is_empty() - && let Some(st) = app.session.active() - { - st.doc.visit_stored_arcs(|n, place| { - if !place.in_layers() && want.remove(&n.id.0) { - c.nested.push((n.id.0, std::sync::Arc::clone(n))); - } - }); - c.nested.sort_by_key(|(id, _)| *id); + // The same revision keeps the objects collected for it, so their thumbnails are not drawn + // again each time the files are looked at. + if !(same_doc && want.iter().all(|id| c.nested_node(*id).is_some())) { + c.nested = match doc { + Some(d) if !want.is_empty() => stored_objects(d, want), + _ => vec![], + }; } } let want = first.filter(|_| o.info); @@ -126,6 +127,44 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< Some(c) } +/// The objects of `doc` outside the layer tree whose ids are in `want`, sorted by id. The art of +/// the stored brushes is set on `doc` only while a command uses it ([`Document::mounted_art`]), so +/// when an id is not found otherwise that art is set on a copy of `doc`, which gives its objects +/// the ids `links.list` reports for them. +/// +/// [`Document::mounted_art`]: vectorcraft_doc::Document::mounted_art +pub(super) fn stored_objects( + doc: &vectorcraft_doc::Document, + mut want: std::collections::HashSet, +) -> Vec<(u64, std::sync::Arc)> { + let mut out = vec![]; + collect_stored(doc, &mut want, &mut out); + if !want.is_empty() && doc.mounted_art.is_empty() { + let art = vectorcraft_brush::stored_art::StoredArt::read(doc); + if !art.is_empty() { + let mut d = doc.clone(); + art.mount(&mut d); + collect_stored(&d, &mut want, &mut out); + } + } + out.sort_by_key(|(id, _)| *id); + out +} + +/// Adds the objects of `d` outside the layer tree whose ids are in `want` to `out`, taking their +/// ids out of `want`. +fn collect_stored( + d: &vectorcraft_doc::Document, + want: &mut std::collections::HashSet, + out: &mut Vec<(u64, std::sync::Arc)>, +) { + d.visit_stored_arcs(|n, place| { + if !place.in_layers() && want.remove(&n.id.0) { + out.push((n.id.0, std::sync::Arc::clone(n))); + } + }); +} + /// The ids of the selected image objects and placed documents. fn selected_images(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 6b773e9d3b..45c1fc3b04 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -230,6 +230,28 @@ fn a_mask_rows_tooltip_names_its_object_inside_a_symbol() { assert!(text.iter().any(|t| t.contains(&want)), "{want} in {text:?}"); } +/// The row of an image in a stored brush's art finds its object for the thumbnail, though that art +/// is set on the document only while a command uses it. +#[test] +fn a_row_in_a_stored_brushs_art_finds_its_object() { + let dir = Folder::new("brush-art"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let leaf = dir.file("leaf.png", &png(30, 20)); + let id = app.run("file.place", json!({"path": leaf, "at": [100, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("brush.new", json!({"type": "scatter", "name": "Leaf", "ids": [id]})).unwrap(); + app.run("edit.clear", json!({"ids": [id]})).unwrap(); + let list = app.run("links.list", json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "leaf.png").unwrap_or_else(|| panic!("{list}")).clone(); + assert_eq!(row["owner"]["kind"], "brush", "{list}"); + let row = row["id"].as_u64().unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!(doc.mounted_art.is_empty(), "the brush's art is not set on the document"); + let found = super::links::stored_objects(doc, [row].into()); + assert_eq!(found.iter().map(|(id, _)| *id).collect::>(), [row]); + assert!(matches!(found[0].1.kind, vectorcraft_doc::NodeKind::Image(_)), "{:?}", found[0].1.kind); +} + #[test] fn an_empty_document_shows_how_to_add_images() { let mut app = VectorcraftApp::new(Session::new(), Default::default());